3 * @copyright Copyright (C) 2020, Friendica
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 namespace Friendica\Model;
24 use Friendica\App\BaseURL;
25 use Friendica\Content\Pager;
26 use Friendica\Core\Hook;
27 use Friendica\Core\Logger;
28 use Friendica\Core\Protocol;
29 use Friendica\Core\Session;
30 use Friendica\Core\System;
31 use Friendica\Core\Worker;
32 use Friendica\Database\DBA;
34 use Friendica\Model\Notify\Type;
35 use Friendica\Network\HTTPException;
36 use Friendica\Network\Probe;
37 use Friendica\Protocol\Activity;
38 use Friendica\Protocol\ActivityPub;
39 use Friendica\Protocol\DFRN;
40 use Friendica\Protocol\Diaspora;
41 use Friendica\Protocol\OStatus;
42 use Friendica\Protocol\Salmon;
43 use Friendica\Util\DateTimeFormat;
44 use Friendica\Util\Images;
45 use Friendica\Util\Network;
46 use Friendica\Util\Proxy;
47 use Friendica\Util\Strings;
50 * functions for interacting with a contact
55 * @deprecated since version 2019.03
56 * @see User::PAGE_FLAGS_NORMAL
58 const PAGE_NORMAL = User::PAGE_FLAGS_NORMAL;
60 * @deprecated since version 2019.03
61 * @see User::PAGE_FLAGS_SOAPBOX
63 const PAGE_SOAPBOX = User::PAGE_FLAGS_SOAPBOX;
65 * @deprecated since version 2019.03
66 * @see User::PAGE_FLAGS_COMMUNITY
68 const PAGE_COMMUNITY = User::PAGE_FLAGS_COMMUNITY;
70 * @deprecated since version 2019.03
71 * @see User::PAGE_FLAGS_FREELOVE
73 const PAGE_FREELOVE = User::PAGE_FLAGS_FREELOVE;
75 * @deprecated since version 2019.03
76 * @see User::PAGE_FLAGS_BLOG
78 const PAGE_BLOG = User::PAGE_FLAGS_BLOG;
80 * @deprecated since version 2019.03
81 * @see User::PAGE_FLAGS_PRVGROUP
83 const PAGE_PRVGROUP = User::PAGE_FLAGS_PRVGROUP;
91 * TYPE_UNKNOWN - the account has been imported from gcontact where this is the default type value
93 * TYPE_PERSON - the account belongs to a person
94 * Associated page types: PAGE_NORMAL, PAGE_SOAPBOX, PAGE_FREELOVE
96 * TYPE_ORGANISATION - the account belongs to an organisation
97 * Associated page type: PAGE_SOAPBOX
99 * TYPE_NEWS - the account is a news reflector
100 * Associated page type: PAGE_SOAPBOX
102 * TYPE_COMMUNITY - the account is community forum
103 * Associated page types: PAGE_COMMUNITY, PAGE_PRVGROUP
105 * TYPE_RELAY - the account is a relay
106 * This will only be assigned to contacts, not to user accounts
109 const TYPE_UNKNOWN = -1;
110 const TYPE_PERSON = User::ACCOUNT_TYPE_PERSON;
111 const TYPE_ORGANISATION = User::ACCOUNT_TYPE_ORGANISATION;
112 const TYPE_NEWS = User::ACCOUNT_TYPE_NEWS;
113 const TYPE_COMMUNITY = User::ACCOUNT_TYPE_COMMUNITY;
114 const TYPE_RELAY = User::ACCOUNT_TYPE_RELAY;
133 * @param array $fields Array of selected fields, empty for all
134 * @param array $condition Array of fields for condition
135 * @param array $params Array of several parameters
139 public static function selectToArray(array $fields = [], array $condition = [], array $params = [])
141 return DBA::selectToArray('contact', $fields, $condition, $params);
145 * @param array $fields Array of selected fields, empty for all
146 * @param array $condition Array of fields for condition
147 * @param array $params Array of several parameters
151 public static function selectFirst(array $fields = [], array $condition = [], array $params = [])
153 $contact = DBA::selectFirst('contact', $fields, $condition, $params);
159 * Insert a row into the contact table
160 * Important: You can't use DBA::lastInsertId() after this call since it will be set to 0.
162 * @param array $fields field array
163 * @param bool $on_duplicate_update Do an update on a duplicate entry
165 * @return boolean was the insert successful?
168 public static function insert(array $fields, bool $on_duplicate_update = false)
170 $ret = DBA::insert('contact', $fields, $on_duplicate_update);
171 $contact = DBA::selectFirst('contact', ['nurl', 'uid'], ['id' => DBA::lastInsertId()]);
172 if (!DBA::isResult($contact)) {
177 // Search for duplicated contacts and get rid of them
178 self::removeDuplicates($contact['nurl'], $contact['uid']);
184 * @param integer $id Contact ID
185 * @param array $fields Array of selected fields, empty for all
186 * @return array|boolean Contact record if it exists, false otherwise
189 public static function getById($id, $fields = [])
191 return DBA::selectFirst('contact', $fields, ['id' => $id]);
195 * Fetches a contact by a given url
197 * @param string $url profile url
198 * @param boolean $update true = always update, false = never update, null = update when not found or outdated
199 * @param array $fields Field list
200 * @param integer $uid User ID of the contact
201 * @return array contact array
203 public static function getByURL(string $url, $update = null, array $fields = [], int $uid = 0)
205 if ($update || is_null($update)) {
206 $cid = self::getIdForURL($url, $uid, $update);
211 $contact = self::getById($cid, $fields);
212 if (empty($contact)) {
218 // Add internal fields
220 if (!empty($fields)) {
221 foreach (['id', 'updated', 'network'] as $internal) {
222 if (!in_array($internal, $fields)) {
223 $fields[] = $internal;
224 $removal[] = $internal;
229 // We first try the nurl (http://server.tld/nick), most common case
230 $options = ['order' => ['id']];
231 $contact = DBA::selectFirst('contact', $fields, ['nurl' => Strings::normaliseLink($url), 'uid' => $uid, 'deleted' => false], $options);
233 // Then the addr (nick@server.tld)
234 if (!DBA::isResult($contact)) {
235 $contact = DBA::selectFirst('contact', $fields, ['addr' => str_replace('acct:', '', $url), 'uid' => $uid, 'deleted' => false], $options);
238 // Then the alias (which could be anything)
239 if (!DBA::isResult($contact)) {
240 // The link could be provided as http although we stored it as https
241 $ssl_url = str_replace('http://', 'https://', $url);
242 $condition = ['`alias` IN (?, ?, ?) AND `uid` = ? AND NOT `deleted`', $url, Strings::normaliseLink($url), $ssl_url, $uid];
243 $contact = DBA::selectFirst('contact', $fields, $condition, $options);
246 if (!DBA::isResult($contact)) {
250 // Update the contact in the background if needed
251 if ((($contact['updated'] < DateTimeFormat::utc('now -7 days')) || empty($contact['avatar'])) &&
252 in_array($contact['network'], Protocol::FEDERATED)) {
253 Worker::add(PRIORITY_LOW, "UpdateContact", $contact['id'], ($uid == 0 ? 'force' : ''));
256 // Remove the internal fields
257 foreach ($removal as $internal) {
258 unset($contact[$internal]);
265 * Fetches a contact for a given user by a given url.
266 * In difference to "getByURL" the function will fetch a public contact when no user contact had been found.
268 * @param string $url profile url
269 * @param integer $uid User ID of the contact
270 * @param boolean $update true = always update, false = never update, null = update when not found or outdated
271 * @param array $fields Field list
272 * @return array contact array
274 public static function getByURLForUser(string $url, int $uid = 0, $update = false, array $fields = [])
277 $contact = self::getByURL($url, $update, $fields, $uid);
278 if (!empty($contact)) {
279 if (!empty($contact['id'])) {
280 $contact['cid'] = $contact['id'];
287 $contact = self::getByURL($url, $update, $fields);
288 if (!empty($contact['id'])) {
290 $contact['zid'] = $contact['id'];
296 * Tests if the given contact is a follower
298 * @param int $cid Either public contact id or user's contact id
299 * @param int $uid User ID
301 * @return boolean is the contact id a follower?
302 * @throws HTTPException\InternalServerErrorException
303 * @throws \ImagickException
305 public static function isFollower($cid, $uid)
307 if (self::isBlockedByUser($cid, $uid)) {
311 $cdata = self::getPublicAndUserContacID($cid, $uid);
312 if (empty($cdata['user'])) {
316 $condition = ['id' => $cdata['user'], 'rel' => [self::FOLLOWER, self::FRIEND]];
317 return DBA::exists('contact', $condition);
321 * Tests if the given contact url is a follower
323 * @param string $url Contact URL
324 * @param int $uid User ID
326 * @return boolean is the contact id a follower?
327 * @throws HTTPException\InternalServerErrorException
328 * @throws \ImagickException
330 public static function isFollowerByURL($url, $uid)
332 $cid = self::getIdForURL($url, $uid, false);
338 return self::isFollower($cid, $uid);
342 * Tests if the given user follow the given contact
344 * @param int $cid Either public contact id or user's contact id
345 * @param int $uid User ID
347 * @return boolean is the contact url being followed?
348 * @throws HTTPException\InternalServerErrorException
349 * @throws \ImagickException
351 public static function isSharing($cid, $uid)
353 if (self::isBlockedByUser($cid, $uid)) {
357 $cdata = self::getPublicAndUserContacID($cid, $uid);
358 if (empty($cdata['user'])) {
362 $condition = ['id' => $cdata['user'], 'rel' => [self::SHARING, self::FRIEND]];
363 return DBA::exists('contact', $condition);
367 * Tests if the given user follow the given contact url
369 * @param string $url Contact URL
370 * @param int $uid User ID
372 * @return boolean is the contact url being followed?
373 * @throws HTTPException\InternalServerErrorException
374 * @throws \ImagickException
376 public static function isSharingByURL($url, $uid)
378 $cid = self::getIdForURL($url, $uid, false);
384 return self::isSharing($cid, $uid);
388 * Get the basepath for a given contact link
390 * @param string $url The contact link
391 * @param boolean $dont_update Don't update the contact
393 * @return string basepath
394 * @throws HTTPException\InternalServerErrorException
395 * @throws \ImagickException
397 public static function getBasepath($url, $dont_update = false)
399 $contact = DBA::selectFirst('contact', ['id', 'baseurl'], ['uid' => 0, 'nurl' => Strings::normaliseLink($url)]);
400 if (!DBA::isResult($contact)) {
404 if (!empty($contact['baseurl'])) {
405 return $contact['baseurl'];
406 } elseif ($dont_update) {
410 // Update the existing contact
411 self::updateFromProbe($contact['id'], '', true);
413 // And fetch the result
414 $contact = DBA::selectFirst('contact', ['baseurl'], ['id' => $contact['id']]);
415 if (empty($contact['baseurl'])) {
416 Logger::info('No baseurl for contact', ['url' => $url]);
420 Logger::info('Found baseurl for contact', ['url' => $url, 'baseurl' => $contact['baseurl']]);
421 return $contact['baseurl'];
425 * Check if the given contact url is on the same server
427 * @param string $url The contact link
429 * @return boolean Is it the same server?
431 public static function isLocal($url)
433 return Strings::compareLink(self::getBasepath($url, true), DI::baseUrl());
437 * Check if the given contact ID is on the same server
439 * @param string $url The contact link
441 * @return boolean Is it the same server?
443 public static function isLocalById(int $cid)
445 $contact = DBA::selectFirst('contact', ['url', 'baseurl'], ['id' => $cid]);
446 if (!DBA::isResult($contact)) {
450 if (empty($contact['baseurl'])) {
451 $baseurl = self::getBasepath($contact['url'], true);
453 $baseurl = $contact['baseurl'];
456 return Strings::compareLink($baseurl, DI::baseUrl());
460 * Returns the public contact id of the given user id
462 * @param integer $uid User ID
464 * @return integer|boolean Public contact id for given user id
467 public static function getPublicIdByUserId($uid)
469 $self = DBA::selectFirst('contact', ['url'], ['self' => true, 'uid' => $uid]);
470 if (!DBA::isResult($self)) {
473 return self::getIdForURL($self['url'], 0, false);
477 * Returns the contact id for the user and the public contact id for a given contact id
479 * @param int $cid Either public contact id or user's contact id
480 * @param int $uid User ID
482 * @return array with public and user's contact id
483 * @throws HTTPException\InternalServerErrorException
484 * @throws \ImagickException
486 public static function getPublicAndUserContacID($cid, $uid)
488 if (empty($uid) || empty($cid)) {
492 $contact = DBA::selectFirst('contact', ['id', 'uid', 'url'], ['id' => $cid]);
493 if (!DBA::isResult($contact)) {
497 // We quit when the user id don't match the user id of the provided contact
498 if (($contact['uid'] != $uid) && ($contact['uid'] != 0)) {
502 if ($contact['uid'] != 0) {
503 $pcid = Contact::getIdForURL($contact['url'], 0, false, ['url' => $contact['url']]);
507 $ucid = $contact['id'];
509 $pcid = $contact['id'];
510 $ucid = Contact::getIdForURL($contact['url'], $uid, false);
513 return ['public' => $pcid, 'user' => $ucid];
517 * Returns contact details for a given contact id in combination with a user id
519 * @param int $cid A contact ID
520 * @param int $uid The User ID
521 * @param array $fields The selected fields for the contact
523 * @return array The contact details
527 public static function getContactForUser($cid, $uid, array $fields = [])
529 $contact = DBA::selectFirst('contact', $fields, ['id' => $cid, 'uid' => $uid]);
531 if (!DBA::isResult($contact)) {
539 * Block contact id for user id
541 * @param int $cid Either public contact id or user's contact id
542 * @param int $uid User ID
543 * @param boolean $blocked Is the contact blocked or unblocked?
546 public static function setBlockedForUser($cid, $uid, $blocked)
548 $cdata = self::getPublicAndUserContacID($cid, $uid);
553 if ($cdata['user'] != 0) {
554 DBA::update('contact', ['blocked' => $blocked], ['id' => $cdata['user'], 'pending' => false]);
557 DBA::update('user-contact', ['blocked' => $blocked], ['cid' => $cdata['public'], 'uid' => $uid], true);
561 * Returns "block" state for contact id and user id
563 * @param int $cid Either public contact id or user's contact id
564 * @param int $uid User ID
566 * @return boolean is the contact id blocked for the given user?
569 public static function isBlockedByUser($cid, $uid)
571 $cdata = self::getPublicAndUserContacID($cid, $uid);
576 $public_blocked = false;
578 if (!empty($cdata['public'])) {
579 $public_contact = DBA::selectFirst('user-contact', ['blocked'], ['cid' => $cdata['public'], 'uid' => $uid]);
580 if (DBA::isResult($public_contact)) {
581 $public_blocked = $public_contact['blocked'];
585 $user_blocked = $public_blocked;
587 if (!empty($cdata['user'])) {
588 $user_contact = DBA::selectFirst('contact', ['blocked'], ['id' => $cdata['user'], 'pending' => false]);
589 if (DBA::isResult($user_contact)) {
590 $user_blocked = $user_contact['blocked'];
594 if ($user_blocked != $public_blocked) {
595 DBA::update('user-contact', ['blocked' => $user_blocked], ['cid' => $cdata['public'], 'uid' => $uid], true);
598 return $user_blocked;
602 * Ignore contact id for user id
604 * @param int $cid Either public contact id or user's contact id
605 * @param int $uid User ID
606 * @param boolean $ignored Is the contact ignored or unignored?
609 public static function setIgnoredForUser($cid, $uid, $ignored)
611 $cdata = self::getPublicAndUserContacID($cid, $uid);
616 if ($cdata['user'] != 0) {
617 DBA::update('contact', ['readonly' => $ignored], ['id' => $cdata['user'], 'pending' => false]);
620 DBA::update('user-contact', ['ignored' => $ignored], ['cid' => $cdata['public'], 'uid' => $uid], true);
624 * Returns "ignore" state for contact id and user id
626 * @param int $cid Either public contact id or user's contact id
627 * @param int $uid User ID
629 * @return boolean is the contact id ignored for the given user?
632 public static function isIgnoredByUser($cid, $uid)
634 $cdata = self::getPublicAndUserContacID($cid, $uid);
639 $public_ignored = false;
641 if (!empty($cdata['public'])) {
642 $public_contact = DBA::selectFirst('user-contact', ['ignored'], ['cid' => $cdata['public'], 'uid' => $uid]);
643 if (DBA::isResult($public_contact)) {
644 $public_ignored = $public_contact['ignored'];
648 $user_ignored = $public_ignored;
650 if (!empty($cdata['user'])) {
651 $user_contact = DBA::selectFirst('contact', ['readonly'], ['id' => $cdata['user'], 'pending' => false]);
652 if (DBA::isResult($user_contact)) {
653 $user_ignored = $user_contact['readonly'];
657 if ($user_ignored != $public_ignored) {
658 DBA::update('user-contact', ['ignored' => $user_ignored], ['cid' => $cdata['public'], 'uid' => $uid], true);
661 return $user_ignored;
665 * Set "collapsed" for contact id and user id
667 * @param int $cid Either public contact id or user's contact id
668 * @param int $uid User ID
669 * @param boolean $collapsed are the contact's posts collapsed or uncollapsed?
672 public static function setCollapsedForUser($cid, $uid, $collapsed)
674 $cdata = self::getPublicAndUserContacID($cid, $uid);
679 DBA::update('user-contact', ['collapsed' => $collapsed], ['cid' => $cdata['public'], 'uid' => $uid], true);
683 * Returns "collapsed" state for contact id and user id
685 * @param int $cid Either public contact id or user's contact id
686 * @param int $uid User ID
688 * @return boolean is the contact id blocked for the given user?
689 * @throws HTTPException\InternalServerErrorException
690 * @throws \ImagickException
692 public static function isCollapsedByUser($cid, $uid)
694 $cdata = self::getPublicAndUserContacID($cid, $uid);
701 if (!empty($cdata['public'])) {
702 $public_contact = DBA::selectFirst('user-contact', ['collapsed'], ['cid' => $cdata['public'], 'uid' => $uid]);
703 if (DBA::isResult($public_contact)) {
704 $collapsed = $public_contact['collapsed'];
712 * Returns a list of contacts belonging in a group
718 public static function getByGroupId($gid)
723 $stmt = DBA::p('SELECT `group_member`.`contact-id`, `contact`.*
725 INNER JOIN `group_member`
726 ON `contact`.`id` = `group_member`.`contact-id`
728 AND `contact`.`uid` = ?
729 AND NOT `contact`.`self`
730 AND NOT `contact`.`deleted`
731 AND NOT `contact`.`blocked`
732 AND NOT `contact`.`pending`
733 ORDER BY `contact`.`name` ASC',
738 if (DBA::isResult($stmt)) {
739 $return = DBA::toArray($stmt);
747 * Creates the self-contact for the provided user id
750 * @return bool Operation success
751 * @throws HTTPException\InternalServerErrorException
753 public static function createSelfFromUserId($uid)
755 // Only create the entry if it doesn't exist yet
756 if (DBA::exists('contact', ['uid' => $uid, 'self' => true])) {
760 $user = DBA::selectFirst('user', ['uid', 'username', 'nickname'], ['uid' => $uid]);
761 if (!DBA::isResult($user)) {
765 $return = DBA::insert('contact', [
766 'uid' => $user['uid'],
767 'created' => DateTimeFormat::utcNow(),
769 'name' => $user['username'],
770 'nick' => $user['nickname'],
771 'photo' => DI::baseUrl() . '/photo/profile/' . $user['uid'] . '.jpg',
772 'thumb' => DI::baseUrl() . '/photo/avatar/' . $user['uid'] . '.jpg',
773 'micro' => DI::baseUrl() . '/photo/micro/' . $user['uid'] . '.jpg',
776 'url' => DI::baseUrl() . '/profile/' . $user['nickname'],
777 'nurl' => Strings::normaliseLink(DI::baseUrl() . '/profile/' . $user['nickname']),
778 'addr' => $user['nickname'] . '@' . substr(DI::baseUrl(), strpos(DI::baseUrl(), '://') + 3),
779 'request' => DI::baseUrl() . '/dfrn_request/' . $user['nickname'],
780 'notify' => DI::baseUrl() . '/dfrn_notify/' . $user['nickname'],
781 'poll' => DI::baseUrl() . '/dfrn_poll/' . $user['nickname'],
782 'confirm' => DI::baseUrl() . '/dfrn_confirm/' . $user['nickname'],
783 'poco' => DI::baseUrl() . '/poco/' . $user['nickname'],
784 'name-date' => DateTimeFormat::utcNow(),
785 'uri-date' => DateTimeFormat::utcNow(),
786 'avatar-date' => DateTimeFormat::utcNow(),
794 * Updates the self-contact for the provided user id
797 * @param boolean $update_avatar Force the avatar update
798 * @throws HTTPException\InternalServerErrorException
800 public static function updateSelfFromUserID($uid, $update_avatar = false)
802 $fields = ['id', 'name', 'nick', 'location', 'about', 'keywords', 'avatar',
803 'xmpp', 'contact-type', 'forum', 'prv', 'avatar-date', 'url', 'nurl', 'unsearchable',
804 'photo', 'thumb', 'micro', 'addr', 'request', 'notify', 'poll', 'confirm', 'poco'];
805 $self = DBA::selectFirst('contact', $fields, ['uid' => $uid, 'self' => true]);
806 if (!DBA::isResult($self)) {
810 $fields = ['nickname', 'page-flags', 'account-type'];
811 $user = DBA::selectFirst('user', $fields, ['uid' => $uid]);
812 if (!DBA::isResult($user)) {
816 $fields = ['name', 'photo', 'thumb', 'about', 'address', 'locality', 'region',
817 'country-name', 'pub_keywords', 'xmpp', 'net-publish'];
818 $profile = DBA::selectFirst('profile', $fields, ['uid' => $uid]);
819 if (!DBA::isResult($profile)) {
823 $file_suffix = 'jpg';
825 $fields = ['name' => $profile['name'], 'nick' => $user['nickname'],
826 'avatar-date' => $self['avatar-date'], 'location' => Profile::formatLocation($profile),
827 'about' => $profile['about'], 'keywords' => $profile['pub_keywords'],
828 'contact-type' => $user['account-type'],
829 'xmpp' => $profile['xmpp']];
831 $avatar = Photo::selectFirst(['resource-id', 'type'], ['uid' => $uid, 'profile' => true]);
832 if (DBA::isResult($avatar)) {
833 if ($update_avatar) {
834 $fields['avatar-date'] = DateTimeFormat::utcNow();
837 // Creating the path to the avatar, beginning with the file suffix
838 $types = Images::supportedTypes();
839 if (isset($types[$avatar['type']])) {
840 $file_suffix = $types[$avatar['type']];
843 // We are adding a timestamp value so that other systems won't use cached content
844 $timestamp = strtotime($fields['avatar-date']);
846 $prefix = DI::baseUrl() . '/photo/' .$avatar['resource-id'] . '-';
847 $suffix = '.' . $file_suffix . '?ts=' . $timestamp;
849 $fields['photo'] = $prefix . '4' . $suffix;
850 $fields['thumb'] = $prefix . '5' . $suffix;
851 $fields['micro'] = $prefix . '6' . $suffix;
853 // We hadn't found a photo entry, so we use the default avatar
854 $fields['photo'] = DI::baseUrl() . '/images/person-300.jpg';
855 $fields['thumb'] = DI::baseUrl() . '/images/person-80.jpg';
856 $fields['micro'] = DI::baseUrl() . '/images/person-48.jpg';
859 $fields['avatar'] = DI::baseUrl() . '/photo/profile/' .$uid . '.' . $file_suffix;
860 $fields['forum'] = $user['page-flags'] == User::PAGE_FLAGS_COMMUNITY;
861 $fields['prv'] = $user['page-flags'] == User::PAGE_FLAGS_PRVGROUP;
862 $fields['unsearchable'] = !$profile['net-publish'];
864 // it seems as if ported accounts can have wrong values, so we make sure that now everything is fine.
865 $fields['url'] = DI::baseUrl() . '/profile/' . $user['nickname'];
866 $fields['nurl'] = Strings::normaliseLink($fields['url']);
867 $fields['addr'] = $user['nickname'] . '@' . substr(DI::baseUrl(), strpos(DI::baseUrl(), '://') + 3);
868 $fields['request'] = DI::baseUrl() . '/dfrn_request/' . $user['nickname'];
869 $fields['notify'] = DI::baseUrl() . '/dfrn_notify/' . $user['nickname'];
870 $fields['poll'] = DI::baseUrl() . '/dfrn_poll/'. $user['nickname'];
871 $fields['confirm'] = DI::baseUrl() . '/dfrn_confirm/' . $user['nickname'];
872 $fields['poco'] = DI::baseUrl() . '/poco/' . $user['nickname'];
876 foreach ($fields as $field => $content) {
877 if ($self[$field] != $content) {
883 if ($fields['name'] != $self['name']) {
884 $fields['name-date'] = DateTimeFormat::utcNow();
886 $fields['updated'] = DateTimeFormat::utcNow();
887 DBA::update('contact', $fields, ['id' => $self['id']]);
889 // Update the public contact as well
890 DBA::update('contact', $fields, ['uid' => 0, 'nurl' => $self['nurl']]);
892 // Update the profile
893 $fields = ['photo' => DI::baseUrl() . '/photo/profile/' .$uid . '.' . $file_suffix,
894 'thumb' => DI::baseUrl() . '/photo/avatar/' . $uid .'.' . $file_suffix];
895 DBA::update('profile', $fields, ['uid' => $uid]);
900 * Marks a contact for removal
902 * @param int $id contact id
904 * @throws HTTPException\InternalServerErrorException
906 public static function remove($id)
908 // We want just to make sure that we don't delete our "self" contact
909 $contact = DBA::selectFirst('contact', ['uid'], ['id' => $id, 'self' => false]);
910 if (!DBA::isResult($contact) || !intval($contact['uid'])) {
914 // Archive the contact
915 DBA::update('contact', ['archive' => true, 'network' => Protocol::PHANTOM, 'deleted' => true], ['id' => $id]);
917 // Delete it in the background
918 Worker::add(PRIORITY_MEDIUM, 'RemoveContact', $id);
922 * Sends an unfriend message. Does not remove the contact
924 * @param array $user User unfriending
925 * @param array $contact Contact unfriended
926 * @param boolean $dissolve Remove the contact on the remote side
928 * @throws HTTPException\InternalServerErrorException
929 * @throws \ImagickException
931 public static function terminateFriendship(array $user, array $contact, $dissolve = false)
933 if (empty($contact['network'])) {
937 $protocol = $contact['network'];
938 if (($protocol == Protocol::DFRN) && !self::isLegacyDFRNContact($contact)) {
939 $protocol = Protocol::ACTIVITYPUB;
942 if (($protocol == Protocol::DFRN) && $dissolve) {
943 DFRN::deliver($user, $contact, 'placeholder', true);
944 } elseif (in_array($protocol, [Protocol::OSTATUS, Protocol::DFRN])) {
945 // create an unfollow slap
947 $item['verb'] = Activity::O_UNFOLLOW;
948 $item['gravity'] = GRAVITY_ACTIVITY;
949 $item['follow'] = $contact["url"];
954 $item['attach'] = '';
955 $slap = OStatus::salmon($item, $user);
957 if (!empty($contact['notify'])) {
958 Salmon::slapper($user, $contact['notify'], $slap);
960 } elseif ($protocol == Protocol::DIASPORA) {
961 Diaspora::sendUnshare($user, $contact);
962 } elseif ($protocol == Protocol::ACTIVITYPUB) {
963 ActivityPub\Transmitter::sendContactUndo($contact['url'], $contact['id'], $user['uid']);
966 ActivityPub\Transmitter::sendContactReject($contact['url'], $contact['hub-verify'], $user['uid']);
972 * Marks a contact for archival after a communication issue delay
974 * Contact has refused to recognise us as a friend. We will start a countdown.
975 * If they still don't recognise us in 32 days, the relationship is over,
976 * and we won't waste any more time trying to communicate with them.
977 * This provides for the possibility that their database is temporarily messed
978 * up or some other transient event and that there's a possibility we could recover from it.
980 * @param array $contact contact to mark for archival
982 * @throws HTTPException\InternalServerErrorException
984 public static function markForArchival(array $contact)
986 if (!isset($contact['url']) && !empty($contact['id'])) {
987 $fields = ['id', 'url', 'archive', 'self', 'term-date'];
988 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact['id']]);
989 if (!DBA::isResult($contact)) {
992 } elseif (!isset($contact['url'])) {
993 Logger::info('Empty contact', ['contact' => $contact, 'callstack' => System::callstack(20)]);
996 Logger::info('Contact is marked for archival', ['id' => $contact['id']]);
998 // Contact already archived or "self" contact? => nothing to do
999 if ($contact['archive'] || $contact['self']) {
1003 if ($contact['term-date'] <= DBA::NULL_DATETIME) {
1004 DBA::update('contact', ['term-date' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
1005 DBA::update('contact', ['term-date' => DateTimeFormat::utcNow()], ['`nurl` = ? AND `term-date` <= ? AND NOT `self`', Strings::normaliseLink($contact['url']), DBA::NULL_DATETIME]);
1008 * We really should send a notification to the owner after 2-3 weeks
1009 * so they won't be surprised when the contact vanishes and can take
1010 * remedial action if this was a serious mistake or glitch
1013 /// @todo Check for contact vitality via probing
1014 $archival_days = DI::config()->get('system', 'archival_days', 32);
1016 $expiry = $contact['term-date'] . ' + ' . $archival_days . ' days ';
1017 if (DateTimeFormat::utcNow() > DateTimeFormat::utc($expiry)) {
1018 /* Relationship is really truly dead. archive them rather than
1019 * delete, though if the owner tries to unarchive them we'll start
1020 * the whole process over again.
1022 DBA::update('contact', ['archive' => true], ['id' => $contact['id']]);
1023 DBA::update('contact', ['archive' => true], ['nurl' => Strings::normaliseLink($contact['url']), 'self' => false]);
1024 GContact::updateFromPublicContactURL($contact['url']);
1030 * Cancels the archival countdown
1032 * @see Contact::markForArchival()
1034 * @param array $contact contact to be unmarked for archival
1036 * @throws \Exception
1038 public static function unmarkForArchival(array $contact)
1040 // Always unarchive the relay contact entry
1041 if (!empty($contact['batch']) && !empty($contact['term-date']) && ($contact['term-date'] > DBA::NULL_DATETIME)) {
1042 $fields = ['failed' => false, 'term-date' => DBA::NULL_DATETIME, 'archive' => false];
1043 $condition = ['uid' => 0, 'network' => Protocol::FEDERATED, 'batch' => $contact['batch'], 'contact-type' => self::TYPE_RELAY];
1044 DBA::update('contact', $fields, $condition);
1047 $condition = ['`id` = ? AND (`term-date` > ? OR `archive`)', $contact['id'], DBA::NULL_DATETIME];
1048 $exists = DBA::exists('contact', $condition);
1050 // We don't need to update, we never marked this contact for archival
1055 Logger::info('Contact is marked as vital again', ['id' => $contact['id']]);
1057 if (!isset($contact['url']) && !empty($contact['id'])) {
1058 $fields = ['id', 'url', 'batch'];
1059 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact['id']]);
1060 if (!DBA::isResult($contact)) {
1065 // It's a miracle. Our dead contact has inexplicably come back to life.
1066 $fields = ['failed' => false, 'term-date' => DBA::NULL_DATETIME, 'archive' => false];
1067 DBA::update('contact', $fields, ['id' => $contact['id']]);
1068 DBA::update('contact', $fields, ['nurl' => Strings::normaliseLink($contact['url']), 'self' => false]);
1069 GContact::updateFromPublicContactURL($contact['url']);
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 $data = DBA::selectFirst('gcontact', $fields, ['nurl' => Strings::normaliseLink($url)]);
1274 if (!DBA::isResult($data)) {
1275 $condition = ['alias' => [$url, Strings::normaliseLink($url), $ssl_url]];
1276 $data = DBA::selectFirst('contact', $fields, $condition);
1279 if (DBA::isResult($data)) {
1280 $data["pubkey"] = '';
1282 $data["priority"] = 0;
1283 $data["batch"] = '';
1284 $data["request"] = '';
1285 $data["confirm"] = '';
1290 $data = ActivityPub::probeProfile($url, false);
1291 if (!empty($data)) {
1295 $fields = ['url', 'addr', 'alias', 'notify', 'poll', 'name', 'nick',
1296 'photo', 'network', 'priority', 'batch', 'request', 'confirm'];
1297 $data = DBA::selectFirst('fcontact', $fields, ['url' => $url]);
1299 if (!DBA::isResult($data)) {
1300 $condition = ['alias' => [$url, Strings::normaliseLink($url), $ssl_url]];
1301 $data = DBA::selectFirst('contact', $fields, $condition);
1304 if (DBA::isResult($data)) {
1305 $data["pubkey"] = '';
1306 $data["keywords"] = '';
1307 $data["location"] = '';
1308 $data["about"] = '';
1317 * Fetch the contact id for a given URL and user
1319 * First lookup in the contact table to find a record matching either `url`, `nurl`,
1320 * `addr` or `alias`.
1322 * If there's no record and we aren't looking for a public contact, we quit.
1323 * If there's one, we check that it isn't time to update the picture else we
1324 * directly return the found contact id.
1326 * Second, we probe the provided $url whether it's http://server.tld/profile or
1327 * nick@server.tld. We quit if we can't get any info back.
1329 * Third, we create the contact record if it doesn't exist
1331 * Fourth, we update the existing record with the new data (avatar, alias, nick)
1332 * if there's any updates
1334 * @param string $url Contact URL
1335 * @param integer $uid The user id for the contact (0 = public contact)
1336 * @param boolean $update true = always update, false = never update, null = update when not found or outdated
1337 * @param array $default Default value for creating the contact when every else fails
1338 * @param boolean $in_loop Internally used variable to prevent an endless loop
1340 * @return integer Contact ID
1341 * @throws HTTPException\InternalServerErrorException
1342 * @throws \ImagickException
1344 public static function getIdForURL($url, $uid = 0, $update = null, $default = [], $in_loop = false)
1346 Logger::info('Get contact data', ['url' => $url, 'user' => $uid]);
1354 $contact = self::getByURL($url, false, ['id', 'avatar', 'updated', 'network'], $uid);
1356 if (!empty($contact)) {
1357 $contact_id = $contact["id"];
1359 if (empty($default) && in_array($contact['network'], [Protocol::MAIL, Protocol::PHANTOM]) && ($uid == 0)) {
1360 // Update public mail accounts via their user's accounts
1361 $fields = ['network', 'addr', 'name', 'nick', 'avatar', 'photo', 'thumb', 'micro'];
1362 $mailcontact = DBA::selectFirst('contact', $fields, ["`addr` = ? AND `network` = ? AND `uid` != 0", $url, Protocol::MAIL]);
1363 if (!DBA::isResult($mailcontact)) {
1364 $mailcontact = DBA::selectFirst('contact', $fields, ["`nurl` = ? AND `network` = ? AND `uid` != 0", $url, Protocol::MAIL]);
1367 if (DBA::isResult($mailcontact)) {
1368 DBA::update('contact', $mailcontact, ['id' => $contact_id]);
1372 if (empty($update)) {
1375 } elseif ($uid != 0) {
1376 // Non-existing user-specific contact, exiting
1380 if (!$update && empty($default)) {
1381 // When we don't want to update, we look if we know this contact in any way
1382 $data = self::getProbeDataFromDatabase($url, $contact_id);
1383 $background_update = true;
1384 } elseif (!$update && !empty($default['network'])) {
1385 // If there are default values, take these
1387 $background_update = false;
1390 $background_update = false;
1393 if ((empty($data) && is_null($update)) || $update) {
1394 $data = Probe::uri($url, "", $uid);
1397 // Take the default values when probing failed
1398 if (!empty($default) && !in_array($data["network"], array_merge(Protocol::NATIVE_SUPPORT, [Protocol::PUMPIO]))) {
1399 $data = array_merge($data, $default);
1402 if (empty($data) || ($data['network'] == Protocol::PHANTOM)) {
1403 Logger::info('No valid network found', ['url' => $url, 'data' => $data, 'callstack' => System::callstack(20)]);
1407 if (!empty($data['baseurl'])) {
1408 $data['baseurl'] = GServer::cleanURL($data['baseurl']);
1411 if (!empty($data['baseurl']) && empty($data['gsid'])) {
1412 $data['gsid'] = GServer::getID($data['baseurl']);
1415 if (!$contact_id && !empty($data['alias']) && ($data['alias'] != $data['url']) && !$in_loop) {
1416 $contact_id = self::getIdForURL($data["alias"], $uid, false, $default, true);
1422 'created' => DateTimeFormat::utcNow(),
1423 'url' => $data['url'],
1424 'nurl' => Strings::normaliseLink($data['url']),
1425 'addr' => $data['addr'] ?? '',
1426 'alias' => $data['alias'] ?? '',
1427 'notify' => $data['notify'] ?? '',
1428 'poll' => $data['poll'] ?? '',
1429 'name' => $data['name'] ?? '',
1430 'nick' => $data['nick'] ?? '',
1431 'keywords' => $data['keywords'] ?? '',
1432 'location' => $data['location'] ?? '',
1433 'about' => $data['about'] ?? '',
1434 'network' => $data['network'],
1435 'pubkey' => $data['pubkey'] ?? '',
1436 'rel' => self::SHARING,
1437 'priority' => $data['priority'] ?? 0,
1438 'batch' => $data['batch'] ?? '',
1439 'request' => $data['request'] ?? '',
1440 'confirm' => $data['confirm'] ?? '',
1441 'poco' => $data['poco'] ?? '',
1442 'baseurl' => $data['baseurl'] ?? '',
1443 'gsid' => $data['gsid'] ?? null,
1444 'name-date' => DateTimeFormat::utcNow(),
1445 'uri-date' => DateTimeFormat::utcNow(),
1446 'avatar-date' => DateTimeFormat::utcNow(),
1452 $condition = ['nurl' => Strings::normaliseLink($data["url"]), 'uid' => $uid, 'deleted' => false];
1454 // Before inserting we do check if the entry does exist now.
1455 $contact = DBA::selectFirst('contact', ['id'], $condition, ['order' => ['id']]);
1456 if (!DBA::isResult($contact)) {
1457 Logger::info('Create new contact', $fields);
1459 self::insert($fields);
1461 // We intentionally aren't using lastInsertId here. There is a chance for duplicates.
1462 $contact = DBA::selectFirst('contact', ['id'], $condition, ['order' => ['id']]);
1463 if (!DBA::isResult($contact)) {
1464 Logger::info('Contact creation failed', $fields);
1469 Logger::info('Contact had been created before', ['id' => $contact["id"], 'url' => $url, 'contact' => $fields]);
1472 $contact_id = $contact["id"];
1475 if (!empty($data['photo']) && ($data['network'] != Protocol::FEED)) {
1476 self::updateAvatar($contact_id, $data['photo']);
1479 if (in_array($data["network"], array_merge(Protocol::NATIVE_SUPPORT, [Protocol::PUMPIO]))) {
1480 if ($background_update) {
1481 // Update in the background when we fetched the data solely from the database
1482 Worker::add(PRIORITY_MEDIUM, "UpdateContact", $contact_id, ($uid == 0 ? 'force' : ''));
1484 // Else do a direct update
1485 self::updateFromProbe($contact_id, '', false);
1488 $fields = ['url', 'nurl', 'addr', 'alias', 'name', 'nick', 'keywords', 'location', 'about', 'avatar-date', 'baseurl', 'gsid'];
1489 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact_id]);
1491 // This condition should always be true
1492 if (!DBA::isResult($contact)) {
1497 'url' => $data['url'],
1498 'nurl' => Strings::normaliseLink($data['url']),
1499 'updated' => DateTimeFormat::utcNow(),
1503 $fields = ['addr', 'alias', 'name', 'nick', 'keywords', 'location', 'about', 'baseurl', 'gsid'];
1505 foreach ($fields as $field) {
1506 $updated[$field] = ($data[$field] ?? '') ?: $contact[$field];
1509 if (($updated['addr'] != $contact['addr']) || (!empty($data['alias']) && ($data['alias'] != $contact['alias']))) {
1510 $updated['uri-date'] = DateTimeFormat::utcNow();
1513 if (($data['name'] != $contact['name']) || ($data['nick'] != $contact['nick'])) {
1514 $updated['name-date'] = DateTimeFormat::utcNow();
1517 DBA::update('contact', $updated, ['id' => $contact_id], $contact);
1524 * Checks if the contact is archived
1526 * @param int $cid contact id
1528 * @return boolean Is the contact archived?
1529 * @throws HTTPException\InternalServerErrorException
1531 public static function isArchived(int $cid)
1537 $contact = DBA::selectFirst('contact', ['archive', 'url', 'batch'], ['id' => $cid]);
1538 if (!DBA::isResult($contact)) {
1542 if ($contact['archive']) {
1546 // Check status of ActivityPub endpoints
1547 $apcontact = APContact::getByURL($contact['url'], false);
1548 if (!empty($apcontact)) {
1549 if (!empty($apcontact['inbox']) && DBA::exists('inbox-status', ['archive' => true, 'url' => $apcontact['inbox']])) {
1553 if (!empty($apcontact['sharedinbox']) && DBA::exists('inbox-status', ['archive' => true, 'url' => $apcontact['sharedinbox']])) {
1558 // Check status of Diaspora endpoints
1559 if (!empty($contact['batch'])) {
1560 $condition = ['archive' => true, 'uid' => 0, 'network' => Protocol::FEDERATED, 'batch' => $contact['batch'], 'contact-type' => self::TYPE_RELAY];
1561 return DBA::exists('contact', $condition);
1568 * Checks if the contact is blocked
1570 * @param int $cid contact id
1572 * @return boolean Is the contact blocked?
1573 * @throws HTTPException\InternalServerErrorException
1575 public static function isBlocked($cid)
1581 $blocked = DBA::selectFirst('contact', ['blocked', 'url'], ['id' => $cid]);
1582 if (!DBA::isResult($blocked)) {
1586 if (Network::isUrlBlocked($blocked['url'])) {
1590 return (bool) $blocked['blocked'];
1594 * Checks if the contact is hidden
1596 * @param int $cid contact id
1598 * @return boolean Is the contact hidden?
1599 * @throws \Exception
1601 public static function isHidden($cid)
1607 $hidden = DBA::selectFirst('contact', ['hidden'], ['id' => $cid]);
1608 if (!DBA::isResult($hidden)) {
1611 return (bool) $hidden['hidden'];
1615 * Returns posts from a given contact url
1617 * @param string $contact_url Contact URL
1618 * @param bool $thread_mode
1619 * @param int $update
1620 * @return string posts in HTML
1621 * @throws \Exception
1623 public static function getPostsFromUrl($contact_url, $thread_mode = false, $update = 0)
1625 return self::getPostsFromId(self::getIdForURL($contact_url), $thread_mode, $update);
1629 * Returns posts from a given contact id
1631 * @param integer $cid
1632 * @param bool $thread_mode
1633 * @param integer $update
1634 * @return string posts in HTML
1635 * @throws \Exception
1637 public static function getPostsFromId($cid, $thread_mode = false, $update = 0)
1641 $contact = DBA::selectFirst('contact', ['contact-type', 'network'], ['id' => $cid]);
1642 if (!DBA::isResult($contact)) {
1646 if (empty($contact["network"]) || in_array($contact["network"], Protocol::FEDERATED)) {
1647 $sql = "(`item`.`uid` = 0 OR (`item`.`uid` = ? AND NOT `item`.`global`))";
1649 $sql = "`item`.`uid` = ?";
1652 $contact_field = ((($contact["contact-type"] == self::TYPE_COMMUNITY) || ($contact['network'] == Protocol::MAIL)) ? 'owner-id' : 'author-id');
1655 $condition = ["`$contact_field` = ? AND `gravity` = ? AND " . $sql,
1656 $cid, GRAVITY_PARENT, local_user()];
1658 $condition = ["`$contact_field` = ? AND `gravity` IN (?, ?) AND " . $sql,
1659 $cid, GRAVITY_PARENT, GRAVITY_COMMENT, local_user()];
1662 if (DI::mode()->isMobile()) {
1663 $itemsPerPage = DI::pConfig()->get(local_user(), 'system', 'itemspage_mobile_network',
1664 DI::config()->get('system', 'itemspage_network_mobile'));
1666 $itemsPerPage = DI::pConfig()->get(local_user(), 'system', 'itemspage_network',
1667 DI::config()->get('system', 'itemspage_network'));
1670 $pager = new Pager(DI::l10n(), DI::args()->getQueryString(), $itemsPerPage);
1672 $params = ['order' => ['received' => true],
1673 'limit' => [$pager->getStart(), $pager->getItemsPerPage()]];
1676 $r = Item::selectThreadForUser(local_user(), ['uri'], $condition, $params);
1678 $items = Item::inArray($r);
1680 $o = conversation($a, $items, 'contacts', $update, false, 'commented', local_user());
1682 $r = Item::selectForUser(local_user(), [], $condition, $params);
1684 $items = Item::inArray($r);
1686 $o = conversation($a, $items, 'contact-posts', false);
1690 $o .= $pager->renderMinimal(count($items));
1697 * Returns the account type name
1699 * The function can be called with either the user or the contact array
1701 * @param array $contact contact or user array
1704 public static function getAccountType(array $contact)
1706 // There are several fields that indicate that the contact or user is a forum
1707 // "page-flags" is a field in the user table,
1708 // "forum" and "prv" are used in the contact table. They stand for User::PAGE_FLAGS_COMMUNITY and User::PAGE_FLAGS_PRVGROUP.
1709 // "community" is used in the gcontact table and is true if the contact is User::PAGE_FLAGS_COMMUNITY or User::PAGE_FLAGS_PRVGROUP.
1710 if ((isset($contact['page-flags']) && (intval($contact['page-flags']) == User::PAGE_FLAGS_COMMUNITY))
1711 || (isset($contact['page-flags']) && (intval($contact['page-flags']) == User::PAGE_FLAGS_PRVGROUP))
1712 || (isset($contact['forum']) && intval($contact['forum']))
1713 || (isset($contact['prv']) && intval($contact['prv']))
1714 || (isset($contact['community']) && intval($contact['community']))
1716 $type = self::TYPE_COMMUNITY;
1718 $type = self::TYPE_PERSON;
1721 // The "contact-type" (contact table) and "account-type" (user table) are more general then the chaos from above.
1722 if (isset($contact["contact-type"])) {
1723 $type = $contact["contact-type"];
1726 if (isset($contact["account-type"])) {
1727 $type = $contact["account-type"];
1731 case self::TYPE_ORGANISATION:
1732 $account_type = DI::l10n()->t("Organisation");
1735 case self::TYPE_NEWS:
1736 $account_type = DI::l10n()->t('News');
1739 case self::TYPE_COMMUNITY:
1740 $account_type = DI::l10n()->t("Forum");
1748 return $account_type;
1756 * @throws \Exception
1758 public static function block($cid, $reason = null)
1760 $return = DBA::update('contact', ['blocked' => true, 'block_reason' => $reason], ['id' => $cid]);
1766 * Unblocks a contact
1770 * @throws \Exception
1772 public static function unblock($cid)
1774 $return = DBA::update('contact', ['blocked' => false, 'block_reason' => null], ['id' => $cid]);
1780 * Ensure that cached avatar exist
1782 * @param integer $cid
1784 public static function checkAvatarCache(int $cid)
1786 $contact = DBA::selectFirst('contact', ['url', 'avatar', 'photo', 'thumb', 'micro'], ['id' => $cid, 'uid' => 0, 'self' => false]);
1787 if (!DBA::isResult($contact)) {
1791 if (empty($contact['avatar']) || (!empty($contact['photo']) && !empty($contact['thumb']) && !empty($contact['micro']))) {
1795 Logger::info('Adding avatar cache', ['id' => $cid, 'contact' => $contact]);
1797 self::updateAvatar($cid, $contact['avatar'], true);
1801 * Return the photo path for a given contact array in the given size
1803 * @param array $contact contact array
1804 * @param string $field Fieldname of the photo in the contact array
1805 * @param string $default Default path when no picture had been found
1806 * @param string $size Size of the avatar picture
1807 * @param string $avatar Avatar path that is displayed when no photo had been found
1808 * @return string photo path
1810 private static function getAvatarPath(array $contact, string $field, string $default, string $size, string $avatar)
1812 if (!empty($contact)) {
1813 $contact = self::checkAvatarCacheByArray($contact);
1814 if (!empty($contact[$field])) {
1815 $avatar = $contact[$field];
1819 if (empty($avatar)) {
1823 if (Proxy::isLocalImage($avatar)) {
1826 return Proxy::proxifyUrl($avatar, false, $size);
1831 * Return the photo path for a given contact array
1833 * @param array $contact Contact array
1834 * @param string $avatar Avatar path that is displayed when no photo had been found
1835 * @return string photo path
1837 public static function getPhoto(array $contact, string $avatar = '')
1839 return self::getAvatarPath($contact, 'photo', DI::baseUrl() . '/images/person-300.jpg', Proxy::SIZE_SMALL, $avatar);
1843 * Return the photo path (thumb size) for a given contact array
1845 * @param array $contact Contact array
1846 * @param string $avatar Avatar path that is displayed when no photo had been found
1847 * @return string photo path
1849 public static function getThumb(array $contact, string $avatar = '')
1851 return self::getAvatarPath($contact, 'thumb', DI::baseUrl() . '/images/person-80.jpg', Proxy::SIZE_THUMB, $avatar);
1855 * Return the photo path (micro size) for a given contact array
1857 * @param array $contact Contact array
1858 * @param string $avatar Avatar path that is displayed when no photo had been found
1859 * @return string photo path
1861 public static function getMicro(array $contact, string $avatar = '')
1863 return self::getAvatarPath($contact, 'micro', DI::baseUrl() . '/images/person-48.jpg', Proxy::SIZE_MICRO, $avatar);
1867 * Check the given contact array for avatar cache fields
1869 * @param array $contact
1870 * @return array contact array with avatar cache fields
1872 private static function checkAvatarCacheByArray(array $contact)
1875 $contact_fields = [];
1876 $fields = ['photo', 'thumb', 'micro'];
1877 foreach ($fields as $field) {
1878 if (isset($contact[$field])) {
1879 $contact_fields[] = $field;
1881 if (isset($contact[$field]) && empty($contact[$field])) {
1890 if (!empty($contact['id']) && !empty($contact['avatar'])) {
1891 self::updateAvatar($contact['id'], $contact['avatar'], true);
1893 $new_contact = self::getById($contact['id'], $contact_fields);
1894 if (DBA::isResult($new_contact)) {
1895 // We only update the cache fields
1896 $contact = array_merge($contact, $new_contact);
1900 /// add the default avatars if the fields aren't filled
1901 if (isset($contact['photo']) && empty($contact['photo'])) {
1902 $contact['photo'] = DI::baseUrl() . '/images/person-300.jpg';
1904 if (isset($contact['thumb']) && empty($contact['thumb'])) {
1905 $contact['thumb'] = DI::baseUrl() . '/images/person-80.jpg';
1907 if (isset($contact['micro']) && empty($contact['micro'])) {
1908 $contact['micro'] = DI::baseUrl() . '/images/person-48.jpg';
1915 * Updates the avatar links in a contact only if needed
1917 * @param int $cid Contact id
1918 * @param string $avatar Link to avatar picture
1919 * @param bool $force force picture update
1922 * @throws HTTPException\InternalServerErrorException
1923 * @throws HTTPException\NotFoundException
1924 * @throws \ImagickException
1926 public static function updateAvatar(int $cid, string $avatar, bool $force = false)
1928 $contact = DBA::selectFirst('contact', ['uid', 'avatar', 'photo', 'thumb', 'micro', 'nurl'], ['id' => $cid, 'self' => false]);
1929 if (!DBA::isResult($contact)) {
1933 $uid = $contact['uid'];
1935 // Only update the cached photo links of public contacts when they already are cached
1936 if (($uid == 0) && !$force && empty($contact['thumb']) && empty($contact['micro'])) {
1937 if ($contact['avatar'] != $avatar) {
1938 DBA::update('contact', ['avatar' => $avatar], ['id' => $cid]);
1939 Logger::info('Only update the avatar', ['id' => $cid, 'avatar' => $avatar, 'contact' => $contact]);
1945 $contact['photo'] ?? '',
1946 $contact['thumb'] ?? '',
1947 $contact['micro'] ?? '',
1950 $update = ($contact['avatar'] != $avatar) || $force;
1953 foreach ($data as $image_uri) {
1954 $image_rid = Photo::ridFromURI($image_uri);
1955 if ($image_rid && !Photo::exists(['resource-id' => $image_rid, 'uid' => $uid])) {
1956 Logger::info('Regenerating avatar', ['contact uid' => $uid, 'cid' => $cid, 'missing photo' => $image_rid, 'avatar' => $contact['avatar']]);
1963 $photos = Photo::importProfilePhoto($avatar, $uid, $cid, true);
1965 $fields = ['avatar' => $avatar, 'photo' => $photos[0], 'thumb' => $photos[1], 'micro' => $photos[2], 'avatar-date' => DateTimeFormat::utcNow()];
1966 DBA::update('contact', $fields, ['id' => $cid]);
1967 } elseif (empty($contact['avatar'])) {
1968 // Ensure that the avatar field is set
1969 DBA::update('contact', ['avatar' => $avatar], ['id' => $cid]);
1970 Logger::info('Failed profile import', ['id' => $cid, 'force' => $force, 'avatar' => $avatar, 'contact' => $contact]);
1976 * Helper function for "updateFromProbe". Updates personal and public contact
1978 * @param integer $id contact id
1979 * @param integer $uid user id
1980 * @param string $url The profile URL of the contact
1981 * @param array $fields The fields that are updated
1983 * @throws \Exception
1985 private static function updateContact($id, $uid, $url, array $fields)
1987 if (!DBA::update('contact', $fields, ['id' => $id])) {
1988 Logger::info('Couldn\'t update contact.', ['id' => $id, 'fields' => $fields]);
1992 // Search for duplicated contacts and get rid of them
1993 if (self::removeDuplicates(Strings::normaliseLink($url), $uid) || ($uid != 0)) {
1997 // Update the corresponding gcontact entry
1998 GContact::updateFromPublicContactID($id);
2000 // Archive or unarchive the contact. We only need to do this for the public contact.
2001 // The archive/unarchive function will update the personal contacts by themselves.
2002 $contact = DBA::selectFirst('contact', [], ['id' => $id]);
2003 if (!DBA::isResult($contact)) {
2004 Logger::info('Couldn\'t select contact for archival.', ['id' => $id]);
2008 if (!empty($fields['success_update'])) {
2009 self::unmarkForArchival($contact);
2010 } elseif (!empty($fields['failure_update'])) {
2011 self::markForArchival($contact);
2014 $condition = ['self' => false, 'nurl' => Strings::normaliseLink($url), 'network' => Protocol::FEDERATED];
2016 // These contacts are sharing with us, we don't poll them.
2017 // This means that we don't set the update fields in "OnePoll.php".
2018 $condition['rel'] = self::SHARING;
2019 DBA::update('contact', $fields, $condition);
2021 unset($fields['last-update']);
2022 unset($fields['success_update']);
2023 unset($fields['failure_update']);
2025 if (empty($fields)) {
2029 // We are polling these contacts, so we mustn't set the update fields here.
2030 $condition['rel'] = [self::FOLLOWER, self::FRIEND];
2031 DBA::update('contact', $fields, $condition);
2035 * Remove duplicated contacts
2037 * @param string $nurl Normalised contact url
2038 * @param integer $uid User id
2040 * @throws \Exception
2042 public static function removeDuplicates(string $nurl, int $uid)
2044 $condition = ['nurl' => $nurl, 'uid' => $uid, 'deleted' => false, 'network' => Protocol::FEDERATED];
2045 $count = DBA::count('contact', $condition);
2050 $first_contact = DBA::selectFirst('contact', ['id', 'network'], $condition, ['order' => ['id']]);
2051 if (!DBA::isResult($first_contact)) {
2052 // Shouldn't happen - so we handle it
2056 $first = $first_contact['id'];
2057 Logger::info('Found duplicates', ['count' => $count, 'first' => $first, 'uid' => $uid, 'nurl' => $nurl]);
2058 if (($uid != 0 && ($first_contact['network'] == Protocol::DFRN))) {
2059 // Don't handle non public DFRN duplicates by now (legacy DFRN is very special because of the key handling)
2060 Logger::info('Not handling non public DFRN duplicate', ['uid' => $uid, 'nurl' => $nurl]);
2064 // Find all duplicates
2065 $condition = ["`nurl` = ? AND `uid` = ? AND `id` != ? AND NOT `self` AND NOT `deleted`", $nurl, $uid, $first];
2066 $duplicates = DBA::select('contact', ['id', 'network'], $condition);
2067 while ($duplicate = DBA::fetch($duplicates)) {
2068 if (!in_array($duplicate['network'], Protocol::FEDERATED)) {
2072 Worker::add(PRIORITY_HIGH, 'MergeContact', $first, $duplicate['id'], $uid);
2074 DBA::close($duplicates);
2075 Logger::info('Duplicates handled', ['uid' => $uid, 'nurl' => $nurl]);
2080 * @param integer $id contact id
2081 * @param string $network Optional network we are probing for
2082 * @param boolean $force Optional forcing of network probing (otherwise we use the cached data)
2084 * @throws HTTPException\InternalServerErrorException
2085 * @throws \ImagickException
2087 public static function updateFromProbe(int $id, string $network = '', bool $force = false)
2090 Warning: Never ever fetch the public key via Probe::uri and write it into the contacts.
2091 This will reliably kill your communication with old Friendica contacts.
2094 // These fields aren't updated by this routine:
2095 // 'xmpp', 'sensitive'
2097 $fields = ['uid', 'avatar', 'name', 'nick', 'location', 'keywords', 'about', 'subscribe',
2098 'unsearchable', 'url', 'addr', 'batch', 'notify', 'poll', 'request', 'confirm', 'poco',
2099 'network', 'alias', 'baseurl', 'gsid', 'forum', 'prv', 'contact-type', 'pubkey'];
2100 $contact = DBA::selectFirst('contact', $fields, ['id' => $id]);
2101 if (!DBA::isResult($contact)) {
2105 $uid = $contact['uid'];
2106 unset($contact['uid']);
2108 $pubkey = $contact['pubkey'];
2109 unset($contact['pubkey']);
2111 $contact['photo'] = $contact['avatar'];
2112 unset($contact['avatar']);
2114 $ret = Probe::uri($contact['url'], $network, $uid, !$force);
2116 $updated = DateTimeFormat::utcNow();
2118 // We must not try to update relay contacts via probe. They are no real contacts.
2119 // We check after the probing to be able to correct falsely detected contact types.
2120 if (($contact['contact-type'] == self::TYPE_RELAY) &&
2121 (!Strings::compareLink($ret['url'], $contact['url']) || in_array($ret['network'], [Protocol::FEED, Protocol::PHANTOM]))) {
2122 self::updateContact($id, $uid, $contact['url'], ['failed' => false, 'last-update' => $updated, 'success_update' => $updated]);
2123 Logger::info('Not updating relais', ['id' => $id, 'url' => $contact['url']]);
2127 // If Probe::uri fails the network code will be different ("feed" or "unkn")
2128 if (in_array($ret['network'], [Protocol::FEED, Protocol::PHANTOM]) && ($ret['network'] != $contact['network'])) {
2129 if ($force && ($uid == 0)) {
2130 self::updateContact($id, $uid, $ret['url'], ['failed' => true, 'last-update' => $updated, 'failure_update' => $updated]);
2135 if (ContactRelation::isDiscoverable($ret['url'])) {
2136 Worker::add(PRIORITY_LOW, 'ContactDiscovery', $ret['url']);
2139 if (isset($ret['hide']) && is_bool($ret['hide'])) {
2140 $ret['unsearchable'] = $ret['hide'];
2143 if (isset($ret['account-type']) && is_int($ret['account-type'])) {
2144 $ret['forum'] = false;
2145 $ret['prv'] = false;
2146 $ret['contact-type'] = $ret['account-type'];
2147 if ($ret['contact-type'] == User::ACCOUNT_TYPE_COMMUNITY) {
2148 $apcontact = APContact::getByURL($ret['url'], false);
2149 if (isset($apcontact['manually-approve'])) {
2150 $ret['forum'] = (bool)!$apcontact['manually-approve'];
2151 $ret['prv'] = (bool)!$ret['forum'];
2156 $new_pubkey = $ret['pubkey'];
2158 // Update the gcontact entry
2160 GContact::updateFromPublicContactID($id);
2165 // make sure to not overwrite existing values with blank entries except some technical fields
2166 $keep = ['batch', 'notify', 'poll', 'request', 'confirm', 'poco', 'baseurl'];
2167 foreach ($ret as $key => $val) {
2168 if (!array_key_exists($key, $contact)) {
2170 } elseif (($contact[$key] != '') && ($val === '') && !is_bool($ret[$key]) && !in_array($key, $keep)) {
2171 $ret[$key] = $contact[$key];
2172 } elseif ($ret[$key] != $contact[$key]) {
2177 if (!empty($ret['photo']) && ($ret['network'] != Protocol::FEED)) {
2178 self::updateAvatar($id, $ret['photo'], $update || $force);
2183 self::updateContact($id, $uid, $ret['url'], ['failed' => false, 'last-update' => $updated, 'success_update' => $updated]);
2186 // Update the public contact
2188 self::updateFromProbeByURL($ret['url']);
2194 $ret['nurl'] = Strings::normaliseLink($ret['url']);
2195 $ret['updated'] = $updated;
2197 // Only fill the pubkey if it had been empty before. We have to prevent identity theft.
2198 if (empty($pubkey) && !empty($new_pubkey)) {
2199 $ret['pubkey'] = $new_pubkey;
2202 if (($ret['addr'] != $contact['addr']) || (!empty($ret['alias']) && ($ret['alias'] != $contact['alias']))) {
2203 $ret['uri-date'] = DateTimeFormat::utcNow();
2206 if (($ret['name'] != $contact['name']) || ($ret['nick'] != $contact['nick'])) {
2207 $ret['name-date'] = $updated;
2210 if ($force && ($uid == 0)) {
2211 $ret['last-update'] = $updated;
2212 $ret['success_update'] = $updated;
2213 $ret['failed'] = false;
2216 unset($ret['photo']);
2218 self::updateContact($id, $uid, $ret['url'], $ret);
2223 public static function updateFromProbeByURL($url, $force = false)
2225 $id = self::getIdForURL($url);
2231 self::updateFromProbe($id, '', $force);
2237 * Detects if a given contact array belongs to a legacy DFRN connection
2239 * @param array $contact
2242 public static function isLegacyDFRNContact($contact)
2244 // Newer Friendica contacts are connected via AP, then these fields aren't set
2245 return !empty($contact['dfrn-id']) || !empty($contact['issued-id']);
2249 * Detects the communication protocol for a given contact url.
2250 * This is used to detect Friendica contacts that we can communicate via AP.
2252 * @param string $url contact url
2253 * @param string $network Network of that contact
2254 * @return string with protocol
2256 public static function getProtocol($url, $network)
2258 if ($network != Protocol::DFRN) {
2262 $apcontact = APContact::getByURL($url);
2263 if (!empty($apcontact) && !empty($apcontact['generator'])) {
2264 return Protocol::ACTIVITYPUB;
2271 * Takes a $uid and a url/handle and adds a new contact
2273 * Currently if the contact is DFRN, interactive needs to be true, to redirect to the
2274 * dfrn_request page.
2276 * Otherwise this can be used to bulk add StatusNet contacts, Twitter contacts, etc.
2279 * $return['success'] boolean true if successful
2280 * $return['message'] error text if success is false.
2282 * Takes a $uid and a url/handle and adds a new contact
2284 * @param array $user The user the contact should be created for
2285 * @param string $url The profile URL of the contact
2286 * @param bool $interactive
2287 * @param string $network
2289 * @throws HTTPException\InternalServerErrorException
2290 * @throws HTTPException\NotFoundException
2291 * @throws \ImagickException
2293 public static function createFromProbe(array $user, $url, $interactive = false, $network = '')
2295 $result = ['cid' => -1, 'success' => false, 'message' => ''];
2297 // remove ajax junk, e.g. Twitter
2298 $url = str_replace('/#!/', '/', $url);
2300 if (!Network::isUrlAllowed($url)) {
2301 $result['message'] = DI::l10n()->t('Disallowed profile URL.');
2305 if (Network::isUrlBlocked($url)) {
2306 $result['message'] = DI::l10n()->t('Blocked domain');
2311 $result['message'] = DI::l10n()->t('Connect URL missing.');
2315 $arr = ['url' => $url, 'contact' => []];
2317 Hook::callAll('follow', $arr);
2320 $result['message'] = DI::l10n()->t('The contact could not be added. Please check the relevant network credentials in your Settings -> Social Networks page.');
2324 if (!empty($arr['contact']['name'])) {
2325 $ret = $arr['contact'];
2327 $ret = Probe::uri($url, $network, $user['uid'], false);
2330 if (($network != '') && ($ret['network'] != $network)) {
2331 Logger::log('Expected network ' . $network . ' does not match actual network ' . $ret['network']);
2335 // check if we already have a contact
2336 // the poll url is more reliable than the profile url, as we may have
2337 // indirect links or webfinger links
2339 $condition = ['uid' => $user['uid'], 'poll' => [$ret['poll'], Strings::normaliseLink($ret['poll'])], 'network' => $ret['network'], 'pending' => false];
2340 $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
2341 if (!DBA::isResult($contact)) {
2342 $condition = ['uid' => $user['uid'], 'nurl' => Strings::normaliseLink($ret['url']), 'network' => $ret['network'], 'pending' => false];
2343 $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
2346 $protocol = self::getProtocol($ret['url'], $ret['network']);
2348 if (($protocol === Protocol::DFRN) && !DBA::isResult($contact)) {
2350 if (strlen(DI::baseUrl()->getUrlPath())) {
2351 $myaddr = bin2hex(DI::baseUrl() . '/profile/' . $user['nickname']);
2353 $myaddr = bin2hex($user['nickname'] . '@' . DI::baseUrl()->getHostname());
2356 DI::baseUrl()->redirect($ret['request'] . "&addr=$myaddr");
2360 } elseif (DI::config()->get('system', 'dfrn_only') && ($ret['network'] != Protocol::DFRN)) {
2361 $result['message'] = DI::l10n()->t('This site is not configured to allow communications with other networks.') . EOL;
2362 $result['message'] .= DI::l10n()->t('No compatible communication protocols or feeds were discovered.') . EOL;
2366 // This extra param just confuses things, remove it
2367 if ($protocol === Protocol::DIASPORA) {
2368 $ret['url'] = str_replace('?absolute=true', '', $ret['url']);
2371 // do we have enough information?
2372 if (empty($ret['name']) || empty($ret['poll']) || (empty($ret['url']) && empty($ret['addr']))) {
2373 $result['message'] .= DI::l10n()->t('The profile address specified does not provide adequate information.') . EOL;
2374 if (empty($ret['poll'])) {
2375 $result['message'] .= DI::l10n()->t('No compatible communication protocols or feeds were discovered.') . EOL;
2377 if (empty($ret['name'])) {
2378 $result['message'] .= DI::l10n()->t('An author or name was not found.') . EOL;
2380 if (empty($ret['url'])) {
2381 $result['message'] .= DI::l10n()->t('No browser URL could be matched to this address.') . EOL;
2383 if (strpos($ret['url'], '@') !== false) {
2384 $result['message'] .= DI::l10n()->t('Unable to match @-style Identity Address with a known protocol or email contact.') . EOL;
2385 $result['message'] .= DI::l10n()->t('Use mailto: in front of address to force email check.') . EOL;
2390 if ($protocol === Protocol::OSTATUS && DI::config()->get('system', 'ostatus_disabled')) {
2391 $result['message'] .= DI::l10n()->t('The profile address specified belongs to a network which has been disabled on this site.') . EOL;
2392 $ret['notify'] = '';
2395 if (!$ret['notify']) {
2396 $result['message'] .= DI::l10n()->t('Limited profile. This person will be unable to receive direct/personal notifications from you.') . EOL;
2399 $writeable = ((($protocol === Protocol::OSTATUS) && ($ret['notify'])) ? 1 : 0);
2401 $subhub = (($protocol === Protocol::OSTATUS) ? true : false);
2403 $hidden = (($protocol === Protocol::MAIL) ? 1 : 0);
2406 if ($protocol == Protocol::ACTIVITYPUB) {
2407 $apcontact = APContact::getByURL($ret['url'], false);
2408 if (isset($apcontact['manually-approve'])) {
2409 $pending = (bool)$apcontact['manually-approve'];
2413 if (in_array($protocol, [Protocol::MAIL, Protocol::DIASPORA, Protocol::ACTIVITYPUB])) {
2417 if (DBA::isResult($contact)) {
2419 $new_relation = (($contact['rel'] == self::FOLLOWER) ? self::FRIEND : self::SHARING);
2421 $fields = ['rel' => $new_relation, 'subhub' => $subhub, 'readonly' => false];
2422 DBA::update('contact', $fields, ['id' => $contact['id']]);
2424 $new_relation = (in_array($protocol, [Protocol::MAIL]) ? self::FRIEND : self::SHARING);
2426 // create contact record
2428 'uid' => $user['uid'],
2429 'created' => DateTimeFormat::utcNow(),
2430 'url' => $ret['url'],
2431 'nurl' => Strings::normaliseLink($ret['url']),
2432 'addr' => $ret['addr'],
2433 'alias' => $ret['alias'],
2434 'batch' => $ret['batch'],
2435 'notify' => $ret['notify'],
2436 'poll' => $ret['poll'],
2437 'poco' => $ret['poco'],
2438 'name' => $ret['name'],
2439 'nick' => $ret['nick'],
2440 'network' => $ret['network'],
2441 'baseurl' => $ret['baseurl'],
2442 'gsid' => $ret['gsid'] ?? null,
2443 'protocol' => $protocol,
2444 'pubkey' => $ret['pubkey'],
2445 'rel' => $new_relation,
2446 'priority'=> $ret['priority'],
2447 'writable'=> $writeable,
2448 'hidden' => $hidden,
2451 'pending' => $pending,
2456 $contact = DBA::selectFirst('contact', [], ['url' => $ret['url'], 'network' => $ret['network'], 'uid' => $user['uid']]);
2457 if (!DBA::isResult($contact)) {
2458 $result['message'] .= DI::l10n()->t('Unable to retrieve contact information.') . EOL;
2462 $contact_id = $contact['id'];
2463 $result['cid'] = $contact_id;
2465 Group::addMember(User::getDefaultGroup($user['uid'], $contact["network"]), $contact_id);
2467 // Update the avatar
2468 self::updateAvatar($contact_id, $ret['photo']);
2470 // pull feed and consume it, which should subscribe to the hub.
2472 Worker::add(PRIORITY_HIGH, "OnePoll", $contact_id, "force");
2474 $owner = User::getOwnerDataById($user['uid']);
2476 if (DBA::isResult($owner)) {
2477 if (in_array($protocol, [Protocol::OSTATUS, Protocol::DFRN])) {
2478 // create a follow slap
2480 $item['verb'] = Activity::FOLLOW;
2481 $item['gravity'] = GRAVITY_ACTIVITY;
2482 $item['follow'] = $contact["url"];
2484 $item['title'] = '';
2486 $item['uri-id'] = 0;
2487 $item['attach'] = '';
2489 $slap = OStatus::salmon($item, $owner);
2491 if (!empty($contact['notify'])) {
2492 Salmon::slapper($owner, $contact['notify'], $slap);
2494 } elseif ($protocol == Protocol::DIASPORA) {
2495 $ret = Diaspora::sendShare($owner, $contact);
2496 Logger::log('share returns: ' . $ret);
2497 } elseif ($protocol == Protocol::ACTIVITYPUB) {
2498 $activity_id = ActivityPub\Transmitter::activityIDFromContact($contact_id);
2499 if (empty($activity_id)) {
2500 // This really should never happen
2504 $ret = ActivityPub\Transmitter::sendActivity('Follow', $contact['url'], $user['uid'], $activity_id);
2505 Logger::log('Follow returns: ' . $ret);
2509 $result['success'] = true;
2514 * Updated contact's SSL policy
2516 * @param array $contact Contact array
2517 * @param string $new_policy New policy, valid: self,full
2519 * @return array Contact array with updated values
2520 * @throws \Exception
2522 public static function updateSslPolicy(array $contact, $new_policy)
2524 $ssl_changed = false;
2525 if ((intval($new_policy) == BaseURL::SSL_POLICY_SELFSIGN || $new_policy === 'self') && strstr($contact['url'], 'https:')) {
2526 $ssl_changed = true;
2527 $contact['url'] = str_replace('https:', 'http:', $contact['url']);
2528 $contact['request'] = str_replace('https:', 'http:', $contact['request']);
2529 $contact['notify'] = str_replace('https:', 'http:', $contact['notify']);
2530 $contact['poll'] = str_replace('https:', 'http:', $contact['poll']);
2531 $contact['confirm'] = str_replace('https:', 'http:', $contact['confirm']);
2532 $contact['poco'] = str_replace('https:', 'http:', $contact['poco']);
2535 if ((intval($new_policy) == BaseURL::SSL_POLICY_FULL || $new_policy === 'full') && strstr($contact['url'], 'http:')) {
2536 $ssl_changed = true;
2537 $contact['url'] = str_replace('http:', 'https:', $contact['url']);
2538 $contact['request'] = str_replace('http:', 'https:', $contact['request']);
2539 $contact['notify'] = str_replace('http:', 'https:', $contact['notify']);
2540 $contact['poll'] = str_replace('http:', 'https:', $contact['poll']);
2541 $contact['confirm'] = str_replace('http:', 'https:', $contact['confirm']);
2542 $contact['poco'] = str_replace('http:', 'https:', $contact['poco']);
2546 $fields = ['url' => $contact['url'], 'request' => $contact['request'],
2547 'notify' => $contact['notify'], 'poll' => $contact['poll'],
2548 'confirm' => $contact['confirm'], 'poco' => $contact['poco']];
2549 DBA::update('contact', $fields, ['id' => $contact['id']]);
2556 * @param array $importer Owner (local user) data
2557 * @param array $contact Existing owner-specific contact data we want to expand the relationship with. Optional.
2558 * @param array $datarray An item-like array with at least the 'author-id' and 'author-url' keys for the contact. Mandatory.
2559 * @param bool $sharing True: Contact is now sharing with Owner; False: Contact is now following Owner (default)
2560 * @param string $note Introduction additional message
2561 * @return bool|null True: follow request is accepted; False: relationship is rejected; Null: relationship is pending
2562 * @throws HTTPException\InternalServerErrorException
2563 * @throws \ImagickException
2565 public static function addRelationship(array $importer, array $contact, array $datarray, $sharing = false, $note = '')
2567 // Should always be set
2568 if (empty($datarray['author-id'])) {
2572 $fields = ['url', 'name', 'nick', 'avatar', 'photo', 'network', 'blocked'];
2573 $pub_contact = DBA::selectFirst('contact', $fields, ['id' => $datarray['author-id']]);
2574 if (!DBA::isResult($pub_contact)) {
2575 // Should never happen
2579 // Contact is blocked at node-level
2580 if (self::isBlocked($datarray['author-id'])) {
2584 $url = ($datarray['author-link'] ?? '') ?: $pub_contact['url'];
2585 $name = $pub_contact['name'];
2586 $photo = ($pub_contact['avatar'] ?? '') ?: $pub_contact["photo"];
2587 $nick = $pub_contact['nick'];
2588 $network = $pub_contact['network'];
2590 // Ensure that we don't create a new contact when there already is one
2591 $cid = self::getIdForURL($url, $importer['uid']);
2593 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
2596 if (!empty($contact)) {
2597 if (!empty($contact['pending'])) {
2598 Logger::info('Pending contact request already exists.', ['url' => $url, 'uid' => $importer['uid']]);
2602 // Contact is blocked at user-level
2603 if (!empty($contact['id']) && !empty($importer['id']) &&
2604 self::isBlockedByUser($contact['id'], $importer['id'])) {
2608 // Make sure that the existing contact isn't archived
2609 self::unmarkForArchival($contact);
2611 if (($contact['rel'] == self::SHARING)
2612 || ($sharing && $contact['rel'] == self::FOLLOWER)) {
2613 DBA::update('contact', ['rel' => self::FRIEND, 'writable' => true, 'pending' => false],
2614 ['id' => $contact['id'], 'uid' => $importer['uid']]);
2617 // Ensure to always have the correct network type, independent from the connection request method
2618 self::updateFromProbe($contact['id'], '', true);
2622 // send email notification to owner?
2623 if (DBA::exists('contact', ['nurl' => Strings::normaliseLink($url), 'uid' => $importer['uid'], 'pending' => true])) {
2624 Logger::log('ignoring duplicated connection request from pending contact ' . $url);
2628 // create contact record
2629 DBA::insert('contact', [
2630 'uid' => $importer['uid'],
2631 'created' => DateTimeFormat::utcNow(),
2633 'nurl' => Strings::normaliseLink($url),
2636 'network' => $network,
2637 'rel' => self::FOLLOWER,
2644 $contact_id = DBA::lastInsertId();
2646 // Ensure to always have the correct network type, independent from the connection request method
2647 self::updateFromProbe($contact_id, '', true);
2649 self::updateAvatar($contact_id, $photo, true);
2651 $contact_record = DBA::selectFirst('contact', ['id', 'network', 'name', 'url', 'photo'], ['id' => $contact_id]);
2653 /// @TODO Encapsulate this into a function/method
2654 $fields = ['uid', 'username', 'email', 'page-flags', 'notify-flags', 'language'];
2655 $user = DBA::selectFirst('user', $fields, ['uid' => $importer['uid']]);
2656 if (DBA::isResult($user) && !in_array($user['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_FREELOVE, User::PAGE_FLAGS_COMMUNITY])) {
2657 // create notification
2658 $hash = Strings::getRandomHex();
2660 if (is_array($contact_record)) {
2661 DBA::insert('intro', ['uid' => $importer['uid'], 'contact-id' => $contact_record['id'],
2662 'blocked' => false, 'knowyou' => false, 'note' => $note,
2663 'hash' => $hash, 'datetime' => DateTimeFormat::utcNow()]);
2666 Group::addMember(User::getDefaultGroup($importer['uid'], $contact_record["network"]), $contact_record['id']);
2668 if (($user['notify-flags'] & Type::INTRO) &&
2669 in_array($user['page-flags'], [User::PAGE_FLAGS_NORMAL])) {
2672 'type' => Type::INTRO,
2673 'notify_flags' => $user['notify-flags'],
2674 'language' => $user['language'],
2675 'to_name' => $user['username'],
2676 'to_email' => $user['email'],
2677 'uid' => $user['uid'],
2678 'link' => DI::baseUrl() . '/notifications/intros',
2679 'source_name' => ((strlen(stripslashes($contact_record['name']))) ? stripslashes($contact_record['name']) : DI::l10n()->t('[Name Withheld]')),
2680 'source_link' => $contact_record['url'],
2681 'source_photo' => $contact_record['photo'],
2682 'verb' => ($sharing ? Activity::FRIEND : Activity::FOLLOW),
2686 } elseif (DBA::isResult($user) && in_array($user['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_FREELOVE, User::PAGE_FLAGS_COMMUNITY])) {
2687 if (($user['page-flags'] == User::PAGE_FLAGS_FREELOVE) && ($network != Protocol::DIASPORA)) {
2688 self::createFromProbe($importer, $url, false, $network);
2691 $condition = ['uid' => $importer['uid'], 'url' => $url, 'pending' => true];
2692 $fields = ['pending' => false];
2693 if ($user['page-flags'] == User::PAGE_FLAGS_FREELOVE) {
2694 $fields['rel'] = Contact::FRIEND;
2697 DBA::update('contact', $fields, $condition);
2706 public static function removeFollower($importer, $contact, array $datarray = [], $item = "")
2708 if (($contact['rel'] == self::FRIEND) || ($contact['rel'] == self::SHARING)) {
2709 DBA::update('contact', ['rel' => self::SHARING], ['id' => $contact['id']]);
2711 Contact::remove($contact['id']);
2715 public static function removeSharer($importer, $contact, array $datarray = [], $item = "")
2717 if (($contact['rel'] == self::FRIEND) || ($contact['rel'] == self::FOLLOWER)) {
2718 DBA::update('contact', ['rel' => self::FOLLOWER], ['id' => $contact['id']]);
2720 Contact::remove($contact['id']);
2725 * Create a birthday event.
2727 * Update the year and the birthday.
2729 public static function updateBirthdays()
2733 AND `bd` > "0001-01-01"
2734 AND SUBSTRING(`bd`, 1, 4) != `bdyear`
2735 AND (`contact`.`rel` = ? OR `contact`.`rel` = ?)
2736 AND NOT `contact`.`pending`
2737 AND NOT `contact`.`hidden`
2738 AND NOT `contact`.`blocked`
2739 AND NOT `contact`.`archive`
2740 AND NOT `contact`.`deleted`',
2745 $contacts = DBA::select('contact', ['id', 'uid', 'name', 'url', 'bd'], $condition);
2747 while ($contact = DBA::fetch($contacts)) {
2748 Logger::log('update_contact_birthday: ' . $contact['bd']);
2750 $nextbd = DateTimeFormat::utcNow('Y') . substr($contact['bd'], 4);
2752 if (Event::createBirthday($contact, $nextbd)) {
2756 ['bdyear' => substr($nextbd, 0, 4), 'bd' => $nextbd],
2757 ['id' => $contact['id']]
2761 DBA::close($contacts);
2765 * Remove the unavailable contact ids from the provided list
2767 * @param array $contact_ids Contact id list
2769 * @throws \Exception
2771 public static function pruneUnavailable(array $contact_ids)
2773 if (empty($contact_ids)) {
2777 $contacts = Contact::selectToArray(['id'], [
2778 'id' => $contact_ids,
2784 return array_column($contacts, 'id');
2788 * Returns a magic link to authenticate remote visitors
2790 * @todo check if the return is either a fully qualified URL or a relative path to Friendica basedir
2792 * @param string $contact_url The address of the target contact profile
2793 * @param string $url An url that we will be redirected to after the authentication
2795 * @return string with "redir" link
2796 * @throws HTTPException\InternalServerErrorException
2797 * @throws \ImagickException
2799 public static function magicLink($contact_url, $url = '')
2801 if (!Session::isAuthenticated()) {
2802 return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
2805 $data = self::getProbeDataFromDatabase($contact_url);
2807 return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
2810 // Prevents endless loop in case only a non-public contact exists for the contact URL
2811 unset($data['uid']);
2813 return self::magicLinkByContact($data, $url ?: $contact_url);
2817 * Returns a magic link to authenticate remote visitors
2819 * @param integer $cid The contact id of the target contact profile
2820 * @param string $url An url that we will be redirected to after the authentication
2822 * @return string with "redir" link
2823 * @throws HTTPException\InternalServerErrorException
2824 * @throws \ImagickException
2826 public static function magicLinkbyId($cid, $url = '')
2828 $contact = DBA::selectFirst('contact', ['id', 'network', 'url', 'uid'], ['id' => $cid]);
2830 return self::magicLinkByContact($contact, $url);
2834 * Returns a magic link to authenticate remote visitors
2836 * @param array $contact The contact array with "uid", "network" and "url"
2837 * @param string $url An url that we will be redirected to after the authentication
2839 * @return string with "redir" link
2840 * @throws HTTPException\InternalServerErrorException
2841 * @throws \ImagickException
2843 public static function magicLinkByContact($contact, $url = '')
2845 $destination = $url ?: $contact['url']; // Equivalent to ($url != '') ? $url : $contact['url'];
2847 if (!Session::isAuthenticated() || ($contact['network'] != Protocol::DFRN)) {
2848 return $destination;
2851 // Only redirections to the same host do make sense
2852 if (($url != '') && (parse_url($url, PHP_URL_HOST) != parse_url($contact['url'], PHP_URL_HOST))) {
2856 if (!empty($contact['uid'])) {
2857 return self::magicLink($contact['url'], $url);
2860 if (empty($contact['id'])) {
2861 return $destination;
2864 $redirect = 'redir/' . $contact['id'];
2866 if (($url != '') && !Strings::compareLink($contact['url'], $url)) {
2867 $redirect .= '?url=' . $url;
2874 * Remove a contact from all groups
2876 * @param integer $contact_id
2878 * @return boolean Success
2880 public static function removeFromGroups($contact_id)
2882 return DBA::delete('group_member', ['contact-id' => $contact_id]);
2886 * Is the contact a forum?
2888 * @param integer $contactid ID of the contact
2890 * @return boolean "true" if it is a forum
2892 public static function isForum($contactid)
2894 $fields = ['forum', 'prv'];
2895 $condition = ['id' => $contactid];
2896 $contact = DBA::selectFirst('contact', $fields, $condition);
2897 if (!DBA::isResult($contact)) {
2902 return ($contact['forum'] || $contact['prv']);
2906 * Can the remote contact receive private messages?
2908 * @param array $contact
2911 public static function canReceivePrivateMessages(array $contact)
2913 $protocol = $contact['network'] ?? $contact['protocol'] ?? Protocol::PHANTOM;
2914 $self = $contact['self'] ?? false;
2916 return in_array($protocol, [Protocol::DFRN, Protocol::DIASPORA, Protocol::ACTIVITYPUB]) && !$self;
2920 * Search contact table by nick or name
2922 * @param string $search Name or nick
2923 * @param string $mode Search mode (e.g. "community")
2925 * @return array with search results
2926 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2928 public static function searchByName($search, $mode = '')
2930 if (empty($search)) {
2934 // check supported networks
2935 if (DI::config()->get('system', 'diaspora_enabled')) {
2936 $diaspora = Protocol::DIASPORA;
2938 $diaspora = Protocol::DFRN;
2941 if (!DI::config()->get('system', 'ostatus_disabled')) {
2942 $ostatus = Protocol::OSTATUS;
2944 $ostatus = Protocol::DFRN;
2947 // check if we search only communities or every contact
2948 if ($mode === 'community') {
2949 $extra_sql = sprintf(' AND `contact-type` = %d', Contact::TYPE_COMMUNITY);
2956 $results = DBA::p("SELECT * FROM `contact`
2957 WHERE NOT `unsearchable` AND `network` IN (?, ?, ?, ?) AND
2958 NOT `failed` AND `uid` = ? AND
2959 (`addr` LIKE ? OR `name` LIKE ? OR `nick` LIKE ?) $extra_sql
2960 ORDER BY `nurl` DESC LIMIT 1000",
2961 Protocol::DFRN, Protocol::ACTIVITYPUB, $ostatus, $diaspora, 0, $search, $search, $search
2964 $contacts = DBA::toArray($results);
2969 * @param int $uid user
2970 * @param int $start optional, default 0
2971 * @param int $limit optional, default 80
2974 static public function getSuggestions(int $uid, int $start = 0, int $limit = 80)
2976 $cid = self::getPublicIdByUserId($uid);
2977 $totallimit = $start + $limit;
2980 Logger::info('Collecting suggestions', ['uid' => $uid, 'cid' => $cid, 'start' => $start, 'limit' => $limit]);
2982 $diaspora = DI::config()->get('system', 'diaspora_enabled') ? Protocol::DIASPORA : Protocol::ACTIVITYPUB;
2983 $ostatus = !DI::config()->get('system', 'ostatus_disabled') ? Protocol::OSTATUS : Protocol::ACTIVITYPUB;
2985 // The query returns contacts where contacts interacted with whom the given user follows.
2986 // Contacts who already are in the user's contact table are ignored.
2987 $results = DBA::select('contact', [],
2988 ["`id` IN (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` IN
2989 (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` = ?)
2990 AND NOT `cid` IN (SELECT `id` FROM `contact` WHERE `uid` = ? AND `nurl` IN
2991 (SELECT `nurl` FROM `contact` WHERE `uid` = ? AND `rel` IN (?, ?))))
2992 AND NOT `hidden` AND `network` IN (?, ?, ?, ?)",
2993 $cid, 0, $uid, Contact::FRIEND, Contact::SHARING,
2994 Protocol::ACTIVITYPUB, Protocol::DFRN, $diaspora, $ostatus],
2995 ['order' => ['last-item' => true], 'limit' => $totallimit]
2998 while ($contact = DBA::fetch($results)) {
2999 $contacts[$contact['id']] = $contact;
3001 DBA::close($results);
3003 Logger::info('Contacts of contacts who are followed by the given user', ['uid' => $uid, 'cid' => $cid, 'count' => count($contacts)]);
3005 if (count($contacts) >= $totallimit) {
3006 return array_slice($contacts, $start, $limit);
3009 // The query returns contacts where contacts interacted with whom also interacted with the given user.
3010 // Contacts who already are in the user's contact table are ignored.
3011 $results = DBA::select('contact', [],
3012 ["`id` IN (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` IN
3013 (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ?)
3014 AND NOT `cid` IN (SELECT `id` FROM `contact` WHERE `uid` = ? AND `nurl` IN
3015 (SELECT `nurl` FROM `contact` WHERE `uid` = ? AND `rel` IN (?, ?))))
3016 AND NOT `hidden` AND `network` IN (?, ?, ?, ?)",
3017 $cid, 0, $uid, Contact::FRIEND, Contact::SHARING,
3018 Protocol::ACTIVITYPUB, Protocol::DFRN, $diaspora, $ostatus],
3019 ['order' => ['last-item' => true], 'limit' => $totallimit]
3022 while ($contact = DBA::fetch($results)) {
3023 $contacts[$contact['id']] = $contact;
3025 DBA::close($results);
3027 Logger::info('Contacts of contacts who are following the given user', ['uid' => $uid, 'cid' => $cid, 'count' => count($contacts)]);
3029 if (count($contacts) >= $totallimit) {
3030 return array_slice($contacts, $start, $limit);
3033 // The query returns contacts that follow the given user but aren't followed by that user.
3034 $results = DBA::select('contact', [],
3035 ["`nurl` IN (SELECT `nurl` FROM `contact` WHERE `uid` = ? AND `rel` = ?)
3036 AND NOT `hidden` AND `uid` = ? AND `network` IN (?, ?, ?, ?)",
3037 $uid, Contact::FOLLOWER, 0,
3038 Protocol::ACTIVITYPUB, Protocol::DFRN, $diaspora, $ostatus],
3039 ['order' => ['last-item' => true], 'limit' => $totallimit]
3042 while ($contact = DBA::fetch($results)) {
3043 $contacts[$contact['id']] = $contact;
3045 DBA::close($results);
3047 Logger::info('Followers that are not followed by the given user', ['uid' => $uid, 'cid' => $cid, 'count' => count($contacts)]);
3049 if (count($contacts) >= $totallimit) {
3050 return array_slice($contacts, $start, $limit);
3053 // The query returns any contact that isn't followed by that user.
3054 $results = DBA::select('contact', [],
3055 ["NOT `nurl` IN (SELECT `nurl` FROM `contact` WHERE `uid` = ? AND `rel` IN (?, ?))
3056 AND NOT `hidden` AND `uid` = ? AND `network` IN (?, ?, ?, ?)",
3057 $uid, Contact::FRIEND, Contact::SHARING, 0,
3058 Protocol::ACTIVITYPUB, Protocol::DFRN, $diaspora, $ostatus],
3059 ['order' => ['last-item' => true], 'limit' => $totallimit]
3062 while ($contact = DBA::fetch($results)) {
3063 $contacts[$contact['id']] = $contact;
3065 DBA::close($results);
3067 Logger::info('Any contact', ['uid' => $uid, 'cid' => $cid, 'count' => count($contacts)]);
3069 return array_slice($contacts, $start, $limit);