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;
26 use Friendica\App\BaseURL;
27 use Friendica\Content\Pager;
28 use Friendica\Core\Hook;
29 use Friendica\Core\Logger;
30 use Friendica\Core\Protocol;
31 use Friendica\Core\Session;
32 use Friendica\Core\System;
33 use Friendica\Core\Worker;
34 use Friendica\Database\DBA;
36 use Friendica\Model\Notify\Type;
37 use Friendica\Network\HTTPException;
38 use Friendica\Network\Probe;
39 use Friendica\Protocol\Activity;
40 use Friendica\Protocol\ActivityPub;
41 use Friendica\Protocol\DFRN;
42 use Friendica\Protocol\Diaspora;
43 use Friendica\Protocol\OStatus;
44 use Friendica\Protocol\Salmon;
45 use Friendica\Util\DateTimeFormat;
46 use Friendica\Util\Images;
47 use Friendica\Util\Network;
48 use Friendica\Util\Proxy;
49 use Friendica\Util\Strings;
52 * functions for interacting with a contact
57 * @deprecated since version 2019.03
58 * @see User::PAGE_FLAGS_NORMAL
60 const PAGE_NORMAL = User::PAGE_FLAGS_NORMAL;
62 * @deprecated since version 2019.03
63 * @see User::PAGE_FLAGS_SOAPBOX
65 const PAGE_SOAPBOX = User::PAGE_FLAGS_SOAPBOX;
67 * @deprecated since version 2019.03
68 * @see User::PAGE_FLAGS_COMMUNITY
70 const PAGE_COMMUNITY = User::PAGE_FLAGS_COMMUNITY;
72 * @deprecated since version 2019.03
73 * @see User::PAGE_FLAGS_FREELOVE
75 const PAGE_FREELOVE = User::PAGE_FLAGS_FREELOVE;
77 * @deprecated since version 2019.03
78 * @see User::PAGE_FLAGS_BLOG
80 const PAGE_BLOG = User::PAGE_FLAGS_BLOG;
82 * @deprecated since version 2019.03
83 * @see User::PAGE_FLAGS_PRVGROUP
85 const PAGE_PRVGROUP = User::PAGE_FLAGS_PRVGROUP;
93 * TYPE_UNKNOWN - unknown type
95 * TYPE_PERSON - the account belongs to a person
96 * Associated page types: PAGE_NORMAL, PAGE_SOAPBOX, PAGE_FREELOVE
98 * TYPE_ORGANISATION - the account belongs to an organisation
99 * Associated page type: PAGE_SOAPBOX
101 * TYPE_NEWS - the account is a news reflector
102 * Associated page type: PAGE_SOAPBOX
104 * TYPE_COMMUNITY - the account is community forum
105 * Associated page types: PAGE_COMMUNITY, PAGE_PRVGROUP
107 * TYPE_RELAY - the account is a relay
108 * This will only be assigned to contacts, not to user accounts
111 const TYPE_UNKNOWN = -1;
112 const TYPE_PERSON = User::ACCOUNT_TYPE_PERSON;
113 const TYPE_ORGANISATION = User::ACCOUNT_TYPE_ORGANISATION;
114 const TYPE_NEWS = User::ACCOUNT_TYPE_NEWS;
115 const TYPE_COMMUNITY = User::ACCOUNT_TYPE_COMMUNITY;
116 const TYPE_RELAY = User::ACCOUNT_TYPE_RELAY;
135 * @param array $fields Array of selected fields, empty for all
136 * @param array $condition Array of fields for condition
137 * @param array $params Array of several parameters
141 public static function selectToArray(array $fields = [], array $condition = [], array $params = [])
143 return DBA::selectToArray('contact', $fields, $condition, $params);
147 * @param array $fields Array of selected fields, empty for all
148 * @param array $condition Array of fields for condition
149 * @param array $params Array of several parameters
153 public static function selectFirst(array $fields = [], array $condition = [], array $params = [])
155 $contact = DBA::selectFirst('contact', $fields, $condition, $params);
161 * Insert a row into the contact table
162 * Important: You can't use DBA::lastInsertId() after this call since it will be set to 0.
164 * @param array $fields field array
165 * @param bool $on_duplicate_update Do an update on a duplicate entry
167 * @return boolean was the insert successful?
170 public static function insert(array $fields, bool $on_duplicate_update = false)
172 $ret = DBA::insert('contact', $fields, $on_duplicate_update);
173 $contact = DBA::selectFirst('contact', ['nurl', 'uid'], ['id' => DBA::lastInsertId()]);
174 if (!DBA::isResult($contact)) {
179 // Search for duplicated contacts and get rid of them
180 self::removeDuplicates($contact['nurl'], $contact['uid']);
186 * @param integer $id Contact ID
187 * @param array $fields Array of selected fields, empty for all
188 * @return array|boolean Contact record if it exists, false otherwise
191 public static function getById($id, $fields = [])
193 return DBA::selectFirst('contact', $fields, ['id' => $id]);
197 * Fetches a contact by a given url
199 * @param string $url profile url
200 * @param boolean $update true = always update, false = never update, null = update when not found or outdated
201 * @param array $fields Field list
202 * @param integer $uid User ID of the contact
203 * @return array contact array
205 public static function getByURL(string $url, $update = null, array $fields = [], int $uid = 0)
207 if ($update || is_null($update)) {
208 $cid = self::getIdForURL($url, $uid, $update);
213 $contact = self::getById($cid, $fields);
214 if (empty($contact)) {
220 // Add internal fields
222 if (!empty($fields)) {
223 foreach (['id', 'updated', 'network'] as $internal) {
224 if (!in_array($internal, $fields)) {
225 $fields[] = $internal;
226 $removal[] = $internal;
231 // We first try the nurl (http://server.tld/nick), most common case
232 $options = ['order' => ['id']];
233 $contact = DBA::selectFirst('contact', $fields, ['nurl' => Strings::normaliseLink($url), 'uid' => $uid, 'deleted' => false], $options);
235 // Then the addr (nick@server.tld)
236 if (!DBA::isResult($contact)) {
237 $contact = DBA::selectFirst('contact', $fields, ['addr' => str_replace('acct:', '', $url), 'uid' => $uid, 'deleted' => false], $options);
240 // Then the alias (which could be anything)
241 if (!DBA::isResult($contact)) {
242 // The link could be provided as http although we stored it as https
243 $ssl_url = str_replace('http://', 'https://', $url);
244 $condition = ['`alias` IN (?, ?, ?) AND `uid` = ? AND NOT `deleted`', $url, Strings::normaliseLink($url), $ssl_url, $uid];
245 $contact = DBA::selectFirst('contact', $fields, $condition, $options);
248 if (!DBA::isResult($contact)) {
252 // Update the contact in the background if needed
253 if ((($contact['updated'] < DateTimeFormat::utc('now -7 days')) || empty($contact['avatar'])) &&
254 in_array($contact['network'], Protocol::FEDERATED)) {
255 Worker::add(PRIORITY_LOW, "UpdateContact", $contact['id'], ($uid == 0 ? 'force' : ''));
258 // Remove the internal fields
259 foreach ($removal as $internal) {
260 unset($contact[$internal]);
267 * Fetches a contact for a given user by a given url.
268 * In difference to "getByURL" the function will fetch a public contact when no user contact had been found.
270 * @param string $url profile url
271 * @param integer $uid User ID of the contact
272 * @param boolean $update true = always update, false = never update, null = update when not found or outdated
273 * @param array $fields Field list
274 * @return array contact array
276 public static function getByURLForUser(string $url, int $uid = 0, $update = false, array $fields = [])
279 $contact = self::getByURL($url, $update, $fields, $uid);
280 if (!empty($contact)) {
281 if (!empty($contact['id'])) {
282 $contact['cid'] = $contact['id'];
289 $contact = self::getByURL($url, $update, $fields);
290 if (!empty($contact['id'])) {
292 $contact['zid'] = $contact['id'];
298 * Tests if the given contact is a follower
300 * @param int $cid Either public contact id or user's contact id
301 * @param int $uid User ID
303 * @return boolean is the contact id a follower?
304 * @throws HTTPException\InternalServerErrorException
305 * @throws \ImagickException
307 public static function isFollower($cid, $uid)
309 if (self::isBlockedByUser($cid, $uid)) {
313 $cdata = self::getPublicAndUserContacID($cid, $uid);
314 if (empty($cdata['user'])) {
318 $condition = ['id' => $cdata['user'], 'rel' => [self::FOLLOWER, self::FRIEND]];
319 return DBA::exists('contact', $condition);
323 * Tests if the given contact url is a follower
325 * @param string $url Contact URL
326 * @param int $uid User ID
328 * @return boolean is the contact id a follower?
329 * @throws HTTPException\InternalServerErrorException
330 * @throws \ImagickException
332 public static function isFollowerByURL($url, $uid)
334 $cid = self::getIdForURL($url, $uid, false);
340 return self::isFollower($cid, $uid);
344 * Tests if the given user follow the given contact
346 * @param int $cid Either public contact id or user's contact id
347 * @param int $uid User ID
349 * @return boolean is the contact url being followed?
350 * @throws HTTPException\InternalServerErrorException
351 * @throws \ImagickException
353 public static function isSharing($cid, $uid)
355 if (self::isBlockedByUser($cid, $uid)) {
359 $cdata = self::getPublicAndUserContacID($cid, $uid);
360 if (empty($cdata['user'])) {
364 $condition = ['id' => $cdata['user'], 'rel' => [self::SHARING, self::FRIEND]];
365 return DBA::exists('contact', $condition);
369 * Tests if the given user follow the given contact url
371 * @param string $url Contact URL
372 * @param int $uid User ID
374 * @return boolean is the contact url being followed?
375 * @throws HTTPException\InternalServerErrorException
376 * @throws \ImagickException
378 public static function isSharingByURL($url, $uid)
380 $cid = self::getIdForURL($url, $uid, false);
386 return self::isSharing($cid, $uid);
390 * Get the basepath for a given contact link
392 * @param string $url The contact link
393 * @param boolean $dont_update Don't update the contact
395 * @return string basepath
396 * @throws HTTPException\InternalServerErrorException
397 * @throws \ImagickException
399 public static function getBasepath($url, $dont_update = false)
401 $contact = DBA::selectFirst('contact', ['id', 'baseurl'], ['uid' => 0, 'nurl' => Strings::normaliseLink($url)]);
402 if (!DBA::isResult($contact)) {
406 if (!empty($contact['baseurl'])) {
407 return $contact['baseurl'];
408 } elseif ($dont_update) {
412 // Update the existing contact
413 self::updateFromProbe($contact['id'], '', true);
415 // And fetch the result
416 $contact = DBA::selectFirst('contact', ['baseurl'], ['id' => $contact['id']]);
417 if (empty($contact['baseurl'])) {
418 Logger::info('No baseurl for contact', ['url' => $url]);
422 Logger::info('Found baseurl for contact', ['url' => $url, 'baseurl' => $contact['baseurl']]);
423 return $contact['baseurl'];
427 * Check if the given contact url is on the same server
429 * @param string $url The contact link
431 * @return boolean Is it the same server?
433 public static function isLocal($url)
435 return Strings::compareLink(self::getBasepath($url, true), DI::baseUrl());
439 * Check if the given contact ID is on the same server
441 * @param string $url The contact link
443 * @return boolean Is it the same server?
445 public static function isLocalById(int $cid)
447 $contact = DBA::selectFirst('contact', ['url', 'baseurl'], ['id' => $cid]);
448 if (!DBA::isResult($contact)) {
452 if (empty($contact['baseurl'])) {
453 $baseurl = self::getBasepath($contact['url'], true);
455 $baseurl = $contact['baseurl'];
458 return Strings::compareLink($baseurl, DI::baseUrl());
462 * Returns the public contact id of the given user id
464 * @param integer $uid User ID
466 * @return integer|boolean Public contact id for given user id
469 public static function getPublicIdByUserId($uid)
471 $self = DBA::selectFirst('contact', ['url'], ['self' => true, 'uid' => $uid]);
472 if (!DBA::isResult($self)) {
475 return self::getIdForURL($self['url'], 0, false);
479 * Returns the contact id for the user and the public contact id for a given contact id
481 * @param int $cid Either public contact id or user's contact id
482 * @param int $uid User ID
484 * @return array with public and user's contact id
485 * @throws HTTPException\InternalServerErrorException
486 * @throws \ImagickException
488 public static function getPublicAndUserContacID($cid, $uid)
490 if (empty($uid) || empty($cid)) {
494 $contact = DBA::selectFirst('contact', ['id', 'uid', 'url'], ['id' => $cid]);
495 if (!DBA::isResult($contact)) {
499 // We quit when the user id don't match the user id of the provided contact
500 if (($contact['uid'] != $uid) && ($contact['uid'] != 0)) {
504 if ($contact['uid'] != 0) {
505 $pcid = Contact::getIdForURL($contact['url'], 0, false, ['url' => $contact['url']]);
509 $ucid = $contact['id'];
511 $pcid = $contact['id'];
512 $ucid = Contact::getIdForURL($contact['url'], $uid, false);
515 return ['public' => $pcid, 'user' => $ucid];
519 * Returns contact details for a given contact id in combination with a user id
521 * @param int $cid A contact ID
522 * @param int $uid The User ID
523 * @param array $fields The selected fields for the contact
525 * @return array The contact details
529 public static function getContactForUser($cid, $uid, array $fields = [])
531 $contact = DBA::selectFirst('contact', $fields, ['id' => $cid, 'uid' => $uid]);
533 if (!DBA::isResult($contact)) {
541 * Block contact id for user id
543 * @param int $cid Either public contact id or user's contact id
544 * @param int $uid User ID
545 * @param boolean $blocked Is the contact blocked or unblocked?
548 public static function setBlockedForUser($cid, $uid, $blocked)
550 $cdata = self::getPublicAndUserContacID($cid, $uid);
555 if ($cdata['user'] != 0) {
556 DBA::update('contact', ['blocked' => $blocked], ['id' => $cdata['user'], 'pending' => false]);
559 DBA::update('user-contact', ['blocked' => $blocked], ['cid' => $cdata['public'], 'uid' => $uid], true);
563 * Returns "block" state for contact id and user id
565 * @param int $cid Either public contact id or user's contact id
566 * @param int $uid User ID
568 * @return boolean is the contact id blocked for the given user?
571 public static function isBlockedByUser($cid, $uid)
573 $cdata = self::getPublicAndUserContacID($cid, $uid);
578 $public_blocked = false;
580 if (!empty($cdata['public'])) {
581 $public_contact = DBA::selectFirst('user-contact', ['blocked'], ['cid' => $cdata['public'], 'uid' => $uid]);
582 if (DBA::isResult($public_contact)) {
583 $public_blocked = $public_contact['blocked'];
587 $user_blocked = $public_blocked;
589 if (!empty($cdata['user'])) {
590 $user_contact = DBA::selectFirst('contact', ['blocked'], ['id' => $cdata['user'], 'pending' => false]);
591 if (DBA::isResult($user_contact)) {
592 $user_blocked = $user_contact['blocked'];
596 if ($user_blocked != $public_blocked) {
597 DBA::update('user-contact', ['blocked' => $user_blocked], ['cid' => $cdata['public'], 'uid' => $uid], true);
600 return $user_blocked;
604 * Ignore contact id for user id
606 * @param int $cid Either public contact id or user's contact id
607 * @param int $uid User ID
608 * @param boolean $ignored Is the contact ignored or unignored?
611 public static function setIgnoredForUser($cid, $uid, $ignored)
613 $cdata = self::getPublicAndUserContacID($cid, $uid);
618 if ($cdata['user'] != 0) {
619 DBA::update('contact', ['readonly' => $ignored], ['id' => $cdata['user'], 'pending' => false]);
622 DBA::update('user-contact', ['ignored' => $ignored], ['cid' => $cdata['public'], 'uid' => $uid], true);
626 * Returns "ignore" state for contact id and user id
628 * @param int $cid Either public contact id or user's contact id
629 * @param int $uid User ID
631 * @return boolean is the contact id ignored for the given user?
634 public static function isIgnoredByUser($cid, $uid)
636 $cdata = self::getPublicAndUserContacID($cid, $uid);
641 $public_ignored = false;
643 if (!empty($cdata['public'])) {
644 $public_contact = DBA::selectFirst('user-contact', ['ignored'], ['cid' => $cdata['public'], 'uid' => $uid]);
645 if (DBA::isResult($public_contact)) {
646 $public_ignored = $public_contact['ignored'];
650 $user_ignored = $public_ignored;
652 if (!empty($cdata['user'])) {
653 $user_contact = DBA::selectFirst('contact', ['readonly'], ['id' => $cdata['user'], 'pending' => false]);
654 if (DBA::isResult($user_contact)) {
655 $user_ignored = $user_contact['readonly'];
659 if ($user_ignored != $public_ignored) {
660 DBA::update('user-contact', ['ignored' => $user_ignored], ['cid' => $cdata['public'], 'uid' => $uid], true);
663 return $user_ignored;
667 * Set "collapsed" for contact id and user id
669 * @param int $cid Either public contact id or user's contact id
670 * @param int $uid User ID
671 * @param boolean $collapsed are the contact's posts collapsed or uncollapsed?
674 public static function setCollapsedForUser($cid, $uid, $collapsed)
676 $cdata = self::getPublicAndUserContacID($cid, $uid);
681 DBA::update('user-contact', ['collapsed' => $collapsed], ['cid' => $cdata['public'], 'uid' => $uid], true);
685 * Returns "collapsed" state for contact id and user id
687 * @param int $cid Either public contact id or user's contact id
688 * @param int $uid User ID
690 * @return boolean is the contact id blocked for the given user?
691 * @throws HTTPException\InternalServerErrorException
692 * @throws \ImagickException
694 public static function isCollapsedByUser($cid, $uid)
696 $cdata = self::getPublicAndUserContacID($cid, $uid);
703 if (!empty($cdata['public'])) {
704 $public_contact = DBA::selectFirst('user-contact', ['collapsed'], ['cid' => $cdata['public'], 'uid' => $uid]);
705 if (DBA::isResult($public_contact)) {
706 $collapsed = $public_contact['collapsed'];
714 * Returns a list of contacts belonging in a group
720 public static function getByGroupId($gid)
725 $stmt = DBA::p('SELECT `group_member`.`contact-id`, `contact`.*
727 INNER JOIN `group_member`
728 ON `contact`.`id` = `group_member`.`contact-id`
730 AND `contact`.`uid` = ?
731 AND NOT `contact`.`self`
732 AND NOT `contact`.`deleted`
733 AND NOT `contact`.`blocked`
734 AND NOT `contact`.`pending`
735 ORDER BY `contact`.`name` ASC',
740 if (DBA::isResult($stmt)) {
741 $return = DBA::toArray($stmt);
749 * Creates the self-contact for the provided user id
752 * @return bool Operation success
753 * @throws HTTPException\InternalServerErrorException
755 public static function createSelfFromUserId($uid)
757 // Only create the entry if it doesn't exist yet
758 if (DBA::exists('contact', ['uid' => $uid, 'self' => true])) {
762 $user = DBA::selectFirst('user', ['uid', 'username', 'nickname'], ['uid' => $uid]);
763 if (!DBA::isResult($user)) {
767 $return = DBA::insert('contact', [
768 'uid' => $user['uid'],
769 'created' => DateTimeFormat::utcNow(),
771 'name' => $user['username'],
772 'nick' => $user['nickname'],
773 'photo' => DI::baseUrl() . '/photo/profile/' . $user['uid'] . '.jpg',
774 'thumb' => DI::baseUrl() . '/photo/avatar/' . $user['uid'] . '.jpg',
775 'micro' => DI::baseUrl() . '/photo/micro/' . $user['uid'] . '.jpg',
778 'url' => DI::baseUrl() . '/profile/' . $user['nickname'],
779 'nurl' => Strings::normaliseLink(DI::baseUrl() . '/profile/' . $user['nickname']),
780 'addr' => $user['nickname'] . '@' . substr(DI::baseUrl(), strpos(DI::baseUrl(), '://') + 3),
781 'request' => DI::baseUrl() . '/dfrn_request/' . $user['nickname'],
782 'notify' => DI::baseUrl() . '/dfrn_notify/' . $user['nickname'],
783 'poll' => DI::baseUrl() . '/dfrn_poll/' . $user['nickname'],
784 'confirm' => DI::baseUrl() . '/dfrn_confirm/' . $user['nickname'],
785 'poco' => DI::baseUrl() . '/poco/' . $user['nickname'],
786 'name-date' => DateTimeFormat::utcNow(),
787 'uri-date' => DateTimeFormat::utcNow(),
788 'avatar-date' => DateTimeFormat::utcNow(),
796 * Updates the self-contact for the provided user id
799 * @param boolean $update_avatar Force the avatar update
800 * @throws HTTPException\InternalServerErrorException
802 public static function updateSelfFromUserID($uid, $update_avatar = false)
804 $fields = ['id', 'name', 'nick', 'location', 'about', 'keywords', 'avatar',
805 'xmpp', 'contact-type', 'forum', 'prv', 'avatar-date', 'url', 'nurl', 'unsearchable',
806 'photo', 'thumb', 'micro', 'addr', 'request', 'notify', 'poll', 'confirm', 'poco'];
807 $self = DBA::selectFirst('contact', $fields, ['uid' => $uid, 'self' => true]);
808 if (!DBA::isResult($self)) {
812 $fields = ['nickname', 'page-flags', 'account-type'];
813 $user = DBA::selectFirst('user', $fields, ['uid' => $uid]);
814 if (!DBA::isResult($user)) {
818 $fields = ['name', 'photo', 'thumb', 'about', 'address', 'locality', 'region',
819 'country-name', 'pub_keywords', 'xmpp', 'net-publish'];
820 $profile = DBA::selectFirst('profile', $fields, ['uid' => $uid]);
821 if (!DBA::isResult($profile)) {
825 $file_suffix = 'jpg';
827 $fields = ['name' => $profile['name'], 'nick' => $user['nickname'],
828 'avatar-date' => $self['avatar-date'], 'location' => Profile::formatLocation($profile),
829 'about' => $profile['about'], 'keywords' => $profile['pub_keywords'],
830 'contact-type' => $user['account-type'],
831 'xmpp' => $profile['xmpp']];
833 $avatar = Photo::selectFirst(['resource-id', 'type'], ['uid' => $uid, 'profile' => true]);
834 if (DBA::isResult($avatar)) {
835 if ($update_avatar) {
836 $fields['avatar-date'] = DateTimeFormat::utcNow();
839 // Creating the path to the avatar, beginning with the file suffix
840 $types = Images::supportedTypes();
841 if (isset($types[$avatar['type']])) {
842 $file_suffix = $types[$avatar['type']];
845 // We are adding a timestamp value so that other systems won't use cached content
846 $timestamp = strtotime($fields['avatar-date']);
848 $prefix = DI::baseUrl() . '/photo/' .$avatar['resource-id'] . '-';
849 $suffix = '.' . $file_suffix . '?ts=' . $timestamp;
851 $fields['photo'] = $prefix . '4' . $suffix;
852 $fields['thumb'] = $prefix . '5' . $suffix;
853 $fields['micro'] = $prefix . '6' . $suffix;
855 // We hadn't found a photo entry, so we use the default avatar
856 $fields['photo'] = DI::baseUrl() . '/images/person-300.jpg';
857 $fields['thumb'] = DI::baseUrl() . '/images/person-80.jpg';
858 $fields['micro'] = DI::baseUrl() . '/images/person-48.jpg';
861 $fields['avatar'] = DI::baseUrl() . '/photo/profile/' .$uid . '.' . $file_suffix;
862 $fields['forum'] = $user['page-flags'] == User::PAGE_FLAGS_COMMUNITY;
863 $fields['prv'] = $user['page-flags'] == User::PAGE_FLAGS_PRVGROUP;
864 $fields['unsearchable'] = !$profile['net-publish'];
866 // it seems as if ported accounts can have wrong values, so we make sure that now everything is fine.
867 $fields['url'] = DI::baseUrl() . '/profile/' . $user['nickname'];
868 $fields['nurl'] = Strings::normaliseLink($fields['url']);
869 $fields['addr'] = $user['nickname'] . '@' . substr(DI::baseUrl(), strpos(DI::baseUrl(), '://') + 3);
870 $fields['request'] = DI::baseUrl() . '/dfrn_request/' . $user['nickname'];
871 $fields['notify'] = DI::baseUrl() . '/dfrn_notify/' . $user['nickname'];
872 $fields['poll'] = DI::baseUrl() . '/dfrn_poll/'. $user['nickname'];
873 $fields['confirm'] = DI::baseUrl() . '/dfrn_confirm/' . $user['nickname'];
874 $fields['poco'] = DI::baseUrl() . '/poco/' . $user['nickname'];
878 foreach ($fields as $field => $content) {
879 if ($self[$field] != $content) {
885 if ($fields['name'] != $self['name']) {
886 $fields['name-date'] = DateTimeFormat::utcNow();
888 $fields['updated'] = DateTimeFormat::utcNow();
889 DBA::update('contact', $fields, ['id' => $self['id']]);
891 // Update the public contact as well
892 DBA::update('contact', $fields, ['uid' => 0, 'nurl' => $self['nurl']]);
894 // Update the profile
895 $fields = ['photo' => DI::baseUrl() . '/photo/profile/' .$uid . '.' . $file_suffix,
896 'thumb' => DI::baseUrl() . '/photo/avatar/' . $uid .'.' . $file_suffix];
897 DBA::update('profile', $fields, ['uid' => $uid]);
902 * Marks a contact for removal
904 * @param int $id contact id
906 * @throws HTTPException\InternalServerErrorException
908 public static function remove($id)
910 // We want just to make sure that we don't delete our "self" contact
911 $contact = DBA::selectFirst('contact', ['uid'], ['id' => $id, 'self' => false]);
912 if (!DBA::isResult($contact) || !intval($contact['uid'])) {
916 // Archive the contact
917 DBA::update('contact', ['archive' => true, 'network' => Protocol::PHANTOM, 'deleted' => true], ['id' => $id]);
919 // Delete it in the background
920 Worker::add(PRIORITY_MEDIUM, 'RemoveContact', $id);
924 * Sends an unfriend message. Does not remove the contact
926 * @param array $user User unfriending
927 * @param array $contact Contact unfriended
928 * @param boolean $dissolve Remove the contact on the remote side
930 * @throws HTTPException\InternalServerErrorException
931 * @throws \ImagickException
933 public static function terminateFriendship(array $user, array $contact, $dissolve = false)
935 if (empty($contact['network'])) {
939 $protocol = $contact['network'];
940 if (($protocol == Protocol::DFRN) && !self::isLegacyDFRNContact($contact)) {
941 $protocol = Protocol::ACTIVITYPUB;
944 if (($protocol == Protocol::DFRN) && $dissolve) {
945 DFRN::deliver($user, $contact, 'placeholder', true);
946 } elseif (in_array($protocol, [Protocol::OSTATUS, Protocol::DFRN])) {
947 // create an unfollow slap
949 $item['verb'] = Activity::O_UNFOLLOW;
950 $item['gravity'] = GRAVITY_ACTIVITY;
951 $item['follow'] = $contact["url"];
956 $item['attach'] = '';
957 $slap = OStatus::salmon($item, $user);
959 if (!empty($contact['notify'])) {
960 Salmon::slapper($user, $contact['notify'], $slap);
962 } elseif ($protocol == Protocol::DIASPORA) {
963 Diaspora::sendUnshare($user, $contact);
964 } elseif ($protocol == Protocol::ACTIVITYPUB) {
965 ActivityPub\Transmitter::sendContactUndo($contact['url'], $contact['id'], $user['uid']);
968 ActivityPub\Transmitter::sendContactReject($contact['url'], $contact['hub-verify'], $user['uid']);
974 * Marks a contact for archival after a communication issue delay
976 * Contact has refused to recognise us as a friend. We will start a countdown.
977 * If they still don't recognise us in 32 days, the relationship is over,
978 * and we won't waste any more time trying to communicate with them.
979 * This provides for the possibility that their database is temporarily messed
980 * up or some other transient event and that there's a possibility we could recover from it.
982 * @param array $contact contact to mark for archival
984 * @throws HTTPException\InternalServerErrorException
986 public static function markForArchival(array $contact)
988 if (!isset($contact['url']) && !empty($contact['id'])) {
989 $fields = ['id', 'url', 'archive', 'self', 'term-date'];
990 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact['id']]);
991 if (!DBA::isResult($contact)) {
994 } elseif (!isset($contact['url'])) {
995 Logger::info('Empty contact', ['contact' => $contact, 'callstack' => System::callstack(20)]);
998 Logger::info('Contact is marked for archival', ['id' => $contact['id']]);
1000 // Contact already archived or "self" contact? => nothing to do
1001 if ($contact['archive'] || $contact['self']) {
1005 if ($contact['term-date'] <= DBA::NULL_DATETIME) {
1006 DBA::update('contact', ['term-date' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
1007 DBA::update('contact', ['term-date' => DateTimeFormat::utcNow()], ['`nurl` = ? AND `term-date` <= ? AND NOT `self`', Strings::normaliseLink($contact['url']), DBA::NULL_DATETIME]);
1010 * We really should send a notification to the owner after 2-3 weeks
1011 * so they won't be surprised when the contact vanishes and can take
1012 * remedial action if this was a serious mistake or glitch
1015 /// @todo Check for contact vitality via probing
1016 $archival_days = DI::config()->get('system', 'archival_days', 32);
1018 $expiry = $contact['term-date'] . ' + ' . $archival_days . ' days ';
1019 if (DateTimeFormat::utcNow() > DateTimeFormat::utc($expiry)) {
1020 /* Relationship is really truly dead. archive them rather than
1021 * delete, though if the owner tries to unarchive them we'll start
1022 * the whole process over again.
1024 DBA::update('contact', ['archive' => true], ['id' => $contact['id']]);
1025 DBA::update('contact', ['archive' => true], ['nurl' => Strings::normaliseLink($contact['url']), 'self' => false]);
1031 * Cancels the archival countdown
1033 * @see Contact::markForArchival()
1035 * @param array $contact contact to be unmarked for archival
1037 * @throws \Exception
1039 public static function unmarkForArchival(array $contact)
1041 // Always unarchive the relay contact entry
1042 if (!empty($contact['batch']) && !empty($contact['term-date']) && ($contact['term-date'] > DBA::NULL_DATETIME)) {
1043 $fields = ['failed' => false, 'term-date' => DBA::NULL_DATETIME, 'archive' => false];
1044 $condition = ['uid' => 0, 'network' => Protocol::FEDERATED, 'batch' => $contact['batch'], 'contact-type' => self::TYPE_RELAY];
1045 DBA::update('contact', $fields, $condition);
1048 $condition = ['`id` = ? AND (`term-date` > ? OR `archive`)', $contact['id'], DBA::NULL_DATETIME];
1049 $exists = DBA::exists('contact', $condition);
1051 // We don't need to update, we never marked this contact for archival
1056 Logger::info('Contact is marked as vital again', ['id' => $contact['id']]);
1058 if (!isset($contact['url']) && !empty($contact['id'])) {
1059 $fields = ['id', 'url', 'batch'];
1060 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact['id']]);
1061 if (!DBA::isResult($contact)) {
1066 // It's a miracle. Our dead contact has inexplicably come back to life.
1067 $fields = ['failed' => false, 'term-date' => DBA::NULL_DATETIME, 'archive' => false];
1068 DBA::update('contact', $fields, ['id' => $contact['id']]);
1069 DBA::update('contact', $fields, ['nurl' => Strings::normaliseLink($contact['url']), 'self' => false]);
1073 * Returns the data array for the photo menu of a given contact
1075 * @param array $contact contact
1076 * @param int $uid optional, default 0
1078 * @throws HTTPException\InternalServerErrorException
1079 * @throws \ImagickException
1081 public static function photoMenu(array $contact, $uid = 0)
1086 $contact_drop_link = '';
1090 $uid = local_user();
1093 if (empty($contact['uid']) || ($contact['uid'] != $uid)) {
1095 $profile_link = self::magicLink($contact['url']);
1096 $menu = ['profile' => [DI::l10n()->t('View Profile'), $profile_link, true]];
1101 // Look for our own contact if the uid doesn't match and isn't public
1102 $contact_own = DBA::selectFirst('contact', [], ['nurl' => $contact['nurl'], 'network' => $contact['network'], 'uid' => $uid]);
1103 if (DBA::isResult($contact_own)) {
1104 return self::photoMenu($contact_own, $uid);
1109 if (($contact['network'] === Protocol::DFRN) && !$contact['self'] && empty($contact['pending'])) {
1111 $profile_link = DI::baseUrl() . '/redir/' . $contact['id'];
1113 $profile_link = $contact['url'];
1116 if ($profile_link === 'mailbox') {
1121 $status_link = $profile_link . '/status';
1122 $photos_link = str_replace('/profile/', '/photos/', $profile_link);
1123 $profile_link = $profile_link . '/profile';
1126 if (self::canReceivePrivateMessages($contact) && empty($contact['pending'])) {
1127 $pm_url = DI::baseUrl() . '/message/new/' . $contact['id'];
1130 if (($contact['network'] == Protocol::DFRN) && !$contact['self'] && empty($contact['pending'])) {
1131 $poke_link = 'contact/' . $contact['id'] . '/poke';
1134 $contact_url = DI::baseUrl() . '/contact/' . $contact['id'];
1136 $posts_link = DI::baseUrl() . '/contact/' . $contact['id'] . '/conversations';
1138 if (!$contact['self']) {
1139 $contact_drop_link = DI::baseUrl() . '/contact/' . $contact['id'] . '/drop?confirm=1';
1143 $unfollow_link = '';
1144 if (!$contact['self'] && in_array($contact['network'], Protocol::NATIVE_SUPPORT)) {
1145 if ($contact['uid'] && in_array($contact['rel'], [self::SHARING, self::FRIEND])) {
1146 $unfollow_link = 'unfollow?url=' . urlencode($contact['url']);
1147 } elseif(!$contact['pending']) {
1148 $follow_link = 'follow?url=' . urlencode($contact['url']);
1152 if (!empty($follow_link) || !empty($unfollow_link)) {
1153 $contact_drop_link = '';
1158 * "name" => [ "Label", "link", (bool)Should the link opened in a new tab? ]
1160 if (empty($contact['uid'])) {
1162 'profile' => [DI::l10n()->t('View Profile') , $profile_link , true],
1163 'network' => [DI::l10n()->t('Network Posts') , $posts_link , false],
1164 'edit' => [DI::l10n()->t('View Contact') , $contact_url , false],
1165 'follow' => [DI::l10n()->t('Connect/Follow'), $follow_link , true],
1166 'unfollow'=> [DI::l10n()->t('UnFollow') , $unfollow_link, true],
1170 'status' => [DI::l10n()->t('View Status') , $status_link , true],
1171 'profile' => [DI::l10n()->t('View Profile') , $profile_link , true],
1172 'photos' => [DI::l10n()->t('View Photos') , $photos_link , true],
1173 'network' => [DI::l10n()->t('Network Posts') , $posts_link , false],
1174 'edit' => [DI::l10n()->t('View Contact') , $contact_url , false],
1175 'drop' => [DI::l10n()->t('Drop Contact') , $contact_drop_link, false],
1176 'pm' => [DI::l10n()->t('Send PM') , $pm_url , false],
1177 'poke' => [DI::l10n()->t('Poke') , $poke_link , false],
1178 'follow' => [DI::l10n()->t('Connect/Follow'), $follow_link , true],
1179 'unfollow'=> [DI::l10n()->t('UnFollow') , $unfollow_link , true],
1182 if (!empty($contact['pending'])) {
1183 $intro = DBA::selectFirst('intro', ['id'], ['contact-id' => $contact['id']]);
1184 if (DBA::isResult($intro)) {
1185 $menu['follow'] = [DI::l10n()->t('Approve'), 'notifications/intros/' . $intro['id'], true];
1190 $args = ['contact' => $contact, 'menu' => &$menu];
1192 Hook::callAll('contact_photo_menu', $args);
1194 $menucondensed = [];
1196 foreach ($menu as $menuname => $menuitem) {
1197 if ($menuitem[1] != '') {
1198 $menucondensed[$menuname] = $menuitem;
1202 return $menucondensed;
1206 * Returns ungrouped contact count or list for user
1208 * Returns either the total number of ungrouped contacts for the given user
1209 * id or a paginated list of ungrouped contacts.
1211 * @param int $uid uid
1213 * @throws \Exception
1215 public static function getUngroupedList($uid)
1225 SELECT DISTINCT(`contact-id`)
1227 INNER JOIN `group` ON `group`.`id` = `group_member`.`gid`
1228 WHERE `group`.`uid` = %d
1229 )", intval($uid), intval($uid));
1233 * Have a look at all contact tables for a given profile url.
1234 * This function works as a replacement for probing the contact.
1236 * @param string $url Contact URL
1237 * @param integer $cid Contact ID
1239 * @return array Contact array in the "probe" structure
1241 private static function getProbeDataFromDatabase($url, $cid = null)
1243 // The link could be provided as http although we stored it as https
1244 $ssl_url = str_replace('http://', 'https://', $url);
1246 $fields = ['id', 'uid', 'url', 'addr', 'alias', 'notify', 'poll', 'name', 'nick',
1247 'photo', 'keywords', 'location', 'about', 'network',
1248 'priority', 'batch', 'request', 'confirm', 'poco'];
1251 $data = DBA::selectFirst('contact', $fields, ['id' => $cid]);
1252 if (DBA::isResult($data)) {
1257 $data = DBA::selectFirst('contact', $fields, ['nurl' => Strings::normaliseLink($url)]);
1259 if (!DBA::isResult($data)) {
1260 $condition = ['alias' => [$url, Strings::normaliseLink($url), $ssl_url]];
1261 $data = DBA::selectFirst('contact', $fields, $condition);
1264 if (DBA::isResult($data)) {
1265 // For security reasons we don't fetch key data from our users
1266 $data["pubkey"] = '';
1270 $fields = ['url', 'addr', 'alias', 'notify', 'name', 'nick',
1271 'photo', 'keywords', 'location', 'about', 'network'];
1272 $condition = ['alias' => [$url, Strings::normaliseLink($url), $ssl_url]];
1273 $data = DBA::selectFirst('contact', $fields, $condition);
1275 if (DBA::isResult($data)) {
1276 $data["pubkey"] = '';
1278 $data["priority"] = 0;
1279 $data["batch"] = '';
1280 $data["request"] = '';
1281 $data["confirm"] = '';
1286 $data = ActivityPub::probeProfile($url, false);
1287 if (!empty($data)) {
1291 $fields = ['url', 'addr', 'alias', 'notify', 'poll', 'name', 'nick',
1292 'photo', 'network', 'priority', 'batch', 'request', 'confirm'];
1293 $data = DBA::selectFirst('fcontact', $fields, ['url' => $url]);
1295 if (!DBA::isResult($data)) {
1296 $condition = ['alias' => [$url, Strings::normaliseLink($url), $ssl_url]];
1297 $data = DBA::selectFirst('contact', $fields, $condition);
1300 if (DBA::isResult($data)) {
1301 $data["pubkey"] = '';
1302 $data["keywords"] = '';
1303 $data["location"] = '';
1304 $data["about"] = '';
1313 * Fetch the contact id for a given URL and user
1315 * First lookup in the contact table to find a record matching either `url`, `nurl`,
1316 * `addr` or `alias`.
1318 * If there's no record and we aren't looking for a public contact, we quit.
1319 * If there's one, we check that it isn't time to update the picture else we
1320 * directly return the found contact id.
1322 * Second, we probe the provided $url whether it's http://server.tld/profile or
1323 * nick@server.tld. We quit if we can't get any info back.
1325 * Third, we create the contact record if it doesn't exist
1327 * Fourth, we update the existing record with the new data (avatar, alias, nick)
1328 * if there's any updates
1330 * @param string $url Contact URL
1331 * @param integer $uid The user id for the contact (0 = public contact)
1332 * @param boolean $update true = always update, false = never update, null = update when not found or outdated
1333 * @param array $default Default value for creating the contact when every else fails
1334 * @param boolean $in_loop Internally used variable to prevent an endless loop
1336 * @return integer Contact ID
1337 * @throws HTTPException\InternalServerErrorException
1338 * @throws \ImagickException
1340 public static function getIdForURL($url, $uid = 0, $update = null, $default = [], $in_loop = false)
1342 Logger::info('Get contact data', ['url' => $url, 'user' => $uid]);
1350 $contact = self::getByURL($url, false, ['id', 'avatar', 'updated', 'network'], $uid);
1352 if (!empty($contact)) {
1353 $contact_id = $contact["id"];
1355 if (empty($default) && in_array($contact['network'], [Protocol::MAIL, Protocol::PHANTOM]) && ($uid == 0)) {
1356 // Update public mail accounts via their user's accounts
1357 $fields = ['network', 'addr', 'name', 'nick', 'avatar', 'photo', 'thumb', 'micro'];
1358 $mailcontact = DBA::selectFirst('contact', $fields, ["`addr` = ? AND `network` = ? AND `uid` != 0", $url, Protocol::MAIL]);
1359 if (!DBA::isResult($mailcontact)) {
1360 $mailcontact = DBA::selectFirst('contact', $fields, ["`nurl` = ? AND `network` = ? AND `uid` != 0", $url, Protocol::MAIL]);
1363 if (DBA::isResult($mailcontact)) {
1364 DBA::update('contact', $mailcontact, ['id' => $contact_id]);
1368 if (empty($update)) {
1371 } elseif ($uid != 0) {
1372 // Non-existing user-specific contact, exiting
1376 if (!$update && empty($default)) {
1377 // When we don't want to update, we look if we know this contact in any way
1378 $data = self::getProbeDataFromDatabase($url, $contact_id);
1379 $background_update = true;
1380 } elseif (!$update && !empty($default['network'])) {
1381 // If there are default values, take these
1383 $background_update = false;
1386 $background_update = false;
1389 if ((empty($data) && is_null($update)) || $update) {
1390 $data = Probe::uri($url, "", $uid);
1393 // Take the default values when probing failed
1394 if (!empty($default) && !in_array($data["network"], array_merge(Protocol::NATIVE_SUPPORT, [Protocol::PUMPIO]))) {
1395 $data = array_merge($data, $default);
1398 if (empty($data) || ($data['network'] == Protocol::PHANTOM)) {
1399 Logger::info('No valid network found', ['url' => $url, 'data' => $data, 'callstack' => System::callstack(20)]);
1403 if (!empty($data['baseurl'])) {
1404 $data['baseurl'] = GServer::cleanURL($data['baseurl']);
1407 if (!empty($data['baseurl']) && empty($data['gsid'])) {
1408 $data['gsid'] = GServer::getID($data['baseurl']);
1411 if (!$contact_id && !empty($data['alias']) && ($data['alias'] != $data['url']) && !$in_loop) {
1412 $contact_id = self::getIdForURL($data["alias"], $uid, false, $default, true);
1418 'created' => DateTimeFormat::utcNow(),
1419 'url' => $data['url'],
1420 'nurl' => Strings::normaliseLink($data['url']),
1421 'addr' => $data['addr'] ?? '',
1422 'alias' => $data['alias'] ?? '',
1423 'notify' => $data['notify'] ?? '',
1424 'poll' => $data['poll'] ?? '',
1425 'name' => $data['name'] ?? '',
1426 'nick' => $data['nick'] ?? '',
1427 'keywords' => $data['keywords'] ?? '',
1428 'location' => $data['location'] ?? '',
1429 'about' => $data['about'] ?? '',
1430 'network' => $data['network'],
1431 'pubkey' => $data['pubkey'] ?? '',
1432 'rel' => self::SHARING,
1433 'priority' => $data['priority'] ?? 0,
1434 'batch' => $data['batch'] ?? '',
1435 'request' => $data['request'] ?? '',
1436 'confirm' => $data['confirm'] ?? '',
1437 'poco' => $data['poco'] ?? '',
1438 'baseurl' => $data['baseurl'] ?? '',
1439 'gsid' => $data['gsid'] ?? null,
1440 'name-date' => DateTimeFormat::utcNow(),
1441 'uri-date' => DateTimeFormat::utcNow(),
1442 'avatar-date' => DateTimeFormat::utcNow(),
1448 $condition = ['nurl' => Strings::normaliseLink($data["url"]), 'uid' => $uid, 'deleted' => false];
1450 // Before inserting we do check if the entry does exist now.
1451 $contact = DBA::selectFirst('contact', ['id'], $condition, ['order' => ['id']]);
1452 if (!DBA::isResult($contact)) {
1453 Logger::info('Create new contact', $fields);
1455 self::insert($fields);
1457 // We intentionally aren't using lastInsertId here. There is a chance for duplicates.
1458 $contact = DBA::selectFirst('contact', ['id'], $condition, ['order' => ['id']]);
1459 if (!DBA::isResult($contact)) {
1460 Logger::info('Contact creation failed', $fields);
1465 Logger::info('Contact had been created before', ['id' => $contact["id"], 'url' => $url, 'contact' => $fields]);
1468 $contact_id = $contact["id"];
1471 if (!empty($data['photo']) && ($data['network'] != Protocol::FEED)) {
1472 self::updateAvatar($contact_id, $data['photo']);
1475 if (in_array($data["network"], array_merge(Protocol::NATIVE_SUPPORT, [Protocol::PUMPIO]))) {
1476 if ($background_update) {
1477 // Update in the background when we fetched the data solely from the database
1478 Worker::add(PRIORITY_MEDIUM, "UpdateContact", $contact_id, ($uid == 0 ? 'force' : ''));
1480 // Else do a direct update
1481 self::updateFromProbe($contact_id, '', false);
1484 $fields = ['url', 'nurl', 'addr', 'alias', 'name', 'nick', 'keywords', 'location', 'about', 'avatar-date', 'baseurl', 'gsid'];
1485 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact_id]);
1487 // This condition should always be true
1488 if (!DBA::isResult($contact)) {
1493 'url' => $data['url'],
1494 'nurl' => Strings::normaliseLink($data['url']),
1495 '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 if ((isset($contact['page-flags']) && (intval($contact['page-flags']) == User::PAGE_FLAGS_COMMUNITY))
1706 || (isset($contact['page-flags']) && (intval($contact['page-flags']) == User::PAGE_FLAGS_PRVGROUP))
1707 || (isset($contact['forum']) && intval($contact['forum']))
1708 || (isset($contact['prv']) && intval($contact['prv']))
1709 || (isset($contact['community']) && intval($contact['community']))
1711 $type = self::TYPE_COMMUNITY;
1713 $type = self::TYPE_PERSON;
1716 // The "contact-type" (contact table) and "account-type" (user table) are more general then the chaos from above.
1717 if (isset($contact["contact-type"])) {
1718 $type = $contact["contact-type"];
1721 if (isset($contact["account-type"])) {
1722 $type = $contact["account-type"];
1726 case self::TYPE_ORGANISATION:
1727 $account_type = DI::l10n()->t("Organisation");
1730 case self::TYPE_NEWS:
1731 $account_type = DI::l10n()->t('News');
1734 case self::TYPE_COMMUNITY:
1735 $account_type = DI::l10n()->t("Forum");
1743 return $account_type;
1751 * @throws \Exception
1753 public static function block($cid, $reason = null)
1755 $return = DBA::update('contact', ['blocked' => true, 'block_reason' => $reason], ['id' => $cid]);
1761 * Unblocks a contact
1765 * @throws \Exception
1767 public static function unblock($cid)
1769 $return = DBA::update('contact', ['blocked' => false, 'block_reason' => null], ['id' => $cid]);
1775 * Ensure that cached avatar exist
1777 * @param integer $cid
1779 public static function checkAvatarCache(int $cid)
1781 $contact = DBA::selectFirst('contact', ['url', 'avatar', 'photo', 'thumb', 'micro'], ['id' => $cid, 'uid' => 0, 'self' => false]);
1782 if (!DBA::isResult($contact)) {
1786 if (empty($contact['avatar']) || (!empty($contact['photo']) && !empty($contact['thumb']) && !empty($contact['micro']))) {
1790 Logger::info('Adding avatar cache', ['id' => $cid, 'contact' => $contact]);
1792 self::updateAvatar($cid, $contact['avatar'], true);
1796 * Return the photo path for a given contact array in the given size
1798 * @param array $contact contact array
1799 * @param string $field Fieldname of the photo in the contact array
1800 * @param string $default Default path when no picture had been found
1801 * @param string $size Size of the avatar picture
1802 * @param string $avatar Avatar path that is displayed when no photo had been found
1803 * @return string photo path
1805 private static function getAvatarPath(array $contact, string $field, string $default, string $size, string $avatar)
1807 if (!empty($contact)) {
1808 $contact = self::checkAvatarCacheByArray($contact);
1809 if (!empty($contact[$field])) {
1810 $avatar = $contact[$field];
1814 if (empty($avatar)) {
1818 if (Proxy::isLocalImage($avatar)) {
1821 return Proxy::proxifyUrl($avatar, false, $size);
1826 * Return the photo path for a given contact array
1828 * @param array $contact Contact array
1829 * @param string $avatar Avatar path that is displayed when no photo had been found
1830 * @return string photo path
1832 public static function getPhoto(array $contact, string $avatar = '')
1834 return self::getAvatarPath($contact, 'photo', DI::baseUrl() . '/images/person-300.jpg', Proxy::SIZE_SMALL, $avatar);
1838 * Return the photo path (thumb size) for a given contact array
1840 * @param array $contact Contact array
1841 * @param string $avatar Avatar path that is displayed when no photo had been found
1842 * @return string photo path
1844 public static function getThumb(array $contact, string $avatar = '')
1846 return self::getAvatarPath($contact, 'thumb', DI::baseUrl() . '/images/person-80.jpg', Proxy::SIZE_THUMB, $avatar);
1850 * Return the photo path (micro size) for a given contact array
1852 * @param array $contact Contact array
1853 * @param string $avatar Avatar path that is displayed when no photo had been found
1854 * @return string photo path
1856 public static function getMicro(array $contact, string $avatar = '')
1858 return self::getAvatarPath($contact, 'micro', DI::baseUrl() . '/images/person-48.jpg', Proxy::SIZE_MICRO, $avatar);
1862 * Check the given contact array for avatar cache fields
1864 * @param array $contact
1865 * @return array contact array with avatar cache fields
1867 private static function checkAvatarCacheByArray(array $contact)
1870 $contact_fields = [];
1871 $fields = ['photo', 'thumb', 'micro'];
1872 foreach ($fields as $field) {
1873 if (isset($contact[$field])) {
1874 $contact_fields[] = $field;
1876 if (isset($contact[$field]) && empty($contact[$field])) {
1885 if (!empty($contact['id']) && !empty($contact['avatar'])) {
1886 self::updateAvatar($contact['id'], $contact['avatar'], true);
1888 $new_contact = self::getById($contact['id'], $contact_fields);
1889 if (DBA::isResult($new_contact)) {
1890 // We only update the cache fields
1891 $contact = array_merge($contact, $new_contact);
1895 /// add the default avatars if the fields aren't filled
1896 if (isset($contact['photo']) && empty($contact['photo'])) {
1897 $contact['photo'] = DI::baseUrl() . '/images/person-300.jpg';
1899 if (isset($contact['thumb']) && empty($contact['thumb'])) {
1900 $contact['thumb'] = DI::baseUrl() . '/images/person-80.jpg';
1902 if (isset($contact['micro']) && empty($contact['micro'])) {
1903 $contact['micro'] = DI::baseUrl() . '/images/person-48.jpg';
1910 * Updates the avatar links in a contact only if needed
1912 * @param int $cid Contact id
1913 * @param string $avatar Link to avatar picture
1914 * @param bool $force force picture update
1917 * @throws HTTPException\InternalServerErrorException
1918 * @throws HTTPException\NotFoundException
1919 * @throws \ImagickException
1921 public static function updateAvatar(int $cid, string $avatar, bool $force = false)
1923 $contact = DBA::selectFirst('contact', ['uid', 'avatar', 'photo', 'thumb', 'micro', 'nurl'], ['id' => $cid, 'self' => false]);
1924 if (!DBA::isResult($contact)) {
1928 $uid = $contact['uid'];
1930 // Only update the cached photo links of public contacts when they already are cached
1931 if (($uid == 0) && !$force && empty($contact['thumb']) && empty($contact['micro'])) {
1932 if ($contact['avatar'] != $avatar) {
1933 DBA::update('contact', ['avatar' => $avatar], ['id' => $cid]);
1934 Logger::info('Only update the avatar', ['id' => $cid, 'avatar' => $avatar, 'contact' => $contact]);
1940 $contact['photo'] ?? '',
1941 $contact['thumb'] ?? '',
1942 $contact['micro'] ?? '',
1945 $update = ($contact['avatar'] != $avatar) || $force;
1948 foreach ($data as $image_uri) {
1949 $image_rid = Photo::ridFromURI($image_uri);
1950 if ($image_rid && !Photo::exists(['resource-id' => $image_rid, 'uid' => $uid])) {
1951 Logger::info('Regenerating avatar', ['contact uid' => $uid, 'cid' => $cid, 'missing photo' => $image_rid, 'avatar' => $contact['avatar']]);
1958 $photos = Photo::importProfilePhoto($avatar, $uid, $cid, true);
1960 $fields = ['avatar' => $avatar, 'photo' => $photos[0], 'thumb' => $photos[1], 'micro' => $photos[2], 'avatar-date' => DateTimeFormat::utcNow()];
1961 DBA::update('contact', $fields, ['id' => $cid]);
1962 } elseif (empty($contact['avatar'])) {
1963 // Ensure that the avatar field is set
1964 DBA::update('contact', ['avatar' => $avatar], ['id' => $cid]);
1965 Logger::info('Failed profile import', ['id' => $cid, 'force' => $force, 'avatar' => $avatar, 'contact' => $contact]);
1971 * Helper function for "updateFromProbe". Updates personal and public contact
1973 * @param integer $id contact id
1974 * @param integer $uid user id
1975 * @param string $url The profile URL of the contact
1976 * @param array $fields The fields that are updated
1978 * @throws \Exception
1980 private static function updateContact($id, $uid, $url, array $fields)
1982 if (!DBA::update('contact', $fields, ['id' => $id])) {
1983 Logger::info('Couldn\'t update contact.', ['id' => $id, 'fields' => $fields]);
1987 // Search for duplicated contacts and get rid of them
1988 if (self::removeDuplicates(Strings::normaliseLink($url), $uid) || ($uid != 0)) {
1992 // Archive or unarchive the contact. We only need to do this for the public contact.
1993 // The archive/unarchive function will update the personal contacts by themselves.
1994 $contact = DBA::selectFirst('contact', [], ['id' => $id]);
1995 if (!DBA::isResult($contact)) {
1996 Logger::info('Couldn\'t select contact for archival.', ['id' => $id]);
2000 if (!empty($fields['success_update'])) {
2001 self::unmarkForArchival($contact);
2002 } elseif (!empty($fields['failure_update'])) {
2003 self::markForArchival($contact);
2006 $condition = ['self' => false, 'nurl' => Strings::normaliseLink($url), 'network' => Protocol::FEDERATED];
2008 // These contacts are sharing with us, we don't poll them.
2009 // This means that we don't set the update fields in "OnePoll.php".
2010 $condition['rel'] = self::SHARING;
2011 DBA::update('contact', $fields, $condition);
2013 unset($fields['last-update']);
2014 unset($fields['success_update']);
2015 unset($fields['failure_update']);
2017 if (empty($fields)) {
2021 // We are polling these contacts, so we mustn't set the update fields here.
2022 $condition['rel'] = [self::FOLLOWER, self::FRIEND];
2023 DBA::update('contact', $fields, $condition);
2027 * Remove duplicated contacts
2029 * @param string $nurl Normalised contact url
2030 * @param integer $uid User id
2032 * @throws \Exception
2034 public static function removeDuplicates(string $nurl, int $uid)
2036 $condition = ['nurl' => $nurl, 'uid' => $uid, 'deleted' => false, 'network' => Protocol::FEDERATED];
2037 $count = DBA::count('contact', $condition);
2042 $first_contact = DBA::selectFirst('contact', ['id', 'network'], $condition, ['order' => ['id']]);
2043 if (!DBA::isResult($first_contact)) {
2044 // Shouldn't happen - so we handle it
2048 $first = $first_contact['id'];
2049 Logger::info('Found duplicates', ['count' => $count, 'first' => $first, 'uid' => $uid, 'nurl' => $nurl]);
2050 if (($uid != 0 && ($first_contact['network'] == Protocol::DFRN))) {
2051 // Don't handle non public DFRN duplicates by now (legacy DFRN is very special because of the key handling)
2052 Logger::info('Not handling non public DFRN duplicate', ['uid' => $uid, 'nurl' => $nurl]);
2056 // Find all duplicates
2057 $condition = ["`nurl` = ? AND `uid` = ? AND `id` != ? AND NOT `self` AND NOT `deleted`", $nurl, $uid, $first];
2058 $duplicates = DBA::select('contact', ['id', 'network'], $condition);
2059 while ($duplicate = DBA::fetch($duplicates)) {
2060 if (!in_array($duplicate['network'], Protocol::FEDERATED)) {
2064 Worker::add(PRIORITY_HIGH, 'MergeContact', $first, $duplicate['id'], $uid);
2066 DBA::close($duplicates);
2067 Logger::info('Duplicates handled', ['uid' => $uid, 'nurl' => $nurl]);
2072 * @param integer $id contact id
2073 * @param string $network Optional network we are probing for
2074 * @param boolean $force Optional forcing of network probing (otherwise we use the cached data)
2076 * @throws HTTPException\InternalServerErrorException
2077 * @throws \ImagickException
2079 public static function updateFromProbe(int $id, string $network = '', bool $force = false)
2082 Warning: Never ever fetch the public key via Probe::uri and write it into the contacts.
2083 This will reliably kill your communication with old Friendica contacts.
2086 // These fields aren't updated by this routine:
2087 // 'xmpp', 'sensitive'
2089 $fields = ['uid', 'avatar', 'name', 'nick', 'location', 'keywords', 'about', 'subscribe',
2090 'unsearchable', 'url', 'addr', 'batch', 'notify', 'poll', 'request', 'confirm', 'poco',
2091 'network', 'alias', 'baseurl', 'gsid', 'forum', 'prv', 'contact-type', 'pubkey'];
2092 $contact = DBA::selectFirst('contact', $fields, ['id' => $id]);
2093 if (!DBA::isResult($contact)) {
2097 $uid = $contact['uid'];
2098 unset($contact['uid']);
2100 $pubkey = $contact['pubkey'];
2101 unset($contact['pubkey']);
2103 $contact['photo'] = $contact['avatar'];
2104 unset($contact['avatar']);
2106 $ret = Probe::uri($contact['url'], $network, $uid, !$force);
2108 $updated = DateTimeFormat::utcNow();
2110 // We must not try to update relay contacts via probe. They are no real contacts.
2111 // We check after the probing to be able to correct falsely detected contact types.
2112 if (($contact['contact-type'] == self::TYPE_RELAY) &&
2113 (!Strings::compareLink($ret['url'], $contact['url']) || in_array($ret['network'], [Protocol::FEED, Protocol::PHANTOM]))) {
2114 self::updateContact($id, $uid, $contact['url'], ['failed' => false, 'last-update' => $updated, 'success_update' => $updated]);
2115 Logger::info('Not updating relais', ['id' => $id, 'url' => $contact['url']]);
2119 // If Probe::uri fails the network code will be different ("feed" or "unkn")
2120 if (in_array($ret['network'], [Protocol::FEED, Protocol::PHANTOM]) && ($ret['network'] != $contact['network'])) {
2121 if ($force && ($uid == 0)) {
2122 self::updateContact($id, $uid, $ret['url'], ['failed' => true, 'last-update' => $updated, 'failure_update' => $updated]);
2127 if (Contact\Relation::isDiscoverable($ret['url'])) {
2128 Worker::add(PRIORITY_LOW, 'ContactDiscovery', $ret['url']);
2131 if (isset($ret['hide']) && is_bool($ret['hide'])) {
2132 $ret['unsearchable'] = $ret['hide'];
2135 if (isset($ret['account-type']) && is_int($ret['account-type'])) {
2136 $ret['forum'] = false;
2137 $ret['prv'] = false;
2138 $ret['contact-type'] = $ret['account-type'];
2139 if ($ret['contact-type'] == User::ACCOUNT_TYPE_COMMUNITY) {
2140 $apcontact = APContact::getByURL($ret['url'], false);
2141 if (isset($apcontact['manually-approve'])) {
2142 $ret['forum'] = (bool)!$apcontact['manually-approve'];
2143 $ret['prv'] = (bool)!$ret['forum'];
2148 $new_pubkey = $ret['pubkey'];
2152 // make sure to not overwrite existing values with blank entries except some technical fields
2153 $keep = ['batch', 'notify', 'poll', 'request', 'confirm', 'poco', 'baseurl'];
2154 foreach ($ret as $key => $val) {
2155 if (!array_key_exists($key, $contact)) {
2157 } elseif (($contact[$key] != '') && ($val === '') && !is_bool($ret[$key]) && !in_array($key, $keep)) {
2158 $ret[$key] = $contact[$key];
2159 } elseif ($ret[$key] != $contact[$key]) {
2164 if (!empty($ret['photo']) && ($ret['network'] != Protocol::FEED)) {
2165 self::updateAvatar($id, $ret['photo'], $update || $force);
2170 self::updateContact($id, $uid, $ret['url'], ['failed' => false, 'last-update' => $updated, 'success_update' => $updated]);
2173 // Update the public contact
2175 self::updateFromProbeByURL($ret['url']);
2181 $ret['nurl'] = Strings::normaliseLink($ret['url']);
2182 $ret['updated'] = $updated;
2184 // Only fill the pubkey if it had been empty before. We have to prevent identity theft.
2185 if (empty($pubkey) && !empty($new_pubkey)) {
2186 $ret['pubkey'] = $new_pubkey;
2189 if (($ret['addr'] != $contact['addr']) || (!empty($ret['alias']) && ($ret['alias'] != $contact['alias']))) {
2190 $ret['uri-date'] = DateTimeFormat::utcNow();
2193 if (($ret['name'] != $contact['name']) || ($ret['nick'] != $contact['nick'])) {
2194 $ret['name-date'] = $updated;
2197 if ($force && ($uid == 0)) {
2198 $ret['last-update'] = $updated;
2199 $ret['success_update'] = $updated;
2200 $ret['failed'] = false;
2203 unset($ret['photo']);
2205 self::updateContact($id, $uid, $ret['url'], $ret);
2210 public static function updateFromProbeByURL($url, $force = false)
2212 $id = self::getIdForURL($url);
2218 self::updateFromProbe($id, '', $force);
2224 * Detects if a given contact array belongs to a legacy DFRN connection
2226 * @param array $contact
2229 public static function isLegacyDFRNContact($contact)
2231 // Newer Friendica contacts are connected via AP, then these fields aren't set
2232 return !empty($contact['dfrn-id']) || !empty($contact['issued-id']);
2236 * Detects the communication protocol for a given contact url.
2237 * This is used to detect Friendica contacts that we can communicate via AP.
2239 * @param string $url contact url
2240 * @param string $network Network of that contact
2241 * @return string with protocol
2243 public static function getProtocol($url, $network)
2245 if ($network != Protocol::DFRN) {
2249 $apcontact = APContact::getByURL($url);
2250 if (!empty($apcontact) && !empty($apcontact['generator'])) {
2251 return Protocol::ACTIVITYPUB;
2258 * Takes a $uid and a url/handle and adds a new contact
2260 * Currently if the contact is DFRN, interactive needs to be true, to redirect to the
2261 * dfrn_request page.
2263 * Otherwise this can be used to bulk add StatusNet contacts, Twitter contacts, etc.
2266 * $return['success'] boolean true if successful
2267 * $return['message'] error text if success is false.
2269 * Takes a $uid and a url/handle and adds a new contact
2271 * @param array $user The user the contact should be created for
2272 * @param string $url The profile URL of the contact
2273 * @param bool $interactive
2274 * @param string $network
2276 * @throws HTTPException\InternalServerErrorException
2277 * @throws HTTPException\NotFoundException
2278 * @throws \ImagickException
2280 public static function createFromProbe(array $user, $url, $interactive = false, $network = '')
2282 $result = ['cid' => -1, 'success' => false, 'message' => ''];
2284 // remove ajax junk, e.g. Twitter
2285 $url = str_replace('/#!/', '/', $url);
2287 if (!Network::isUrlAllowed($url)) {
2288 $result['message'] = DI::l10n()->t('Disallowed profile URL.');
2292 if (Network::isUrlBlocked($url)) {
2293 $result['message'] = DI::l10n()->t('Blocked domain');
2298 $result['message'] = DI::l10n()->t('Connect URL missing.');
2302 $arr = ['url' => $url, 'contact' => []];
2304 Hook::callAll('follow', $arr);
2307 $result['message'] = DI::l10n()->t('The contact could not be added. Please check the relevant network credentials in your Settings -> Social Networks page.');
2311 if (!empty($arr['contact']['name'])) {
2312 $ret = $arr['contact'];
2314 $ret = Probe::uri($url, $network, $user['uid'], false);
2317 if (($network != '') && ($ret['network'] != $network)) {
2318 Logger::log('Expected network ' . $network . ' does not match actual network ' . $ret['network']);
2322 // check if we already have a contact
2323 // the poll url is more reliable than the profile url, as we may have
2324 // indirect links or webfinger links
2326 $condition = ['uid' => $user['uid'], 'poll' => [$ret['poll'], Strings::normaliseLink($ret['poll'])], 'network' => $ret['network'], 'pending' => false];
2327 $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
2328 if (!DBA::isResult($contact)) {
2329 $condition = ['uid' => $user['uid'], 'nurl' => Strings::normaliseLink($ret['url']), 'network' => $ret['network'], 'pending' => false];
2330 $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
2333 $protocol = self::getProtocol($ret['url'], $ret['network']);
2335 if (($protocol === Protocol::DFRN) && !DBA::isResult($contact)) {
2337 if (strlen(DI::baseUrl()->getUrlPath())) {
2338 $myaddr = bin2hex(DI::baseUrl() . '/profile/' . $user['nickname']);
2340 $myaddr = bin2hex($user['nickname'] . '@' . DI::baseUrl()->getHostname());
2343 DI::baseUrl()->redirect($ret['request'] . "&addr=$myaddr");
2347 } elseif (DI::config()->get('system', 'dfrn_only') && ($ret['network'] != Protocol::DFRN)) {
2348 $result['message'] = DI::l10n()->t('This site is not configured to allow communications with other networks.') . EOL;
2349 $result['message'] .= DI::l10n()->t('No compatible communication protocols or feeds were discovered.') . EOL;
2353 // This extra param just confuses things, remove it
2354 if ($protocol === Protocol::DIASPORA) {
2355 $ret['url'] = str_replace('?absolute=true', '', $ret['url']);
2358 // do we have enough information?
2359 if (empty($ret['name']) || empty($ret['poll']) || (empty($ret['url']) && empty($ret['addr']))) {
2360 $result['message'] .= DI::l10n()->t('The profile address specified does not provide adequate information.') . EOL;
2361 if (empty($ret['poll'])) {
2362 $result['message'] .= DI::l10n()->t('No compatible communication protocols or feeds were discovered.') . EOL;
2364 if (empty($ret['name'])) {
2365 $result['message'] .= DI::l10n()->t('An author or name was not found.') . EOL;
2367 if (empty($ret['url'])) {
2368 $result['message'] .= DI::l10n()->t('No browser URL could be matched to this address.') . EOL;
2370 if (strpos($ret['url'], '@') !== false) {
2371 $result['message'] .= DI::l10n()->t('Unable to match @-style Identity Address with a known protocol or email contact.') . EOL;
2372 $result['message'] .= DI::l10n()->t('Use mailto: in front of address to force email check.') . EOL;
2377 if ($protocol === Protocol::OSTATUS && DI::config()->get('system', 'ostatus_disabled')) {
2378 $result['message'] .= DI::l10n()->t('The profile address specified belongs to a network which has been disabled on this site.') . EOL;
2379 $ret['notify'] = '';
2382 if (!$ret['notify']) {
2383 $result['message'] .= DI::l10n()->t('Limited profile. This person will be unable to receive direct/personal notifications from you.') . EOL;
2386 $writeable = ((($protocol === Protocol::OSTATUS) && ($ret['notify'])) ? 1 : 0);
2388 $subhub = (($protocol === Protocol::OSTATUS) ? true : false);
2390 $hidden = (($protocol === Protocol::MAIL) ? 1 : 0);
2393 if ($protocol == Protocol::ACTIVITYPUB) {
2394 $apcontact = APContact::getByURL($ret['url'], false);
2395 if (isset($apcontact['manually-approve'])) {
2396 $pending = (bool)$apcontact['manually-approve'];
2400 if (in_array($protocol, [Protocol::MAIL, Protocol::DIASPORA, Protocol::ACTIVITYPUB])) {
2404 if (DBA::isResult($contact)) {
2406 $new_relation = (($contact['rel'] == self::FOLLOWER) ? self::FRIEND : self::SHARING);
2408 $fields = ['rel' => $new_relation, 'subhub' => $subhub, 'readonly' => false];
2409 DBA::update('contact', $fields, ['id' => $contact['id']]);
2411 $new_relation = (in_array($protocol, [Protocol::MAIL]) ? self::FRIEND : self::SHARING);
2413 // create contact record
2415 'uid' => $user['uid'],
2416 'created' => DateTimeFormat::utcNow(),
2417 'url' => $ret['url'],
2418 'nurl' => Strings::normaliseLink($ret['url']),
2419 'addr' => $ret['addr'],
2420 'alias' => $ret['alias'],
2421 'batch' => $ret['batch'],
2422 'notify' => $ret['notify'],
2423 'poll' => $ret['poll'],
2424 'poco' => $ret['poco'],
2425 'name' => $ret['name'],
2426 'nick' => $ret['nick'],
2427 'network' => $ret['network'],
2428 'baseurl' => $ret['baseurl'],
2429 'gsid' => $ret['gsid'] ?? null,
2430 'protocol' => $protocol,
2431 'pubkey' => $ret['pubkey'],
2432 'rel' => $new_relation,
2433 'priority'=> $ret['priority'],
2434 'writable'=> $writeable,
2435 'hidden' => $hidden,
2438 'pending' => $pending,
2443 $contact = DBA::selectFirst('contact', [], ['url' => $ret['url'], 'network' => $ret['network'], 'uid' => $user['uid']]);
2444 if (!DBA::isResult($contact)) {
2445 $result['message'] .= DI::l10n()->t('Unable to retrieve contact information.') . EOL;
2449 $contact_id = $contact['id'];
2450 $result['cid'] = $contact_id;
2452 Group::addMember(User::getDefaultGroup($user['uid'], $contact["network"]), $contact_id);
2454 // Update the avatar
2455 self::updateAvatar($contact_id, $ret['photo']);
2457 // pull feed and consume it, which should subscribe to the hub.
2459 Worker::add(PRIORITY_HIGH, "OnePoll", $contact_id, "force");
2461 $owner = User::getOwnerDataById($user['uid']);
2463 if (DBA::isResult($owner)) {
2464 if (in_array($protocol, [Protocol::OSTATUS, Protocol::DFRN])) {
2465 // create a follow slap
2467 $item['verb'] = Activity::FOLLOW;
2468 $item['gravity'] = GRAVITY_ACTIVITY;
2469 $item['follow'] = $contact["url"];
2471 $item['title'] = '';
2473 $item['uri-id'] = 0;
2474 $item['attach'] = '';
2476 $slap = OStatus::salmon($item, $owner);
2478 if (!empty($contact['notify'])) {
2479 Salmon::slapper($owner, $contact['notify'], $slap);
2481 } elseif ($protocol == Protocol::DIASPORA) {
2482 $ret = Diaspora::sendShare($owner, $contact);
2483 Logger::log('share returns: ' . $ret);
2484 } elseif ($protocol == Protocol::ACTIVITYPUB) {
2485 $activity_id = ActivityPub\Transmitter::activityIDFromContact($contact_id);
2486 if (empty($activity_id)) {
2487 // This really should never happen
2491 $ret = ActivityPub\Transmitter::sendActivity('Follow', $contact['url'], $user['uid'], $activity_id);
2492 Logger::log('Follow returns: ' . $ret);
2496 $result['success'] = true;
2501 * Updated contact's SSL policy
2503 * @param array $contact Contact array
2504 * @param string $new_policy New policy, valid: self,full
2506 * @return array Contact array with updated values
2507 * @throws \Exception
2509 public static function updateSslPolicy(array $contact, $new_policy)
2511 $ssl_changed = false;
2512 if ((intval($new_policy) == BaseURL::SSL_POLICY_SELFSIGN || $new_policy === 'self') && strstr($contact['url'], 'https:')) {
2513 $ssl_changed = true;
2514 $contact['url'] = str_replace('https:', 'http:', $contact['url']);
2515 $contact['request'] = str_replace('https:', 'http:', $contact['request']);
2516 $contact['notify'] = str_replace('https:', 'http:', $contact['notify']);
2517 $contact['poll'] = str_replace('https:', 'http:', $contact['poll']);
2518 $contact['confirm'] = str_replace('https:', 'http:', $contact['confirm']);
2519 $contact['poco'] = str_replace('https:', 'http:', $contact['poco']);
2522 if ((intval($new_policy) == BaseURL::SSL_POLICY_FULL || $new_policy === 'full') && strstr($contact['url'], 'http:')) {
2523 $ssl_changed = true;
2524 $contact['url'] = str_replace('http:', 'https:', $contact['url']);
2525 $contact['request'] = str_replace('http:', 'https:', $contact['request']);
2526 $contact['notify'] = str_replace('http:', 'https:', $contact['notify']);
2527 $contact['poll'] = str_replace('http:', 'https:', $contact['poll']);
2528 $contact['confirm'] = str_replace('http:', 'https:', $contact['confirm']);
2529 $contact['poco'] = str_replace('http:', 'https:', $contact['poco']);
2533 $fields = ['url' => $contact['url'], 'request' => $contact['request'],
2534 'notify' => $contact['notify'], 'poll' => $contact['poll'],
2535 'confirm' => $contact['confirm'], 'poco' => $contact['poco']];
2536 DBA::update('contact', $fields, ['id' => $contact['id']]);
2543 * @param array $importer Owner (local user) data
2544 * @param array $contact Existing owner-specific contact data we want to expand the relationship with. Optional.
2545 * @param array $datarray An item-like array with at least the 'author-id' and 'author-url' keys for the contact. Mandatory.
2546 * @param bool $sharing True: Contact is now sharing with Owner; False: Contact is now following Owner (default)
2547 * @param string $note Introduction additional message
2548 * @return bool|null True: follow request is accepted; False: relationship is rejected; Null: relationship is pending
2549 * @throws HTTPException\InternalServerErrorException
2550 * @throws \ImagickException
2552 public static function addRelationship(array $importer, array $contact, array $datarray, $sharing = false, $note = '')
2554 // Should always be set
2555 if (empty($datarray['author-id'])) {
2559 $fields = ['url', 'name', 'nick', 'avatar', 'photo', 'network', 'blocked'];
2560 $pub_contact = DBA::selectFirst('contact', $fields, ['id' => $datarray['author-id']]);
2561 if (!DBA::isResult($pub_contact)) {
2562 // Should never happen
2566 // Contact is blocked at node-level
2567 if (self::isBlocked($datarray['author-id'])) {
2571 $url = ($datarray['author-link'] ?? '') ?: $pub_contact['url'];
2572 $name = $pub_contact['name'];
2573 $photo = ($pub_contact['avatar'] ?? '') ?: $pub_contact["photo"];
2574 $nick = $pub_contact['nick'];
2575 $network = $pub_contact['network'];
2577 // Ensure that we don't create a new contact when there already is one
2578 $cid = self::getIdForURL($url, $importer['uid']);
2580 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
2583 if (!empty($contact)) {
2584 if (!empty($contact['pending'])) {
2585 Logger::info('Pending contact request already exists.', ['url' => $url, 'uid' => $importer['uid']]);
2589 // Contact is blocked at user-level
2590 if (!empty($contact['id']) && !empty($importer['id']) &&
2591 self::isBlockedByUser($contact['id'], $importer['id'])) {
2595 // Make sure that the existing contact isn't archived
2596 self::unmarkForArchival($contact);
2598 if (($contact['rel'] == self::SHARING)
2599 || ($sharing && $contact['rel'] == self::FOLLOWER)) {
2600 DBA::update('contact', ['rel' => self::FRIEND, 'writable' => true, 'pending' => false],
2601 ['id' => $contact['id'], 'uid' => $importer['uid']]);
2604 // Ensure to always have the correct network type, independent from the connection request method
2605 self::updateFromProbe($contact['id'], '', true);
2609 // send email notification to owner?
2610 if (DBA::exists('contact', ['nurl' => Strings::normaliseLink($url), 'uid' => $importer['uid'], 'pending' => true])) {
2611 Logger::log('ignoring duplicated connection request from pending contact ' . $url);
2615 // create contact record
2616 DBA::insert('contact', [
2617 'uid' => $importer['uid'],
2618 'created' => DateTimeFormat::utcNow(),
2620 'nurl' => Strings::normaliseLink($url),
2623 'network' => $network,
2624 'rel' => self::FOLLOWER,
2631 $contact_id = DBA::lastInsertId();
2633 // Ensure to always have the correct network type, independent from the connection request method
2634 self::updateFromProbe($contact_id, '', true);
2636 self::updateAvatar($contact_id, $photo, true);
2638 $contact_record = DBA::selectFirst('contact', ['id', 'network', 'name', 'url', 'photo'], ['id' => $contact_id]);
2640 /// @TODO Encapsulate this into a function/method
2641 $fields = ['uid', 'username', 'email', 'page-flags', 'notify-flags', 'language'];
2642 $user = DBA::selectFirst('user', $fields, ['uid' => $importer['uid']]);
2643 if (DBA::isResult($user) && !in_array($user['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_FREELOVE, User::PAGE_FLAGS_COMMUNITY])) {
2644 // create notification
2645 $hash = Strings::getRandomHex();
2647 if (is_array($contact_record)) {
2648 DBA::insert('intro', ['uid' => $importer['uid'], 'contact-id' => $contact_record['id'],
2649 'blocked' => false, 'knowyou' => false, 'note' => $note,
2650 'hash' => $hash, 'datetime' => DateTimeFormat::utcNow()]);
2653 Group::addMember(User::getDefaultGroup($importer['uid'], $contact_record["network"]), $contact_record['id']);
2655 if (($user['notify-flags'] & Type::INTRO) &&
2656 in_array($user['page-flags'], [User::PAGE_FLAGS_NORMAL])) {
2659 'type' => Type::INTRO,
2660 'notify_flags' => $user['notify-flags'],
2661 'language' => $user['language'],
2662 'to_name' => $user['username'],
2663 'to_email' => $user['email'],
2664 'uid' => $user['uid'],
2665 'link' => DI::baseUrl() . '/notifications/intros',
2666 'source_name' => ((strlen(stripslashes($contact_record['name']))) ? stripslashes($contact_record['name']) : DI::l10n()->t('[Name Withheld]')),
2667 'source_link' => $contact_record['url'],
2668 'source_photo' => $contact_record['photo'],
2669 'verb' => ($sharing ? Activity::FRIEND : Activity::FOLLOW),
2673 } elseif (DBA::isResult($user) && in_array($user['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_FREELOVE, User::PAGE_FLAGS_COMMUNITY])) {
2674 if (($user['page-flags'] == User::PAGE_FLAGS_FREELOVE) && ($network != Protocol::DIASPORA)) {
2675 self::createFromProbe($importer, $url, false, $network);
2678 $condition = ['uid' => $importer['uid'], 'url' => $url, 'pending' => true];
2679 $fields = ['pending' => false];
2680 if ($user['page-flags'] == User::PAGE_FLAGS_FREELOVE) {
2681 $fields['rel'] = Contact::FRIEND;
2684 DBA::update('contact', $fields, $condition);
2693 public static function removeFollower($importer, $contact, array $datarray = [], $item = "")
2695 if (($contact['rel'] == self::FRIEND) || ($contact['rel'] == self::SHARING)) {
2696 DBA::update('contact', ['rel' => self::SHARING], ['id' => $contact['id']]);
2698 Contact::remove($contact['id']);
2702 public static function removeSharer($importer, $contact, array $datarray = [], $item = "")
2704 if (($contact['rel'] == self::FRIEND) || ($contact['rel'] == self::FOLLOWER)) {
2705 DBA::update('contact', ['rel' => self::FOLLOWER], ['id' => $contact['id']]);
2707 Contact::remove($contact['id']);
2712 * Create a birthday event.
2714 * Update the year and the birthday.
2716 public static function updateBirthdays()
2720 AND `bd` > "0001-01-01"
2721 AND SUBSTRING(`bd`, 1, 4) != `bdyear`
2722 AND (`contact`.`rel` = ? OR `contact`.`rel` = ?)
2723 AND NOT `contact`.`pending`
2724 AND NOT `contact`.`hidden`
2725 AND NOT `contact`.`blocked`
2726 AND NOT `contact`.`archive`
2727 AND NOT `contact`.`deleted`',
2732 $contacts = DBA::select('contact', ['id', 'uid', 'name', 'url', 'bd'], $condition);
2734 while ($contact = DBA::fetch($contacts)) {
2735 Logger::log('update_contact_birthday: ' . $contact['bd']);
2737 $nextbd = DateTimeFormat::utcNow('Y') . substr($contact['bd'], 4);
2739 if (Event::createBirthday($contact, $nextbd)) {
2743 ['bdyear' => substr($nextbd, 0, 4), 'bd' => $nextbd],
2744 ['id' => $contact['id']]
2748 DBA::close($contacts);
2752 * Remove the unavailable contact ids from the provided list
2754 * @param array $contact_ids Contact id list
2756 * @throws \Exception
2758 public static function pruneUnavailable(array $contact_ids)
2760 if (empty($contact_ids)) {
2764 $contacts = Contact::selectToArray(['id'], [
2765 'id' => $contact_ids,
2771 return array_column($contacts, 'id');
2775 * Returns a magic link to authenticate remote visitors
2777 * @todo check if the return is either a fully qualified URL or a relative path to Friendica basedir
2779 * @param string $contact_url The address of the target contact profile
2780 * @param string $url An url that we will be redirected to after the authentication
2782 * @return string with "redir" link
2783 * @throws HTTPException\InternalServerErrorException
2784 * @throws \ImagickException
2786 public static function magicLink($contact_url, $url = '')
2788 if (!Session::isAuthenticated()) {
2789 return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
2792 $data = self::getProbeDataFromDatabase($contact_url);
2794 return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
2797 // Prevents endless loop in case only a non-public contact exists for the contact URL
2798 unset($data['uid']);
2800 return self::magicLinkByContact($data, $url ?: $contact_url);
2804 * Returns a magic link to authenticate remote visitors
2806 * @param integer $cid The contact id of the target contact profile
2807 * @param string $url An url that we will be redirected to after the authentication
2809 * @return string with "redir" link
2810 * @throws HTTPException\InternalServerErrorException
2811 * @throws \ImagickException
2813 public static function magicLinkbyId($cid, $url = '')
2815 $contact = DBA::selectFirst('contact', ['id', 'network', 'url', 'uid'], ['id' => $cid]);
2817 return self::magicLinkByContact($contact, $url);
2821 * Returns a magic link to authenticate remote visitors
2823 * @param array $contact The contact array with "uid", "network" and "url"
2824 * @param string $url An url that we will be redirected to after the authentication
2826 * @return string with "redir" link
2827 * @throws HTTPException\InternalServerErrorException
2828 * @throws \ImagickException
2830 public static function magicLinkByContact($contact, $url = '')
2832 $destination = $url ?: $contact['url']; // Equivalent to ($url != '') ? $url : $contact['url'];
2834 if (!Session::isAuthenticated() || ($contact['network'] != Protocol::DFRN)) {
2835 return $destination;
2838 // Only redirections to the same host do make sense
2839 if (($url != '') && (parse_url($url, PHP_URL_HOST) != parse_url($contact['url'], PHP_URL_HOST))) {
2843 if (!empty($contact['uid'])) {
2844 return self::magicLink($contact['url'], $url);
2847 if (empty($contact['id'])) {
2848 return $destination;
2851 $redirect = 'redir/' . $contact['id'];
2853 if (($url != '') && !Strings::compareLink($contact['url'], $url)) {
2854 $redirect .= '?url=' . $url;
2861 * Remove a contact from all groups
2863 * @param integer $contact_id
2865 * @return boolean Success
2867 public static function removeFromGroups($contact_id)
2869 return DBA::delete('group_member', ['contact-id' => $contact_id]);
2873 * Is the contact a forum?
2875 * @param integer $contactid ID of the contact
2877 * @return boolean "true" if it is a forum
2879 public static function isForum($contactid)
2881 $fields = ['forum', 'prv'];
2882 $condition = ['id' => $contactid];
2883 $contact = DBA::selectFirst('contact', $fields, $condition);
2884 if (!DBA::isResult($contact)) {
2889 return ($contact['forum'] || $contact['prv']);
2893 * Can the remote contact receive private messages?
2895 * @param array $contact
2898 public static function canReceivePrivateMessages(array $contact)
2900 $protocol = $contact['network'] ?? $contact['protocol'] ?? Protocol::PHANTOM;
2901 $self = $contact['self'] ?? false;
2903 return in_array($protocol, [Protocol::DFRN, Protocol::DIASPORA, Protocol::ACTIVITYPUB]) && !$self;
2907 * Search contact table by nick or name
2909 * @param string $search Name or nick
2910 * @param string $mode Search mode (e.g. "community")
2912 * @return array with search results
2913 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2915 public static function searchByName($search, $mode = '')
2917 if (empty($search)) {
2921 // check supported networks
2922 if (DI::config()->get('system', 'diaspora_enabled')) {
2923 $diaspora = Protocol::DIASPORA;
2925 $diaspora = Protocol::DFRN;
2928 if (!DI::config()->get('system', 'ostatus_disabled')) {
2929 $ostatus = Protocol::OSTATUS;
2931 $ostatus = Protocol::DFRN;
2934 // check if we search only communities or every contact
2935 if ($mode === 'community') {
2936 $extra_sql = sprintf(' AND `contact-type` = %d', Contact::TYPE_COMMUNITY);
2943 $results = DBA::p("SELECT * FROM `contact`
2944 WHERE NOT `unsearchable` AND `network` IN (?, ?, ?, ?) AND
2945 NOT `failed` AND `uid` = ? AND
2946 (`addr` LIKE ? OR `name` LIKE ? OR `nick` LIKE ?) $extra_sql
2947 ORDER BY `nurl` DESC LIMIT 1000",
2948 Protocol::DFRN, Protocol::ACTIVITYPUB, $ostatus, $diaspora, 0, $search, $search, $search
2951 $contacts = DBA::toArray($results);
2956 * @param int $uid user
2957 * @param int $start optional, default 0
2958 * @param int $limit optional, default 80
2961 static public function getSuggestions(int $uid, int $start = 0, int $limit = 80)
2963 $cid = self::getPublicIdByUserId($uid);
2964 $totallimit = $start + $limit;
2967 Logger::info('Collecting suggestions', ['uid' => $uid, 'cid' => $cid, 'start' => $start, 'limit' => $limit]);
2969 $diaspora = DI::config()->get('system', 'diaspora_enabled') ? Protocol::DIASPORA : Protocol::ACTIVITYPUB;
2970 $ostatus = !DI::config()->get('system', 'ostatus_disabled') ? Protocol::OSTATUS : Protocol::ACTIVITYPUB;
2972 // The query returns contacts where contacts interacted with whom the given user follows.
2973 // Contacts who already are in the user's contact table are ignored.
2974 $results = DBA::select('contact', [],
2975 ["`id` IN (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` IN
2976 (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` = ?)
2977 AND NOT `cid` IN (SELECT `id` FROM `contact` WHERE `uid` = ? AND `nurl` IN
2978 (SELECT `nurl` FROM `contact` WHERE `uid` = ? AND `rel` IN (?, ?))))
2979 AND NOT `hidden` AND `network` IN (?, ?, ?, ?)",
2980 $cid, 0, $uid, Contact::FRIEND, Contact::SHARING,
2981 Protocol::ACTIVITYPUB, Protocol::DFRN, $diaspora, $ostatus],
2982 ['order' => ['last-item' => true], 'limit' => $totallimit]
2985 while ($contact = DBA::fetch($results)) {
2986 $contacts[$contact['id']] = $contact;
2988 DBA::close($results);
2990 Logger::info('Contacts of contacts who are followed by the given user', ['uid' => $uid, 'cid' => $cid, 'count' => count($contacts)]);
2992 if (count($contacts) >= $totallimit) {
2993 return array_slice($contacts, $start, $limit);
2996 // The query returns contacts where contacts interacted with whom also interacted with the given user.
2997 // Contacts who already are in the user's contact table are ignored.
2998 $results = DBA::select('contact', [],
2999 ["`id` IN (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` IN
3000 (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ?)
3001 AND NOT `cid` IN (SELECT `id` FROM `contact` WHERE `uid` = ? AND `nurl` IN
3002 (SELECT `nurl` FROM `contact` WHERE `uid` = ? AND `rel` IN (?, ?))))
3003 AND NOT `hidden` AND `network` IN (?, ?, ?, ?)",
3004 $cid, 0, $uid, Contact::FRIEND, Contact::SHARING,
3005 Protocol::ACTIVITYPUB, Protocol::DFRN, $diaspora, $ostatus],
3006 ['order' => ['last-item' => true], 'limit' => $totallimit]
3009 while ($contact = DBA::fetch($results)) {
3010 $contacts[$contact['id']] = $contact;
3012 DBA::close($results);
3014 Logger::info('Contacts of contacts who are following the given user', ['uid' => $uid, 'cid' => $cid, 'count' => count($contacts)]);
3016 if (count($contacts) >= $totallimit) {
3017 return array_slice($contacts, $start, $limit);
3020 // The query returns contacts that follow the given user but aren't followed by that user.
3021 $results = DBA::select('contact', [],
3022 ["`nurl` IN (SELECT `nurl` FROM `contact` WHERE `uid` = ? AND `rel` = ?)
3023 AND NOT `hidden` AND `uid` = ? AND `network` IN (?, ?, ?, ?)",
3024 $uid, Contact::FOLLOWER, 0,
3025 Protocol::ACTIVITYPUB, Protocol::DFRN, $diaspora, $ostatus],
3026 ['order' => ['last-item' => true], 'limit' => $totallimit]
3029 while ($contact = DBA::fetch($results)) {
3030 $contacts[$contact['id']] = $contact;
3032 DBA::close($results);
3034 Logger::info('Followers that are not followed by the given user', ['uid' => $uid, 'cid' => $cid, 'count' => count($contacts)]);
3036 if (count($contacts) >= $totallimit) {
3037 return array_slice($contacts, $start, $limit);
3040 // The query returns any contact that isn't followed by that user.
3041 $results = DBA::select('contact', [],
3042 ["NOT `nurl` IN (SELECT `nurl` FROM `contact` WHERE `uid` = ? AND `rel` IN (?, ?))
3043 AND NOT `hidden` AND `uid` = ? AND `network` IN (?, ?, ?, ?)",
3044 $uid, Contact::FRIEND, Contact::SHARING, 0,
3045 Protocol::ACTIVITYPUB, Protocol::DFRN, $diaspora, $ostatus],
3046 ['order' => ['last-item' => true], 'limit' => $totallimit]
3049 while ($contact = DBA::fetch($results)) {
3050 $contacts[$contact['id']] = $contact;
3052 DBA::close($results);
3054 Logger::info('Any contact', ['uid' => $uid, 'cid' => $cid, 'count' => count($contacts)]);
3056 return array_slice($contacts, $start, $limit);
3060 * Returns a list of all common friends between two given public contact ids.
3062 * @param int $cid1 first public contact id
3063 * @param int $cid2 second public contact id
3066 public static function countContactsOfContact(int $cid)
3068 return DBA::count('contact',
3069 ["`id` IN (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` = ?)
3070 OR `id` IN (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ?)",
3076 * Returns a list of all contacts of a given public contact id.
3078 * @param int $cid public contact id
3079 * @param int $start optional, default 0
3080 * @param int $limit optional, default 80
3083 public static function getContactsOfContact(int $cid, int $start = 0, int $limit = 80)
3085 return DBA::selectToArray('contact', [],
3086 ["`id` IN (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` = ?)
3087 OR `id` IN (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ?)",
3089 ['limit' => [$start, $limit]]
3094 * Add public contacts from an array
3096 * @param array $urls
3097 * @return array result "count", "added" and "updated"
3099 public static function addByUrls(array $urls)
3105 foreach ($urls as $url) {
3106 $contact = Contact::getByURL($url, false, ['id']);
3107 if (empty($contact['id'])) {
3108 Worker::add(PRIORITY_LOW, 'AddContact', 0, $url);
3111 Worker::add(PRIORITY_LOW, 'UpdateContact', $contact['id']);
3117 return ['count' => $count, 'added' => $added, 'updated' => $updated];
3121 * Set the last date that the contact had posted something
3123 * This functionality is currently unused
3125 * @param string $data probing result
3126 * @param bool $force force updating
3128 private static function setLastUpdate(array $data, bool $force = false)
3130 $contact = self::getByURL($data['url'], false, []);
3131 if (empty($contact)) {
3134 if (!$force && !GServer::updateNeeded($contact['created'], $contact['updated'], $contact['last_failure'], $contact['last_contact'])) {
3135 Logger::info("Don't update profile", ['url' => $data['url'], 'updated' => $contact['updated']]);
3139 if (self::updateFromNoScrape($data)) {
3143 if (!empty($data['outbox'])) {
3144 self::updateFromOutbox($data['outbox'], $data);
3145 } elseif (!empty($data['poll']) && ($data['network'] == Protocol::ACTIVITYPUB)) {
3146 self::updateFromOutbox($data['poll'], $data);
3147 } elseif (!empty($data['poll'])) {
3148 self::updateFromFeed($data);
3153 * Update a global contact via the "noscrape" endpoint
3155 * @param string $data Probing result
3157 * @return bool 'true' if update was successful or the server was unreachable
3159 private static function updateFromNoScrape(array $data)
3161 // Check the 'noscrape' endpoint when it is a Friendica server
3162 $gserver = DBA::selectFirst('gserver', ['noscrape'], ["`nurl` = ? AND `noscrape` != ''",
3163 Strings::normaliseLink($data['baseurl'])]);
3164 if (!DBA::isResult($gserver)) {
3168 $curlResult = DI::httpRequest()->get($gserver['noscrape'] . '/' . $data['nick']);
3170 if ($curlResult->isSuccess() && !empty($curlResult->getBody())) {
3171 $noscrape = json_decode($curlResult->getBody(), true);
3172 if (!empty($noscrape) && !empty($noscrape['updated'])) {
3173 $noscrape['updated'] = DateTimeFormat::utc($noscrape['updated'], DateTimeFormat::MYSQL);
3174 $fields = ['failed' => false, 'last_contact' => DateTimeFormat::utcNow(), 'updated' => $noscrape['updated']];
3175 DBA::update('contact', $fields, ['nurl' => Strings::normaliseLink($data['url'])]);
3178 } elseif ($curlResult->isTimeout()) {
3179 // On a timeout return the existing value, but mark the contact as failure
3180 $fields = ['failed' => true, 'last_failure' => DateTimeFormat::utcNow()];
3181 DBA::update('contact', $fields, ['nurl' => Strings::normaliseLink($data['url'])]);
3188 * Update a global contact via an ActivityPub Outbox
3190 * @param string $feed
3191 * @param array $data Probing result
3192 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3194 private static function updateFromOutbox(string $feed, array $data)
3196 $outbox = ActivityPub::fetchContent($feed);
3197 if (empty($outbox)) {
3201 if (!empty($outbox['orderedItems'])) {
3202 $items = $outbox['orderedItems'];
3203 } elseif (!empty($outbox['first']['orderedItems'])) {
3204 $items = $outbox['first']['orderedItems'];
3205 } elseif (!empty($outbox['first']['href']) && ($outbox['first']['href'] != $feed)) {
3206 self::updateFromOutbox($outbox['first']['href'], $data);
3208 } elseif (!empty($outbox['first'])) {
3209 if (is_string($outbox['first']) && ($outbox['first'] != $feed)) {
3210 self::updateFromOutbox($outbox['first'], $data);
3212 Logger::warning('Unexpected data', ['outbox' => $outbox]);
3220 foreach ($items as $activity) {
3221 if (!empty($activity['published'])) {
3222 $published = DateTimeFormat::utc($activity['published']);
3223 } elseif (!empty($activity['object']['published'])) {
3224 $published = DateTimeFormat::utc($activity['object']['published']);
3229 if ($last_updated < $published) {
3230 $last_updated = $published;
3234 if (empty($last_updated)) {
3238 $fields = ['failed' => false, 'last_contact' => DateTimeFormat::utcNow(), 'updated' => $last_updated];
3239 DBA::update('contact', $fields, ['nurl' => Strings::normaliseLink($data['url'])]);
3243 * Update a global contact via an XML feed
3245 * @param string $data Probing result
3247 private static function updateFromFeed(array $data)
3249 // Search for the newest entry in the feed
3250 $curlResult = DI::httpRequest()->get($data['poll']);
3251 if (!$curlResult->isSuccess()) {
3252 $fields = ['failed' => true, 'last_failure' => DateTimeFormat::utcNow()];
3253 DBA::update('contact', $fields, ['nurl' => Strings::normaliseLink($data['url'])]);
3255 Logger::info("Profile wasn't reachable (no feed)", ['url' => $data['url']]);
3259 $doc = new DOMDocument();
3260 @$doc->loadXML($curlResult->getBody());
3262 $xpath = new DOMXPath($doc);
3263 $xpath->registerNamespace('atom', 'http://www.w3.org/2005/Atom');
3265 $entries = $xpath->query('/atom:feed/atom:entry');
3269 foreach ($entries as $entry) {
3270 $published_item = $xpath->query('atom:published/text()', $entry)->item(0);
3271 $updated_item = $xpath->query('atom:updated/text()' , $entry)->item(0);
3272 $published = !empty($published_item->nodeValue) ? DateTimeFormat::utc($published_item->nodeValue) : null;
3273 $updated = !empty($updated_item->nodeValue) ? DateTimeFormat::utc($updated_item->nodeValue) : null;
3275 if (empty($published) || empty($updated)) {
3276 Logger::notice('Invalid entry for XPath.', ['entry' => $entry, 'url' => $data['url']]);
3280 if ($last_updated < $published) {
3281 $last_updated = $published;
3284 if ($last_updated < $updated) {
3285 $last_updated = $updated;
3289 if (empty($last_updated)) {
3293 $fields = ['failed' => false, 'last_contact' => DateTimeFormat::utcNow(), 'updated' => $last_updated];
3294 DBA::update('contact', $fields, ['nurl' => Strings::normaliseLink($data['url'])]);
3298 * Returns a random, global contact of the current node
3300 * @return string The profile URL
3303 public static function getRandomUrl()
3305 $r = DBA::selectFirst('contact', ['url'], [
3306 "`uid` = ? AND `network` = ? AND NOT `failed` AND `last-item` > ?",
3307 0, Protocol::DFRN, DateTimeFormat::utc('now - 1 month'),
3308 ], ['order' => ['RAND()']]);
3310 if (DBA::isResult($r)) {