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\ContactSelector;
26 use Friendica\Content\Pager;
27 use Friendica\Core\Hook;
28 use Friendica\Core\Logger;
29 use Friendica\Core\Protocol;
30 use Friendica\Core\Session;
31 use Friendica\Core\System;
32 use Friendica\Core\Worker;
33 use Friendica\Database\DBA;
35 use Friendica\Model\Notify\Type;
36 use Friendica\Network\HTTPException;
37 use Friendica\Network\Probe;
38 use Friendica\Protocol\Activity;
39 use Friendica\Protocol\ActivityPub;
40 use Friendica\Protocol\DFRN;
41 use Friendica\Protocol\Diaspora;
42 use Friendica\Protocol\OStatus;
43 use Friendica\Protocol\Salmon;
44 use Friendica\Util\DateTimeFormat;
45 use Friendica\Util\Images;
46 use Friendica\Util\Network;
47 use Friendica\Util\Proxy;
48 use Friendica\Util\Strings;
51 * functions for interacting with a contact
56 * @deprecated since version 2019.03
57 * @see User::PAGE_FLAGS_NORMAL
59 const PAGE_NORMAL = User::PAGE_FLAGS_NORMAL;
61 * @deprecated since version 2019.03
62 * @see User::PAGE_FLAGS_SOAPBOX
64 const PAGE_SOAPBOX = User::PAGE_FLAGS_SOAPBOX;
66 * @deprecated since version 2019.03
67 * @see User::PAGE_FLAGS_COMMUNITY
69 const PAGE_COMMUNITY = User::PAGE_FLAGS_COMMUNITY;
71 * @deprecated since version 2019.03
72 * @see User::PAGE_FLAGS_FREELOVE
74 const PAGE_FREELOVE = User::PAGE_FLAGS_FREELOVE;
76 * @deprecated since version 2019.03
77 * @see User::PAGE_FLAGS_BLOG
79 const PAGE_BLOG = User::PAGE_FLAGS_BLOG;
81 * @deprecated since version 2019.03
82 * @see User::PAGE_FLAGS_PRVGROUP
84 const PAGE_PRVGROUP = User::PAGE_FLAGS_PRVGROUP;
92 * TYPE_UNKNOWN - the account has been imported from gcontact where this is the default type value
94 * TYPE_PERSON - the account belongs to a person
95 * Associated page types: PAGE_NORMAL, PAGE_SOAPBOX, PAGE_FREELOVE
97 * TYPE_ORGANISATION - the account belongs to an organisation
98 * Associated page type: PAGE_SOAPBOX
100 * TYPE_NEWS - the account is a news reflector
101 * Associated page type: PAGE_SOAPBOX
103 * TYPE_COMMUNITY - the account is community forum
104 * Associated page types: PAGE_COMMUNITY, PAGE_PRVGROUP
106 * TYPE_RELAY - the account is a relay
107 * This will only be assigned to contacts, not to user accounts
110 const TYPE_UNKNOWN = -1;
111 const TYPE_PERSON = User::ACCOUNT_TYPE_PERSON;
112 const TYPE_ORGANISATION = User::ACCOUNT_TYPE_ORGANISATION;
113 const TYPE_NEWS = User::ACCOUNT_TYPE_NEWS;
114 const TYPE_COMMUNITY = User::ACCOUNT_TYPE_COMMUNITY;
115 const TYPE_RELAY = User::ACCOUNT_TYPE_RELAY;
134 * @param array $fields Array of selected fields, empty for all
135 * @param array $condition Array of fields for condition
136 * @param array $params Array of several parameters
140 public static function selectToArray(array $fields = [], array $condition = [], array $params = [])
142 return DBA::selectToArray('contact', $fields, $condition, $params);
146 * @param array $fields Array of selected fields, empty for all
147 * @param array $condition Array of fields for condition
148 * @param array $params Array of several parameters
152 public static function selectFirst(array $fields = [], array $condition = [], array $params = [])
154 $contact = DBA::selectFirst('contact', $fields, $condition, $params);
160 * Insert a row into the contact table
161 * Important: You can't use DBA::lastInsertId() after this call since it will be set to 0.
163 * @param array $fields field array
164 * @param bool $on_duplicate_update Do an update on a duplicate entry
166 * @return boolean was the insert successful?
169 public static function insert(array $fields, bool $on_duplicate_update = false)
171 $ret = DBA::insert('contact', $fields, $on_duplicate_update);
172 $contact = DBA::selectFirst('contact', ['nurl', 'uid'], ['id' => DBA::lastInsertId()]);
173 if (!DBA::isResult($contact)) {
178 // Search for duplicated contacts and get rid of them
179 self::removeDuplicates($contact['nurl'], $contact['uid']);
185 * @param integer $id Contact ID
186 * @param array $fields Array of selected fields, empty for all
187 * @return array|boolean Contact record if it exists, false otherwise
190 public static function getById($id, $fields = [])
192 return DBA::selectFirst('contact', $fields, ['id' => $id]);
196 * Fetches a contact by a given url
198 * @param string $url profile url
199 * @param boolean $update true = always update, false = never update, null = update when not found or outdated
200 * @param array $fields Field list
201 * @param integer $uid User ID of the contact
202 * @return array contact array
204 public static function getByURL(string $url, $update = null, array $fields = [], int $uid = 0)
206 if ($update || is_null($update)) {
207 $cid = self::getIdForURL($url, $uid, $update);
212 $contact = self::getById($cid, $fields);
213 if (empty($contact)) {
219 // Add internal fields
221 if (!empty($fields)) {
222 foreach (['id', 'updated', 'network'] as $internal) {
223 if (!in_array($internal, $fields)) {
224 $fields[] = $internal;
225 $removal[] = $internal;
230 // We first try the nurl (http://server.tld/nick), most common case
231 $options = ['order' => ['id']];
232 $contact = DBA::selectFirst('contact', $fields, ['nurl' => Strings::normaliseLink($url), 'uid' => $uid, 'deleted' => false], $options);
234 // Then the addr (nick@server.tld)
235 if (!DBA::isResult($contact)) {
236 $contact = DBA::selectFirst('contact', $fields, ['addr' => str_replace('acct:', '', $url), 'uid' => $uid, 'deleted' => false], $options);
239 // Then the alias (which could be anything)
240 if (!DBA::isResult($contact)) {
241 // The link could be provided as http although we stored it as https
242 $ssl_url = str_replace('http://', 'https://', $url);
243 $condition = ['`alias` IN (?, ?, ?) AND `uid` = ? AND NOT `deleted`', $url, Strings::normaliseLink($url), $ssl_url, $uid];
244 $contact = DBA::selectFirst('contact', $fields, $condition, $options);
247 if (!DBA::isResult($contact)) {
251 // Update the contact in the background if needed
252 if ((($contact['updated'] < DateTimeFormat::utc('now -7 days')) || empty($contact['avatar'])) &&
253 in_array($contact['network'], Protocol::FEDERATED)) {
254 Worker::add(PRIORITY_LOW, "UpdateContact", $contact['id'], ($uid == 0 ? 'force' : ''));
257 // Remove the internal fields
258 foreach ($removal as $internal) {
259 unset($contact[$internal]);
266 * Fetches a contact for a given user by a given url.
267 * In difference to "getByURL" the function will fetch a public contact when no user contact had been found.
269 * @param string $url profile url
270 * @param integer $uid User ID of the contact
271 * @param boolean $update true = always update, false = never update, null = update when not found or outdated
272 * @param array $fields Field list
273 * @return array contact array
275 public static function getByURLForUser(string $url, int $uid = 0, $update = false, array $fields = [])
278 $contact = self::getByURL($url, $update, $fields, $uid);
279 if (!empty($contact)) {
280 if (!empty($contact['id'])) {
281 $contact['cid'] = $contact['id'];
288 $contact = self::getByURL($url, $update, $fields);
289 if (!empty($contact['id'])) {
291 $contact['zid'] = $contact['id'];
297 * Tests if the given contact is a follower
299 * @param int $cid Either public contact id or user's contact id
300 * @param int $uid User ID
302 * @return boolean is the contact id a follower?
303 * @throws HTTPException\InternalServerErrorException
304 * @throws \ImagickException
306 public static function isFollower($cid, $uid)
308 if (self::isBlockedByUser($cid, $uid)) {
312 $cdata = self::getPublicAndUserContacID($cid, $uid);
313 if (empty($cdata['user'])) {
317 $condition = ['id' => $cdata['user'], 'rel' => [self::FOLLOWER, self::FRIEND]];
318 return DBA::exists('contact', $condition);
322 * Tests if the given contact url is a follower
324 * @param string $url Contact URL
325 * @param int $uid User ID
327 * @return boolean is the contact id a follower?
328 * @throws HTTPException\InternalServerErrorException
329 * @throws \ImagickException
331 public static function isFollowerByURL($url, $uid)
333 $cid = self::getIdForURL($url, $uid, false);
339 return self::isFollower($cid, $uid);
343 * Tests if the given user follow the given contact
345 * @param int $cid Either public contact id or user's contact id
346 * @param int $uid User ID
348 * @return boolean is the contact url being followed?
349 * @throws HTTPException\InternalServerErrorException
350 * @throws \ImagickException
352 public static function isSharing($cid, $uid)
354 if (self::isBlockedByUser($cid, $uid)) {
358 $cdata = self::getPublicAndUserContacID($cid, $uid);
359 if (empty($cdata['user'])) {
363 $condition = ['id' => $cdata['user'], 'rel' => [self::SHARING, self::FRIEND]];
364 return DBA::exists('contact', $condition);
368 * Tests if the given user follow the given contact url
370 * @param string $url Contact URL
371 * @param int $uid User ID
373 * @return boolean is the contact url being followed?
374 * @throws HTTPException\InternalServerErrorException
375 * @throws \ImagickException
377 public static function isSharingByURL($url, $uid)
379 $cid = self::getIdForURL($url, $uid, false);
385 return self::isSharing($cid, $uid);
389 * Get the basepath for a given contact link
391 * @param string $url The contact link
392 * @param boolean $dont_update Don't update the contact
394 * @return string basepath
395 * @throws HTTPException\InternalServerErrorException
396 * @throws \ImagickException
398 public static function getBasepath($url, $dont_update = false)
400 $contact = DBA::selectFirst('contact', ['id', 'baseurl'], ['uid' => 0, 'nurl' => Strings::normaliseLink($url)]);
401 if (!DBA::isResult($contact)) {
405 if (!empty($contact['baseurl'])) {
406 return $contact['baseurl'];
407 } elseif ($dont_update) {
411 // Update the existing contact
412 self::updateFromProbe($contact['id'], '', true);
414 // And fetch the result
415 $contact = DBA::selectFirst('contact', ['baseurl'], ['id' => $contact['id']]);
416 if (empty($contact['baseurl'])) {
417 Logger::info('No baseurl for contact', ['url' => $url]);
421 Logger::info('Found baseurl for contact', ['url' => $url, 'baseurl' => $contact['baseurl']]);
422 return $contact['baseurl'];
426 * Check if the given contact url is on the same server
428 * @param string $url The contact link
430 * @return boolean Is it the same server?
432 public static function isLocal($url)
434 return Strings::compareLink(self::getBasepath($url, true), DI::baseUrl());
438 * Check if the given contact ID is on the same server
440 * @param string $url The contact link
442 * @return boolean Is it the same server?
444 public static function isLocalById(int $cid)
446 $contact = DBA::selectFirst('contact', ['url', 'baseurl'], ['id' => $cid]);
447 if (!DBA::isResult($contact)) {
451 if (empty($contact['baseurl'])) {
452 $baseurl = self::getBasepath($contact['url'], true);
454 $baseurl = $contact['baseurl'];
457 return Strings::compareLink($baseurl, DI::baseUrl());
461 * Returns the public contact id of the given user id
463 * @param integer $uid User ID
465 * @return integer|boolean Public contact id for given user id
468 public static function getPublicIdByUserId($uid)
470 $self = DBA::selectFirst('contact', ['url'], ['self' => true, 'uid' => $uid]);
471 if (!DBA::isResult($self)) {
474 return self::getIdForURL($self['url'], 0, false);
478 * Returns the contact id for the user and the public contact id for a given contact id
480 * @param int $cid Either public contact id or user's contact id
481 * @param int $uid User ID
483 * @return array with public and user's contact id
484 * @throws HTTPException\InternalServerErrorException
485 * @throws \ImagickException
487 public static function getPublicAndUserContacID($cid, $uid)
489 if (empty($uid) || empty($cid)) {
493 $contact = DBA::selectFirst('contact', ['id', 'uid', 'url'], ['id' => $cid]);
494 if (!DBA::isResult($contact)) {
498 // We quit when the user id don't match the user id of the provided contact
499 if (($contact['uid'] != $uid) && ($contact['uid'] != 0)) {
503 if ($contact['uid'] != 0) {
504 $pcid = Contact::getIdForURL($contact['url'], 0, false, ['url' => $contact['url']]);
508 $ucid = $contact['id'];
510 $pcid = $contact['id'];
511 $ucid = Contact::getIdForURL($contact['url'], $uid, false);
514 return ['public' => $pcid, 'user' => $ucid];
518 * Returns contact details for a given contact id in combination with a user id
520 * @param int $cid A contact ID
521 * @param int $uid The User ID
522 * @param array $fields The selected fields for the contact
524 * @return array The contact details
528 public static function getContactForUser($cid, $uid, array $fields = [])
530 $contact = DBA::selectFirst('contact', $fields, ['id' => $cid, 'uid' => $uid]);
532 if (!DBA::isResult($contact)) {
540 * Block contact id for user id
542 * @param int $cid Either public contact id or user's contact id
543 * @param int $uid User ID
544 * @param boolean $blocked Is the contact blocked or unblocked?
547 public static function setBlockedForUser($cid, $uid, $blocked)
549 $cdata = self::getPublicAndUserContacID($cid, $uid);
554 if ($cdata['user'] != 0) {
555 DBA::update('contact', ['blocked' => $blocked], ['id' => $cdata['user'], 'pending' => false]);
558 DBA::update('user-contact', ['blocked' => $blocked], ['cid' => $cdata['public'], 'uid' => $uid], true);
562 * Returns "block" state for contact id and user id
564 * @param int $cid Either public contact id or user's contact id
565 * @param int $uid User ID
567 * @return boolean is the contact id blocked for the given user?
570 public static function isBlockedByUser($cid, $uid)
572 $cdata = self::getPublicAndUserContacID($cid, $uid);
577 $public_blocked = false;
579 if (!empty($cdata['public'])) {
580 $public_contact = DBA::selectFirst('user-contact', ['blocked'], ['cid' => $cdata['public'], 'uid' => $uid]);
581 if (DBA::isResult($public_contact)) {
582 $public_blocked = $public_contact['blocked'];
586 $user_blocked = $public_blocked;
588 if (!empty($cdata['user'])) {
589 $user_contact = DBA::selectFirst('contact', ['blocked'], ['id' => $cdata['user'], 'pending' => false]);
590 if (DBA::isResult($user_contact)) {
591 $user_blocked = $user_contact['blocked'];
595 if ($user_blocked != $public_blocked) {
596 DBA::update('user-contact', ['blocked' => $user_blocked], ['cid' => $cdata['public'], 'uid' => $uid], true);
599 return $user_blocked;
603 * Ignore contact id for user id
605 * @param int $cid Either public contact id or user's contact id
606 * @param int $uid User ID
607 * @param boolean $ignored Is the contact ignored or unignored?
610 public static function setIgnoredForUser($cid, $uid, $ignored)
612 $cdata = self::getPublicAndUserContacID($cid, $uid);
617 if ($cdata['user'] != 0) {
618 DBA::update('contact', ['readonly' => $ignored], ['id' => $cdata['user'], 'pending' => false]);
621 DBA::update('user-contact', ['ignored' => $ignored], ['cid' => $cdata['public'], 'uid' => $uid], true);
625 * Returns "ignore" state for contact id and user id
627 * @param int $cid Either public contact id or user's contact id
628 * @param int $uid User ID
630 * @return boolean is the contact id ignored for the given user?
633 public static function isIgnoredByUser($cid, $uid)
635 $cdata = self::getPublicAndUserContacID($cid, $uid);
640 $public_ignored = false;
642 if (!empty($cdata['public'])) {
643 $public_contact = DBA::selectFirst('user-contact', ['ignored'], ['cid' => $cdata['public'], 'uid' => $uid]);
644 if (DBA::isResult($public_contact)) {
645 $public_ignored = $public_contact['ignored'];
649 $user_ignored = $public_ignored;
651 if (!empty($cdata['user'])) {
652 $user_contact = DBA::selectFirst('contact', ['readonly'], ['id' => $cdata['user'], 'pending' => false]);
653 if (DBA::isResult($user_contact)) {
654 $user_ignored = $user_contact['readonly'];
658 if ($user_ignored != $public_ignored) {
659 DBA::update('user-contact', ['ignored' => $user_ignored], ['cid' => $cdata['public'], 'uid' => $uid], true);
662 return $user_ignored;
666 * Set "collapsed" for contact id and user id
668 * @param int $cid Either public contact id or user's contact id
669 * @param int $uid User ID
670 * @param boolean $collapsed are the contact's posts collapsed or uncollapsed?
673 public static function setCollapsedForUser($cid, $uid, $collapsed)
675 $cdata = self::getPublicAndUserContacID($cid, $uid);
680 DBA::update('user-contact', ['collapsed' => $collapsed], ['cid' => $cdata['public'], 'uid' => $uid], true);
684 * Returns "collapsed" state for contact id and user id
686 * @param int $cid Either public contact id or user's contact id
687 * @param int $uid User ID
689 * @return boolean is the contact id blocked for the given user?
690 * @throws HTTPException\InternalServerErrorException
691 * @throws \ImagickException
693 public static function isCollapsedByUser($cid, $uid)
695 $cdata = self::getPublicAndUserContacID($cid, $uid);
702 if (!empty($cdata['public'])) {
703 $public_contact = DBA::selectFirst('user-contact', ['collapsed'], ['cid' => $cdata['public'], 'uid' => $uid]);
704 if (DBA::isResult($public_contact)) {
705 $collapsed = $public_contact['collapsed'];
713 * Returns a list of contacts belonging in a group
719 public static function getByGroupId($gid)
724 $stmt = DBA::p('SELECT `group_member`.`contact-id`, `contact`.*
726 INNER JOIN `group_member`
727 ON `contact`.`id` = `group_member`.`contact-id`
729 AND `contact`.`uid` = ?
730 AND NOT `contact`.`self`
731 AND NOT `contact`.`deleted`
732 AND NOT `contact`.`blocked`
733 AND NOT `contact`.`pending`
734 ORDER BY `contact`.`name` ASC',
739 if (DBA::isResult($stmt)) {
740 $return = DBA::toArray($stmt);
748 * Creates the self-contact for the provided user id
751 * @return bool Operation success
752 * @throws HTTPException\InternalServerErrorException
754 public static function createSelfFromUserId($uid)
756 // Only create the entry if it doesn't exist yet
757 if (DBA::exists('contact', ['uid' => $uid, 'self' => true])) {
761 $user = DBA::selectFirst('user', ['uid', 'username', 'nickname'], ['uid' => $uid]);
762 if (!DBA::isResult($user)) {
766 $return = DBA::insert('contact', [
767 'uid' => $user['uid'],
768 'created' => DateTimeFormat::utcNow(),
770 'name' => $user['username'],
771 'nick' => $user['nickname'],
772 'photo' => DI::baseUrl() . '/photo/profile/' . $user['uid'] . '.jpg',
773 'thumb' => DI::baseUrl() . '/photo/avatar/' . $user['uid'] . '.jpg',
774 'micro' => DI::baseUrl() . '/photo/micro/' . $user['uid'] . '.jpg',
777 'url' => DI::baseUrl() . '/profile/' . $user['nickname'],
778 'nurl' => Strings::normaliseLink(DI::baseUrl() . '/profile/' . $user['nickname']),
779 'addr' => $user['nickname'] . '@' . substr(DI::baseUrl(), strpos(DI::baseUrl(), '://') + 3),
780 'request' => DI::baseUrl() . '/dfrn_request/' . $user['nickname'],
781 'notify' => DI::baseUrl() . '/dfrn_notify/' . $user['nickname'],
782 'poll' => DI::baseUrl() . '/dfrn_poll/' . $user['nickname'],
783 'confirm' => DI::baseUrl() . '/dfrn_confirm/' . $user['nickname'],
784 'poco' => DI::baseUrl() . '/poco/' . $user['nickname'],
785 'name-date' => DateTimeFormat::utcNow(),
786 'uri-date' => DateTimeFormat::utcNow(),
787 'avatar-date' => DateTimeFormat::utcNow(),
795 * Updates the self-contact for the provided user id
798 * @param boolean $update_avatar Force the avatar update
799 * @throws HTTPException\InternalServerErrorException
801 public static function updateSelfFromUserID($uid, $update_avatar = false)
803 $fields = ['id', 'name', 'nick', 'location', 'about', 'keywords', 'avatar',
804 'xmpp', 'contact-type', 'forum', 'prv', 'avatar-date', 'url', 'nurl', 'unsearchable',
805 'photo', 'thumb', 'micro', 'addr', 'request', 'notify', 'poll', 'confirm', 'poco'];
806 $self = DBA::selectFirst('contact', $fields, ['uid' => $uid, 'self' => true]);
807 if (!DBA::isResult($self)) {
811 $fields = ['nickname', 'page-flags', 'account-type'];
812 $user = DBA::selectFirst('user', $fields, ['uid' => $uid]);
813 if (!DBA::isResult($user)) {
817 $fields = ['name', 'photo', 'thumb', 'about', 'address', 'locality', 'region',
818 'country-name', 'pub_keywords', 'xmpp', 'net-publish'];
819 $profile = DBA::selectFirst('profile', $fields, ['uid' => $uid]);
820 if (!DBA::isResult($profile)) {
824 $file_suffix = 'jpg';
826 $fields = ['name' => $profile['name'], 'nick' => $user['nickname'],
827 'avatar-date' => $self['avatar-date'], 'location' => Profile::formatLocation($profile),
828 'about' => $profile['about'], 'keywords' => $profile['pub_keywords'],
829 'contact-type' => $user['account-type'],
830 'xmpp' => $profile['xmpp']];
832 $avatar = Photo::selectFirst(['resource-id', 'type'], ['uid' => $uid, 'profile' => true]);
833 if (DBA::isResult($avatar)) {
834 if ($update_avatar) {
835 $fields['avatar-date'] = DateTimeFormat::utcNow();
838 // Creating the path to the avatar, beginning with the file suffix
839 $types = Images::supportedTypes();
840 if (isset($types[$avatar['type']])) {
841 $file_suffix = $types[$avatar['type']];
844 // We are adding a timestamp value so that other systems won't use cached content
845 $timestamp = strtotime($fields['avatar-date']);
847 $prefix = DI::baseUrl() . '/photo/' .$avatar['resource-id'] . '-';
848 $suffix = '.' . $file_suffix . '?ts=' . $timestamp;
850 $fields['photo'] = $prefix . '4' . $suffix;
851 $fields['thumb'] = $prefix . '5' . $suffix;
852 $fields['micro'] = $prefix . '6' . $suffix;
854 // We hadn't found a photo entry, so we use the default avatar
855 $fields['photo'] = DI::baseUrl() . '/images/person-300.jpg';
856 $fields['thumb'] = DI::baseUrl() . '/images/person-80.jpg';
857 $fields['micro'] = DI::baseUrl() . '/images/person-48.jpg';
860 $fields['avatar'] = DI::baseUrl() . '/photo/profile/' .$uid . '.' . $file_suffix;
861 $fields['forum'] = $user['page-flags'] == User::PAGE_FLAGS_COMMUNITY;
862 $fields['prv'] = $user['page-flags'] == User::PAGE_FLAGS_PRVGROUP;
863 $fields['unsearchable'] = !$profile['net-publish'];
865 // it seems as if ported accounts can have wrong values, so we make sure that now everything is fine.
866 $fields['url'] = DI::baseUrl() . '/profile/' . $user['nickname'];
867 $fields['nurl'] = Strings::normaliseLink($fields['url']);
868 $fields['addr'] = $user['nickname'] . '@' . substr(DI::baseUrl(), strpos(DI::baseUrl(), '://') + 3);
869 $fields['request'] = DI::baseUrl() . '/dfrn_request/' . $user['nickname'];
870 $fields['notify'] = DI::baseUrl() . '/dfrn_notify/' . $user['nickname'];
871 $fields['poll'] = DI::baseUrl() . '/dfrn_poll/'. $user['nickname'];
872 $fields['confirm'] = DI::baseUrl() . '/dfrn_confirm/' . $user['nickname'];
873 $fields['poco'] = DI::baseUrl() . '/poco/' . $user['nickname'];
877 foreach ($fields as $field => $content) {
878 if ($self[$field] != $content) {
884 if ($fields['name'] != $self['name']) {
885 $fields['name-date'] = DateTimeFormat::utcNow();
887 $fields['updated'] = DateTimeFormat::utcNow();
888 DBA::update('contact', $fields, ['id' => $self['id']]);
890 // Update the public contact as well
891 DBA::update('contact', $fields, ['uid' => 0, 'nurl' => $self['nurl']]);
893 // Update the profile
894 $fields = ['photo' => DI::baseUrl() . '/photo/profile/' .$uid . '.' . $file_suffix,
895 'thumb' => DI::baseUrl() . '/photo/avatar/' . $uid .'.' . $file_suffix];
896 DBA::update('profile', $fields, ['uid' => $uid]);
901 * Marks a contact for removal
903 * @param int $id contact id
905 * @throws HTTPException\InternalServerErrorException
907 public static function remove($id)
909 // We want just to make sure that we don't delete our "self" contact
910 $contact = DBA::selectFirst('contact', ['uid'], ['id' => $id, 'self' => false]);
911 if (!DBA::isResult($contact) || !intval($contact['uid'])) {
915 // Archive the contact
916 DBA::update('contact', ['archive' => true, 'network' => Protocol::PHANTOM, 'deleted' => true], ['id' => $id]);
918 // Delete it in the background
919 Worker::add(PRIORITY_MEDIUM, 'RemoveContact', $id);
923 * Sends an unfriend message. Does not remove the contact
925 * @param array $user User unfriending
926 * @param array $contact Contact unfriended
927 * @param boolean $dissolve Remove the contact on the remote side
929 * @throws HTTPException\InternalServerErrorException
930 * @throws \ImagickException
932 public static function terminateFriendship(array $user, array $contact, $dissolve = false)
934 if (empty($contact['network'])) {
938 $protocol = $contact['network'];
939 if (($protocol == Protocol::DFRN) && !self::isLegacyDFRNContact($contact)) {
940 $protocol = Protocol::ACTIVITYPUB;
943 if (($protocol == Protocol::DFRN) && $dissolve) {
944 DFRN::deliver($user, $contact, 'placeholder', true);
945 } elseif (in_array($protocol, [Protocol::OSTATUS, Protocol::DFRN])) {
946 // create an unfollow slap
948 $item['verb'] = Activity::O_UNFOLLOW;
949 $item['gravity'] = GRAVITY_ACTIVITY;
950 $item['follow'] = $contact["url"];
955 $item['attach'] = '';
956 $slap = OStatus::salmon($item, $user);
958 if (!empty($contact['notify'])) {
959 Salmon::slapper($user, $contact['notify'], $slap);
961 } elseif ($protocol == Protocol::DIASPORA) {
962 Diaspora::sendUnshare($user, $contact);
963 } elseif ($protocol == Protocol::ACTIVITYPUB) {
964 ActivityPub\Transmitter::sendContactUndo($contact['url'], $contact['id'], $user['uid']);
967 ActivityPub\Transmitter::sendContactReject($contact['url'], $contact['hub-verify'], $user['uid']);
973 * Marks a contact for archival after a communication issue delay
975 * Contact has refused to recognise us as a friend. We will start a countdown.
976 * If they still don't recognise us in 32 days, the relationship is over,
977 * and we won't waste any more time trying to communicate with them.
978 * This provides for the possibility that their database is temporarily messed
979 * up or some other transient event and that there's a possibility we could recover from it.
981 * @param array $contact contact to mark for archival
983 * @throws HTTPException\InternalServerErrorException
985 public static function markForArchival(array $contact)
987 if (!isset($contact['url']) && !empty($contact['id'])) {
988 $fields = ['id', 'url', 'archive', 'self', 'term-date'];
989 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact['id']]);
990 if (!DBA::isResult($contact)) {
993 } elseif (!isset($contact['url'])) {
994 Logger::info('Empty contact', ['contact' => $contact, 'callstack' => System::callstack(20)]);
997 Logger::info('Contact is marked for archival', ['id' => $contact['id']]);
999 // Contact already archived or "self" contact? => nothing to do
1000 if ($contact['archive'] || $contact['self']) {
1004 if ($contact['term-date'] <= DBA::NULL_DATETIME) {
1005 DBA::update('contact', ['term-date' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
1006 DBA::update('contact', ['term-date' => DateTimeFormat::utcNow()], ['`nurl` = ? AND `term-date` <= ? AND NOT `self`', Strings::normaliseLink($contact['url']), DBA::NULL_DATETIME]);
1009 * We really should send a notification to the owner after 2-3 weeks
1010 * so they won't be surprised when the contact vanishes and can take
1011 * remedial action if this was a serious mistake or glitch
1014 /// @todo Check for contact vitality via probing
1015 $archival_days = DI::config()->get('system', 'archival_days', 32);
1017 $expiry = $contact['term-date'] . ' + ' . $archival_days . ' days ';
1018 if (DateTimeFormat::utcNow() > DateTimeFormat::utc($expiry)) {
1019 /* Relationship is really truly dead. archive them rather than
1020 * delete, though if the owner tries to unarchive them we'll start
1021 * the whole process over again.
1023 DBA::update('contact', ['archive' => true], ['id' => $contact['id']]);
1024 DBA::update('contact', ['archive' => true], ['nurl' => Strings::normaliseLink($contact['url']), 'self' => false]);
1025 GContact::updateFromPublicContactURL($contact['url']);
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]);
1070 GContact::updateFromPublicContactURL($contact['url']);
1074 * Returns the data array for the photo menu of a given contact
1076 * @param array $contact contact
1077 * @param int $uid optional, default 0
1079 * @throws HTTPException\InternalServerErrorException
1080 * @throws \ImagickException
1082 public static function photoMenu(array $contact, $uid = 0)
1087 $contact_drop_link = '';
1091 $uid = local_user();
1094 if (empty($contact['uid']) || ($contact['uid'] != $uid)) {
1096 $profile_link = self::magicLink($contact['url']);
1097 $menu = ['profile' => [DI::l10n()->t('View Profile'), $profile_link, true]];
1102 // Look for our own contact if the uid doesn't match and isn't public
1103 $contact_own = DBA::selectFirst('contact', [], ['nurl' => $contact['nurl'], 'network' => $contact['network'], 'uid' => $uid]);
1104 if (DBA::isResult($contact_own)) {
1105 return self::photoMenu($contact_own, $uid);
1110 if (($contact['network'] === Protocol::DFRN) && !$contact['self'] && empty($contact['pending'])) {
1112 $profile_link = DI::baseUrl() . '/redir/' . $contact['id'];
1114 $profile_link = $contact['url'];
1117 if ($profile_link === 'mailbox') {
1122 $status_link = $profile_link . '/status';
1123 $photos_link = str_replace('/profile/', '/photos/', $profile_link);
1124 $profile_link = $profile_link . '/profile';
1127 if (self::canReceivePrivateMessages($contact) && empty($contact['pending'])) {
1128 $pm_url = DI::baseUrl() . '/message/new/' . $contact['id'];
1131 if (($contact['network'] == Protocol::DFRN) && !$contact['self'] && empty($contact['pending'])) {
1132 $poke_link = 'contact/' . $contact['id'] . '/poke';
1135 $contact_url = DI::baseUrl() . '/contact/' . $contact['id'];
1137 $posts_link = DI::baseUrl() . '/contact/' . $contact['id'] . '/conversations';
1139 if (!$contact['self']) {
1140 $contact_drop_link = DI::baseUrl() . '/contact/' . $contact['id'] . '/drop?confirm=1';
1144 $unfollow_link = '';
1145 if (!$contact['self'] && in_array($contact['network'], Protocol::NATIVE_SUPPORT)) {
1146 if ($contact['uid'] && in_array($contact['rel'], [self::SHARING, self::FRIEND])) {
1147 $unfollow_link = 'unfollow?url=' . urlencode($contact['url']);
1148 } elseif(!$contact['pending']) {
1149 $follow_link = 'follow?url=' . urlencode($contact['url']);
1153 if (!empty($follow_link) || !empty($unfollow_link)) {
1154 $contact_drop_link = '';
1159 * "name" => [ "Label", "link", (bool)Should the link opened in a new tab? ]
1161 if (empty($contact['uid'])) {
1163 'profile' => [DI::l10n()->t('View Profile') , $profile_link , true],
1164 'network' => [DI::l10n()->t('Network Posts') , $posts_link , false],
1165 'edit' => [DI::l10n()->t('View Contact') , $contact_url , false],
1166 'follow' => [DI::l10n()->t('Connect/Follow'), $follow_link , true],
1167 'unfollow'=> [DI::l10n()->t('UnFollow') , $unfollow_link, true],
1171 'status' => [DI::l10n()->t('View Status') , $status_link , true],
1172 'profile' => [DI::l10n()->t('View Profile') , $profile_link , true],
1173 'photos' => [DI::l10n()->t('View Photos') , $photos_link , true],
1174 'network' => [DI::l10n()->t('Network Posts') , $posts_link , false],
1175 'edit' => [DI::l10n()->t('View Contact') , $contact_url , false],
1176 'drop' => [DI::l10n()->t('Drop Contact') , $contact_drop_link, false],
1177 'pm' => [DI::l10n()->t('Send PM') , $pm_url , false],
1178 'poke' => [DI::l10n()->t('Poke') , $poke_link , false],
1179 'follow' => [DI::l10n()->t('Connect/Follow'), $follow_link , true],
1180 'unfollow'=> [DI::l10n()->t('UnFollow') , $unfollow_link , true],
1183 if (!empty($contact['pending'])) {
1184 $intro = DBA::selectFirst('intro', ['id'], ['contact-id' => $contact['id']]);
1185 if (DBA::isResult($intro)) {
1186 $menu['follow'] = [DI::l10n()->t('Approve'), 'notifications/intros/' . $intro['id'], true];
1191 $args = ['contact' => $contact, 'menu' => &$menu];
1193 Hook::callAll('contact_photo_menu', $args);
1195 $menucondensed = [];
1197 foreach ($menu as $menuname => $menuitem) {
1198 if ($menuitem[1] != '') {
1199 $menucondensed[$menuname] = $menuitem;
1203 return $menucondensed;
1207 * Returns ungrouped contact count or list for user
1209 * Returns either the total number of ungrouped contacts for the given user
1210 * id or a paginated list of ungrouped contacts.
1212 * @param int $uid uid
1214 * @throws \Exception
1216 public static function getUngroupedList($uid)
1226 SELECT DISTINCT(`contact-id`)
1228 INNER JOIN `group` ON `group`.`id` = `group_member`.`gid`
1229 WHERE `group`.`uid` = %d
1230 )", intval($uid), intval($uid));
1234 * Have a look at all contact tables for a given profile url.
1235 * This function works as a replacement for probing the contact.
1237 * @param string $url Contact URL
1238 * @param integer $cid Contact ID
1240 * @return array Contact array in the "probe" structure
1242 private static function getProbeDataFromDatabase($url, $cid = null)
1244 // The link could be provided as http although we stored it as https
1245 $ssl_url = str_replace('http://', 'https://', $url);
1247 $fields = ['id', 'uid', 'url', 'addr', 'alias', 'notify', 'poll', 'name', 'nick',
1248 'photo', 'keywords', 'location', 'about', 'network',
1249 'priority', 'batch', 'request', 'confirm', 'poco'];
1252 $data = DBA::selectFirst('contact', $fields, ['id' => $cid]);
1253 if (DBA::isResult($data)) {
1258 $data = DBA::selectFirst('contact', $fields, ['nurl' => Strings::normaliseLink($url)]);
1260 if (!DBA::isResult($data)) {
1261 $condition = ['alias' => [$url, Strings::normaliseLink($url), $ssl_url]];
1262 $data = DBA::selectFirst('contact', $fields, $condition);
1265 if (DBA::isResult($data)) {
1266 // For security reasons we don't fetch key data from our users
1267 $data["pubkey"] = '';
1271 $fields = ['url', 'addr', 'alias', 'notify', 'name', 'nick',
1272 'photo', 'keywords', 'location', 'about', 'network'];
1273 $data = DBA::selectFirst('gcontact', $fields, ['nurl' => Strings::normaliseLink($url)]);
1275 if (!DBA::isResult($data)) {
1276 $condition = ['alias' => [$url, Strings::normaliseLink($url), $ssl_url]];
1277 $data = DBA::selectFirst('contact', $fields, $condition);
1280 if (DBA::isResult($data)) {
1281 $data["pubkey"] = '';
1283 $data["priority"] = 0;
1284 $data["batch"] = '';
1285 $data["request"] = '';
1286 $data["confirm"] = '';
1291 $data = ActivityPub::probeProfile($url, false);
1292 if (!empty($data)) {
1296 $fields = ['url', 'addr', 'alias', 'notify', 'poll', 'name', 'nick',
1297 'photo', 'network', 'priority', 'batch', 'request', 'confirm'];
1298 $data = DBA::selectFirst('fcontact', $fields, ['url' => $url]);
1300 if (!DBA::isResult($data)) {
1301 $condition = ['alias' => [$url, Strings::normaliseLink($url), $ssl_url]];
1302 $data = DBA::selectFirst('contact', $fields, $condition);
1305 if (DBA::isResult($data)) {
1306 $data["pubkey"] = '';
1307 $data["keywords"] = '';
1308 $data["location"] = '';
1309 $data["about"] = '';
1318 * Fetch the contact id for a given URL and user
1320 * First lookup in the contact table to find a record matching either `url`, `nurl`,
1321 * `addr` or `alias`.
1323 * If there's no record and we aren't looking for a public contact, we quit.
1324 * If there's one, we check that it isn't time to update the picture else we
1325 * directly return the found contact id.
1327 * Second, we probe the provided $url whether it's http://server.tld/profile or
1328 * nick@server.tld. We quit if we can't get any info back.
1330 * Third, we create the contact record if it doesn't exist
1332 * Fourth, we update the existing record with the new data (avatar, alias, nick)
1333 * if there's any updates
1335 * @param string $url Contact URL
1336 * @param integer $uid The user id for the contact (0 = public contact)
1337 * @param boolean $update true = always update, false = never update, null = update when not found or outdated
1338 * @param array $default Default value for creating the contact when every else fails
1339 * @param boolean $in_loop Internally used variable to prevent an endless loop
1341 * @return integer Contact ID
1342 * @throws HTTPException\InternalServerErrorException
1343 * @throws \ImagickException
1345 public static function getIdForURL($url, $uid = 0, $update = null, $default = [], $in_loop = false)
1347 Logger::info('Get contact data', ['url' => $url, 'user' => $uid]);
1355 $contact = self::getByURL($url, false, ['id', 'avatar', 'updated', 'network'], $uid);
1357 if (!empty($contact)) {
1358 $contact_id = $contact["id"];
1360 if (empty($default) && in_array($contact['network'], [Protocol::MAIL, Protocol::PHANTOM]) && ($uid == 0)) {
1361 // Update public mail accounts via their user's accounts
1362 $fields = ['network', 'addr', 'name', 'nick', 'avatar', 'photo', 'thumb', 'micro'];
1363 $mailcontact = DBA::selectFirst('contact', $fields, ["`addr` = ? AND `network` = ? AND `uid` != 0", $url, Protocol::MAIL]);
1364 if (!DBA::isResult($mailcontact)) {
1365 $mailcontact = DBA::selectFirst('contact', $fields, ["`nurl` = ? AND `network` = ? AND `uid` != 0", $url, Protocol::MAIL]);
1368 if (DBA::isResult($mailcontact)) {
1369 DBA::update('contact', $mailcontact, ['id' => $contact_id]);
1373 if (empty($update)) {
1376 } elseif ($uid != 0) {
1377 // Non-existing user-specific contact, exiting
1381 if (!$update && empty($default)) {
1382 // When we don't want to update, we look if we know this contact in any way
1383 $data = self::getProbeDataFromDatabase($url, $contact_id);
1384 $background_update = true;
1385 } elseif (!$update && !empty($default['network'])) {
1386 // If there are default values, take these
1388 $background_update = false;
1391 $background_update = false;
1394 if ((empty($data) && is_null($update)) || $update) {
1395 $data = Probe::uri($url, "", $uid);
1398 // Take the default values when probing failed
1399 if (!empty($default) && !in_array($data["network"], array_merge(Protocol::NATIVE_SUPPORT, [Protocol::PUMPIO]))) {
1400 $data = array_merge($data, $default);
1403 if (empty($data) || ($data['network'] == Protocol::PHANTOM)) {
1404 Logger::info('No valid network found', ['url' => $url, 'data' => $data, 'callstack' => System::callstack(20)]);
1408 if (!empty($data['baseurl'])) {
1409 $data['baseurl'] = GServer::cleanURL($data['baseurl']);
1412 if (!empty($data['baseurl']) && empty($data['gsid'])) {
1413 $data['gsid'] = GServer::getID($data['baseurl']);
1416 if (!$contact_id && !empty($data['alias']) && ($data['alias'] != $data['url']) && !$in_loop) {
1417 $contact_id = self::getIdForURL($data["alias"], $uid, false, $default, true);
1423 'created' => DateTimeFormat::utcNow(),
1424 'url' => $data['url'],
1425 'nurl' => Strings::normaliseLink($data['url']),
1426 'addr' => $data['addr'] ?? '',
1427 'alias' => $data['alias'] ?? '',
1428 'notify' => $data['notify'] ?? '',
1429 'poll' => $data['poll'] ?? '',
1430 'name' => $data['name'] ?? '',
1431 'nick' => $data['nick'] ?? '',
1432 'keywords' => $data['keywords'] ?? '',
1433 'location' => $data['location'] ?? '',
1434 'about' => $data['about'] ?? '',
1435 'network' => $data['network'],
1436 'pubkey' => $data['pubkey'] ?? '',
1437 'rel' => self::SHARING,
1438 'priority' => $data['priority'] ?? 0,
1439 'batch' => $data['batch'] ?? '',
1440 'request' => $data['request'] ?? '',
1441 'confirm' => $data['confirm'] ?? '',
1442 'poco' => $data['poco'] ?? '',
1443 'baseurl' => $data['baseurl'] ?? '',
1444 'gsid' => $data['gsid'] ?? null,
1445 'name-date' => DateTimeFormat::utcNow(),
1446 'uri-date' => DateTimeFormat::utcNow(),
1447 'avatar-date' => DateTimeFormat::utcNow(),
1453 $condition = ['nurl' => Strings::normaliseLink($data["url"]), 'uid' => $uid, 'deleted' => false];
1455 // Before inserting we do check if the entry does exist now.
1456 $contact = DBA::selectFirst('contact', ['id'], $condition, ['order' => ['id']]);
1457 if (!DBA::isResult($contact)) {
1458 Logger::info('Create new contact', $fields);
1460 self::insert($fields);
1462 // We intentionally aren't using lastInsertId here. There is a chance for duplicates.
1463 $contact = DBA::selectFirst('contact', ['id'], $condition, ['order' => ['id']]);
1464 if (!DBA::isResult($contact)) {
1465 Logger::info('Contact creation failed', $fields);
1470 Logger::info('Contact had been created before', ['id' => $contact["id"], 'url' => $url, 'contact' => $fields]);
1473 $contact_id = $contact["id"];
1476 if (!empty($data['photo']) && ($data['network'] != Protocol::FEED)) {
1477 self::updateAvatar($contact_id, $data['photo']);
1480 if (in_array($data["network"], array_merge(Protocol::NATIVE_SUPPORT, [Protocol::PUMPIO]))) {
1481 if ($background_update) {
1482 // Update in the background when we fetched the data solely from the database
1483 Worker::add(PRIORITY_MEDIUM, "UpdateContact", $contact_id, ($uid == 0 ? 'force' : ''));
1485 // Else do a direct update
1486 self::updateFromProbe($contact_id, '', false);
1489 $fields = ['url', 'nurl', 'addr', 'alias', 'name', 'nick', 'keywords', 'location', 'about', 'avatar-date', 'baseurl', 'gsid'];
1490 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact_id]);
1492 // This condition should always be true
1493 if (!DBA::isResult($contact)) {
1498 'url' => $data['url'],
1499 'nurl' => Strings::normaliseLink($data['url']),
1500 'updated' => DateTimeFormat::utcNow(),
1504 $fields = ['addr', 'alias', 'name', 'nick', 'keywords', 'location', 'about', 'baseurl', 'gsid'];
1506 foreach ($fields as $field) {
1507 $updated[$field] = ($data[$field] ?? '') ?: $contact[$field];
1510 if (($updated['addr'] != $contact['addr']) || (!empty($data['alias']) && ($data['alias'] != $contact['alias']))) {
1511 $updated['uri-date'] = DateTimeFormat::utcNow();
1514 if (($data['name'] != $contact['name']) || ($data['nick'] != $contact['nick'])) {
1515 $updated['name-date'] = DateTimeFormat::utcNow();
1518 DBA::update('contact', $updated, ['id' => $contact_id], $contact);
1525 * Checks if the contact is archived
1527 * @param int $cid contact id
1529 * @return boolean Is the contact archived?
1530 * @throws HTTPException\InternalServerErrorException
1532 public static function isArchived(int $cid)
1538 $contact = DBA::selectFirst('contact', ['archive', 'url', 'batch'], ['id' => $cid]);
1539 if (!DBA::isResult($contact)) {
1543 if ($contact['archive']) {
1547 // Check status of ActivityPub endpoints
1548 $apcontact = APContact::getByURL($contact['url'], false);
1549 if (!empty($apcontact)) {
1550 if (!empty($apcontact['inbox']) && DBA::exists('inbox-status', ['archive' => true, 'url' => $apcontact['inbox']])) {
1554 if (!empty($apcontact['sharedinbox']) && DBA::exists('inbox-status', ['archive' => true, 'url' => $apcontact['sharedinbox']])) {
1559 // Check status of Diaspora endpoints
1560 if (!empty($contact['batch'])) {
1561 $condition = ['archive' => true, 'uid' => 0, 'network' => Protocol::FEDERATED, 'batch' => $contact['batch'], 'contact-type' => self::TYPE_RELAY];
1562 return DBA::exists('contact', $condition);
1569 * Checks if the contact is blocked
1571 * @param int $cid contact id
1573 * @return boolean Is the contact blocked?
1574 * @throws HTTPException\InternalServerErrorException
1576 public static function isBlocked($cid)
1582 $blocked = DBA::selectFirst('contact', ['blocked', 'url'], ['id' => $cid]);
1583 if (!DBA::isResult($blocked)) {
1587 if (Network::isUrlBlocked($blocked['url'])) {
1591 return (bool) $blocked['blocked'];
1595 * Checks if the contact is hidden
1597 * @param int $cid contact id
1599 * @return boolean Is the contact hidden?
1600 * @throws \Exception
1602 public static function isHidden($cid)
1608 $hidden = DBA::selectFirst('contact', ['hidden'], ['id' => $cid]);
1609 if (!DBA::isResult($hidden)) {
1612 return (bool) $hidden['hidden'];
1616 * Returns posts from a given contact url
1618 * @param string $contact_url Contact URL
1619 * @param bool $thread_mode
1620 * @param int $update
1621 * @return string posts in HTML
1622 * @throws \Exception
1624 public static function getPostsFromUrl($contact_url, $thread_mode = false, $update = 0)
1626 return self::getPostsFromId(self::getIdForURL($contact_url), $thread_mode, $update);
1630 * Returns posts from a given contact id
1632 * @param integer $cid
1633 * @param bool $thread_mode
1634 * @param integer $update
1635 * @return string posts in HTML
1636 * @throws \Exception
1638 public static function getPostsFromId($cid, $thread_mode = false, $update = 0)
1642 $contact = DBA::selectFirst('contact', ['contact-type', 'network'], ['id' => $cid]);
1643 if (!DBA::isResult($contact)) {
1647 if (empty($contact["network"]) || in_array($contact["network"], Protocol::FEDERATED)) {
1648 $sql = "(`item`.`uid` = 0 OR (`item`.`uid` = ? AND NOT `item`.`global`))";
1650 $sql = "`item`.`uid` = ?";
1653 $contact_field = ((($contact["contact-type"] == self::TYPE_COMMUNITY) || ($contact['network'] == Protocol::MAIL)) ? 'owner-id' : 'author-id');
1656 $condition = ["`$contact_field` = ? AND `gravity` = ? AND " . $sql,
1657 $cid, GRAVITY_PARENT, local_user()];
1659 $condition = ["`$contact_field` = ? AND `gravity` IN (?, ?) AND " . $sql,
1660 $cid, GRAVITY_PARENT, GRAVITY_COMMENT, local_user()];
1663 if (DI::mode()->isMobile()) {
1664 $itemsPerPage = DI::pConfig()->get(local_user(), 'system', 'itemspage_mobile_network',
1665 DI::config()->get('system', 'itemspage_network_mobile'));
1667 $itemsPerPage = DI::pConfig()->get(local_user(), 'system', 'itemspage_network',
1668 DI::config()->get('system', 'itemspage_network'));
1671 $pager = new Pager(DI::l10n(), DI::args()->getQueryString(), $itemsPerPage);
1673 $params = ['order' => ['received' => true],
1674 'limit' => [$pager->getStart(), $pager->getItemsPerPage()]];
1677 $r = Item::selectThreadForUser(local_user(), ['uri'], $condition, $params);
1679 $items = Item::inArray($r);
1681 $o = conversation($a, $items, 'contacts', $update, false, 'commented', local_user());
1683 $r = Item::selectForUser(local_user(), [], $condition, $params);
1685 $items = Item::inArray($r);
1687 $o = conversation($a, $items, 'contact-posts', false);
1691 $o .= $pager->renderMinimal(count($items));
1698 * Returns the account type name
1700 * The function can be called with either the user or the contact array
1702 * @param array $contact contact or user array
1705 public static function getAccountType(array $contact)
1707 // There are several fields that indicate that the contact or user is a forum
1708 // "page-flags" is a field in the user table,
1709 // "forum" and "prv" are used in the contact table. They stand for User::PAGE_FLAGS_COMMUNITY and User::PAGE_FLAGS_PRVGROUP.
1710 // "community" is used in the gcontact table and is true if the contact is User::PAGE_FLAGS_COMMUNITY or User::PAGE_FLAGS_PRVGROUP.
1711 if ((isset($contact['page-flags']) && (intval($contact['page-flags']) == User::PAGE_FLAGS_COMMUNITY))
1712 || (isset($contact['page-flags']) && (intval($contact['page-flags']) == User::PAGE_FLAGS_PRVGROUP))
1713 || (isset($contact['forum']) && intval($contact['forum']))
1714 || (isset($contact['prv']) && intval($contact['prv']))
1715 || (isset($contact['community']) && intval($contact['community']))
1717 $type = self::TYPE_COMMUNITY;
1719 $type = self::TYPE_PERSON;
1722 // The "contact-type" (contact table) and "account-type" (user table) are more general then the chaos from above.
1723 if (isset($contact["contact-type"])) {
1724 $type = $contact["contact-type"];
1727 if (isset($contact["account-type"])) {
1728 $type = $contact["account-type"];
1732 case self::TYPE_ORGANISATION:
1733 $account_type = DI::l10n()->t("Organisation");
1736 case self::TYPE_NEWS:
1737 $account_type = DI::l10n()->t('News');
1740 case self::TYPE_COMMUNITY:
1741 $account_type = DI::l10n()->t("Forum");
1749 return $account_type;
1757 * @throws \Exception
1759 public static function block($cid, $reason = null)
1761 $return = DBA::update('contact', ['blocked' => true, 'block_reason' => $reason], ['id' => $cid]);
1767 * Unblocks a contact
1771 * @throws \Exception
1773 public static function unblock($cid)
1775 $return = DBA::update('contact', ['blocked' => false, 'block_reason' => null], ['id' => $cid]);
1781 * Ensure that cached avatar exist
1783 * @param integer $cid
1785 public static function checkAvatarCache(int $cid)
1787 $contact = DBA::selectFirst('contact', ['url', 'avatar', 'photo', 'thumb', 'micro'], ['id' => $cid, 'uid' => 0, 'self' => false]);
1788 if (!DBA::isResult($contact)) {
1792 if (empty($contact['avatar']) || (!empty($contact['photo']) && !empty($contact['thumb']) && !empty($contact['micro']))) {
1796 Logger::info('Adding avatar cache', ['id' => $cid, 'contact' => $contact]);
1798 self::updateAvatar($cid, $contact['avatar'], true);
1802 * Return the photo path for a given contact array in the given size
1804 * @param array $contact contact array
1805 * @param string $field Fieldname of the photo in the contact array
1806 * @param string $default Default path when no picture had been found
1807 * @param string $size Size of the avatar picture
1808 * @param string $avatar Avatar path that is displayed when no photo had been found
1809 * @return string photo path
1811 private static function getAvatarPath(array $contact, string $field, string $default, string $size, string $avatar)
1813 if (!empty($contact)) {
1814 $contact = self::checkAvatarCacheByArray($contact);
1815 if (!empty($contact[$field])) {
1816 $avatar = $contact[$field];
1820 if (empty($avatar)) {
1824 if (Proxy::isLocalImage($avatar)) {
1827 return Proxy::proxifyUrl($avatar, false, $size);
1832 * Return the photo path for a given contact array
1834 * @param array $contact Contact array
1835 * @param string $avatar Avatar path that is displayed when no photo had been found
1836 * @return string photo path
1838 public static function getPhoto(array $contact, string $avatar = '')
1840 return self::getAvatarPath($contact, 'photo', DI::baseUrl() . '/images/person-300.jpg', Proxy::SIZE_SMALL, $avatar);
1844 * Return the photo path (thumb size) for a given contact array
1846 * @param array $contact Contact array
1847 * @param string $avatar Avatar path that is displayed when no photo had been found
1848 * @return string photo path
1850 public static function getThumb(array $contact, string $avatar = '')
1852 return self::getAvatarPath($contact, 'thumb', DI::baseUrl() . '/images/person-80.jpg', Proxy::SIZE_THUMB, $avatar);
1856 * Return the photo path (micro size) for a given contact array
1858 * @param array $contact Contact array
1859 * @param string $avatar Avatar path that is displayed when no photo had been found
1860 * @return string photo path
1862 public static function getMicro(array $contact, string $avatar = '')
1864 return self::getAvatarPath($contact, 'micro', DI::baseUrl() . '/images/person-48.jpg', Proxy::SIZE_MICRO, $avatar);
1868 * Check the given contact array for avatar cache fields
1870 * @param array $contact
1871 * @return array contact array with avatar cache fields
1873 private static function checkAvatarCacheByArray(array $contact)
1876 $contact_fields = [];
1877 $fields = ['photo', 'thumb', 'micro'];
1878 foreach ($fields as $field) {
1879 if (isset($contact[$field])) {
1880 $contact_fields[] = $field;
1882 if (isset($contact[$field]) && empty($contact[$field])) {
1891 if (!empty($contact['id']) && !empty($contact['avatar'])) {
1892 self::updateAvatar($contact['id'], $contact['avatar'], true);
1894 $new_contact = self::getById($contact['id'], $contact_fields);
1895 if (DBA::isResult($new_contact)) {
1896 // We only update the cache fields
1897 $contact = array_merge($contact, $new_contact);
1901 /// add the default avatars if the fields aren't filled
1902 if (isset($contact['photo']) && empty($contact['photo'])) {
1903 $contact['photo'] = DI::baseUrl() . '/images/person-300.jpg';
1905 if (isset($contact['thumb']) && empty($contact['thumb'])) {
1906 $contact['thumb'] = DI::baseUrl() . '/images/person-80.jpg';
1908 if (isset($contact['micro']) && empty($contact['micro'])) {
1909 $contact['micro'] = DI::baseUrl() . '/images/person-48.jpg';
1916 * Updates the avatar links in a contact only if needed
1918 * @param int $cid Contact id
1919 * @param string $avatar Link to avatar picture
1920 * @param bool $force force picture update
1923 * @throws HTTPException\InternalServerErrorException
1924 * @throws HTTPException\NotFoundException
1925 * @throws \ImagickException
1927 public static function updateAvatar(int $cid, string $avatar, bool $force = false)
1929 $contact = DBA::selectFirst('contact', ['uid', 'avatar', 'photo', 'thumb', 'micro', 'nurl'], ['id' => $cid, 'self' => false]);
1930 if (!DBA::isResult($contact)) {
1934 $uid = $contact['uid'];
1936 // Only update the cached photo links of public contacts when they already are cached
1937 if (($uid == 0) && !$force && empty($contact['thumb']) && empty($contact['micro'])) {
1938 if ($contact['avatar'] != $avatar) {
1939 DBA::update('contact', ['avatar' => $avatar], ['id' => $cid]);
1940 Logger::info('Only update the avatar', ['id' => $cid, 'avatar' => $avatar, 'contact' => $contact]);
1946 $contact['photo'] ?? '',
1947 $contact['thumb'] ?? '',
1948 $contact['micro'] ?? '',
1951 $update = ($contact['avatar'] != $avatar) || $force;
1954 foreach ($data as $image_uri) {
1955 $image_rid = Photo::ridFromURI($image_uri);
1956 if ($image_rid && !Photo::exists(['resource-id' => $image_rid, 'uid' => $uid])) {
1957 Logger::info('Regenerating avatar', ['contact uid' => $uid, 'cid' => $cid, 'missing photo' => $image_rid, 'avatar' => $contact['avatar']]);
1964 $photos = Photo::importProfilePhoto($avatar, $uid, $cid, true);
1966 $fields = ['avatar' => $avatar, 'photo' => $photos[0], 'thumb' => $photos[1], 'micro' => $photos[2], 'avatar-date' => DateTimeFormat::utcNow()];
1967 DBA::update('contact', $fields, ['id' => $cid]);
1968 } elseif (empty($contact['avatar'])) {
1969 // Ensure that the avatar field is set
1970 DBA::update('contact', ['avatar' => $avatar], ['id' => $cid]);
1971 Logger::info('Failed profile import', ['id' => $cid, 'force' => $force, 'avatar' => $avatar, 'contact' => $contact]);
1977 * Helper function for "updateFromProbe". Updates personal and public contact
1979 * @param integer $id contact id
1980 * @param integer $uid user id
1981 * @param string $url The profile URL of the contact
1982 * @param array $fields The fields that are updated
1984 * @throws \Exception
1986 private static function updateContact($id, $uid, $url, array $fields)
1988 if (!DBA::update('contact', $fields, ['id' => $id])) {
1989 Logger::info('Couldn\'t update contact.', ['id' => $id, 'fields' => $fields]);
1993 // Search for duplicated contacts and get rid of them
1994 if (self::removeDuplicates(Strings::normaliseLink($url), $uid) || ($uid != 0)) {
1998 // Update the corresponding gcontact entry
1999 GContact::updateFromPublicContactID($id);
2001 // Archive or unarchive the contact. We only need to do this for the public contact.
2002 // The archive/unarchive function will update the personal contacts by themselves.
2003 $contact = DBA::selectFirst('contact', [], ['id' => $id]);
2004 if (!DBA::isResult($contact)) {
2005 Logger::info('Couldn\'t select contact for archival.', ['id' => $id]);
2009 if (!empty($fields['success_update'])) {
2010 self::unmarkForArchival($contact);
2011 } elseif (!empty($fields['failure_update'])) {
2012 self::markForArchival($contact);
2015 $condition = ['self' => false, 'nurl' => Strings::normaliseLink($url), 'network' => Protocol::FEDERATED];
2017 // These contacts are sharing with us, we don't poll them.
2018 // This means that we don't set the update fields in "OnePoll.php".
2019 $condition['rel'] = self::SHARING;
2020 DBA::update('contact', $fields, $condition);
2022 unset($fields['last-update']);
2023 unset($fields['success_update']);
2024 unset($fields['failure_update']);
2026 if (empty($fields)) {
2030 // We are polling these contacts, so we mustn't set the update fields here.
2031 $condition['rel'] = [self::FOLLOWER, self::FRIEND];
2032 DBA::update('contact', $fields, $condition);
2036 * Remove duplicated contacts
2038 * @param string $nurl Normalised contact url
2039 * @param integer $uid User id
2041 * @throws \Exception
2043 public static function removeDuplicates(string $nurl, int $uid)
2045 $condition = ['nurl' => $nurl, 'uid' => $uid, 'deleted' => false, 'network' => Protocol::FEDERATED];
2046 $count = DBA::count('contact', $condition);
2051 $first_contact = DBA::selectFirst('contact', ['id', 'network'], $condition, ['order' => ['id']]);
2052 if (!DBA::isResult($first_contact)) {
2053 // Shouldn't happen - so we handle it
2057 $first = $first_contact['id'];
2058 Logger::info('Found duplicates', ['count' => $count, 'first' => $first, 'uid' => $uid, 'nurl' => $nurl]);
2059 if (($uid != 0 && ($first_contact['network'] == Protocol::DFRN))) {
2060 // Don't handle non public DFRN duplicates by now (legacy DFRN is very special because of the key handling)
2061 Logger::info('Not handling non public DFRN duplicate', ['uid' => $uid, 'nurl' => $nurl]);
2065 // Find all duplicates
2066 $condition = ["`nurl` = ? AND `uid` = ? AND `id` != ? AND NOT `self` AND NOT `deleted`", $nurl, $uid, $first];
2067 $duplicates = DBA::select('contact', ['id', 'network'], $condition);
2068 while ($duplicate = DBA::fetch($duplicates)) {
2069 if (!in_array($duplicate['network'], Protocol::FEDERATED)) {
2073 Worker::add(PRIORITY_HIGH, 'MergeContact', $first, $duplicate['id'], $uid);
2075 DBA::close($duplicates);
2076 Logger::info('Duplicates handled', ['uid' => $uid, 'nurl' => $nurl]);
2081 * @param integer $id contact id
2082 * @param string $network Optional network we are probing for
2083 * @param boolean $force Optional forcing of network probing (otherwise we use the cached data)
2085 * @throws HTTPException\InternalServerErrorException
2086 * @throws \ImagickException
2088 public static function updateFromProbe(int $id, string $network = '', bool $force = false)
2091 Warning: Never ever fetch the public key via Probe::uri and write it into the contacts.
2092 This will reliably kill your communication with old Friendica contacts.
2095 // These fields aren't updated by this routine:
2096 // 'xmpp', 'sensitive'
2098 $fields = ['uid', 'avatar', 'name', 'nick', 'location', 'keywords', 'about', 'subscribe',
2099 'unsearchable', 'url', 'addr', 'batch', 'notify', 'poll', 'request', 'confirm', 'poco',
2100 'network', 'alias', 'baseurl', 'gsid', 'forum', 'prv', 'contact-type', 'pubkey'];
2101 $contact = DBA::selectFirst('contact', $fields, ['id' => $id]);
2102 if (!DBA::isResult($contact)) {
2106 $uid = $contact['uid'];
2107 unset($contact['uid']);
2109 $pubkey = $contact['pubkey'];
2110 unset($contact['pubkey']);
2112 $contact['photo'] = $contact['avatar'];
2113 unset($contact['avatar']);
2115 $ret = Probe::uri($contact['url'], $network, $uid, !$force);
2117 $updated = DateTimeFormat::utcNow();
2119 // We must not try to update relay contacts via probe. They are no real contacts.
2120 // We check after the probing to be able to correct falsely detected contact types.
2121 if (($contact['contact-type'] == self::TYPE_RELAY) &&
2122 (!Strings::compareLink($ret['url'], $contact['url']) || in_array($ret['network'], [Protocol::FEED, Protocol::PHANTOM]))) {
2123 self::updateContact($id, $uid, $contact['url'], ['failed' => false, 'last-update' => $updated, 'success_update' => $updated]);
2124 Logger::info('Not updating relais', ['id' => $id, 'url' => $contact['url']]);
2128 // If Probe::uri fails the network code will be different ("feed" or "unkn")
2129 if (in_array($ret['network'], [Protocol::FEED, Protocol::PHANTOM]) && ($ret['network'] != $contact['network'])) {
2130 if ($force && ($uid == 0)) {
2131 self::updateContact($id, $uid, $ret['url'], ['failed' => true, 'last-update' => $updated, 'failure_update' => $updated]);
2136 if (ContactRelation::isDiscoverable($ret['url'])) {
2137 Worker::add(PRIORITY_LOW, 'ContactDiscovery', $ret['url']);
2140 if (isset($ret['hide']) && is_bool($ret['hide'])) {
2141 $ret['unsearchable'] = $ret['hide'];
2144 if (isset($ret['account-type']) && is_int($ret['account-type'])) {
2145 $ret['forum'] = false;
2146 $ret['prv'] = false;
2147 $ret['contact-type'] = $ret['account-type'];
2148 if ($ret['contact-type'] == User::ACCOUNT_TYPE_COMMUNITY) {
2149 $apcontact = APContact::getByURL($ret['url'], false);
2150 if (isset($apcontact['manually-approve'])) {
2151 $ret['forum'] = (bool)!$apcontact['manually-approve'];
2152 $ret['prv'] = (bool)!$ret['forum'];
2157 $new_pubkey = $ret['pubkey'];
2159 // Update the gcontact entry
2161 GContact::updateFromPublicContactID($id);
2166 // make sure to not overwrite existing values with blank entries except some technical fields
2167 $keep = ['batch', 'notify', 'poll', 'request', 'confirm', 'poco', 'baseurl'];
2168 foreach ($ret as $key => $val) {
2169 if (!array_key_exists($key, $contact)) {
2171 } elseif (($contact[$key] != '') && ($val === '') && !is_bool($ret[$key]) && !in_array($key, $keep)) {
2172 $ret[$key] = $contact[$key];
2173 } elseif ($ret[$key] != $contact[$key]) {
2178 if (!empty($ret['photo']) && ($ret['network'] != Protocol::FEED)) {
2179 self::updateAvatar($id, $ret['photo'], $update || $force);
2184 self::updateContact($id, $uid, $ret['url'], ['failed' => false, 'last-update' => $updated, 'success_update' => $updated]);
2187 // Update the public contact
2189 self::updateFromProbeByURL($ret['url']);
2195 $ret['nurl'] = Strings::normaliseLink($ret['url']);
2196 $ret['updated'] = $updated;
2198 // Only fill the pubkey if it had been empty before. We have to prevent identity theft.
2199 if (empty($pubkey) && !empty($new_pubkey)) {
2200 $ret['pubkey'] = $new_pubkey;
2203 if (($ret['addr'] != $contact['addr']) || (!empty($ret['alias']) && ($ret['alias'] != $contact['alias']))) {
2204 $ret['uri-date'] = DateTimeFormat::utcNow();
2207 if (($ret['name'] != $contact['name']) || ($ret['nick'] != $contact['nick'])) {
2208 $ret['name-date'] = $updated;
2211 if ($force && ($uid == 0)) {
2212 $ret['last-update'] = $updated;
2213 $ret['success_update'] = $updated;
2214 $ret['failed'] = false;
2217 unset($ret['photo']);
2219 self::updateContact($id, $uid, $ret['url'], $ret);
2224 public static function updateFromProbeByURL($url, $force = false)
2226 $id = self::getIdForURL($url);
2232 self::updateFromProbe($id, '', $force);
2238 * Detects if a given contact array belongs to a legacy DFRN connection
2240 * @param array $contact
2243 public static function isLegacyDFRNContact($contact)
2245 // Newer Friendica contacts are connected via AP, then these fields aren't set
2246 return !empty($contact['dfrn-id']) || !empty($contact['issued-id']);
2250 * Detects the communication protocol for a given contact url.
2251 * This is used to detect Friendica contacts that we can communicate via AP.
2253 * @param string $url contact url
2254 * @param string $network Network of that contact
2255 * @return string with protocol
2257 public static function getProtocol($url, $network)
2259 if ($network != Protocol::DFRN) {
2263 $apcontact = APContact::getByURL($url);
2264 if (!empty($apcontact) && !empty($apcontact['generator'])) {
2265 return Protocol::ACTIVITYPUB;
2272 * Takes a $uid and a url/handle and adds a new contact
2274 * Currently if the contact is DFRN, interactive needs to be true, to redirect to the
2275 * dfrn_request page.
2277 * Otherwise this can be used to bulk add StatusNet contacts, Twitter contacts, etc.
2280 * $return['success'] boolean true if successful
2281 * $return['message'] error text if success is false.
2283 * Takes a $uid and a url/handle and adds a new contact
2285 * @param array $user The user the contact should be created for
2286 * @param string $url The profile URL of the contact
2287 * @param bool $interactive
2288 * @param string $network
2290 * @throws HTTPException\InternalServerErrorException
2291 * @throws HTTPException\NotFoundException
2292 * @throws \ImagickException
2294 public static function createFromProbe(array $user, $url, $interactive = false, $network = '')
2296 $result = ['cid' => -1, 'success' => false, 'message' => ''];
2298 // remove ajax junk, e.g. Twitter
2299 $url = str_replace('/#!/', '/', $url);
2301 if (!Network::isUrlAllowed($url)) {
2302 $result['message'] = DI::l10n()->t('Disallowed profile URL.');
2306 if (Network::isUrlBlocked($url)) {
2307 $result['message'] = DI::l10n()->t('Blocked domain');
2312 $result['message'] = DI::l10n()->t('Connect URL missing.');
2316 $arr = ['url' => $url, 'contact' => []];
2318 Hook::callAll('follow', $arr);
2321 $result['message'] = DI::l10n()->t('The contact could not be added. Please check the relevant network credentials in your Settings -> Social Networks page.');
2325 if (!empty($arr['contact']['name'])) {
2326 $ret = $arr['contact'];
2328 $ret = Probe::uri($url, $network, $user['uid'], false);
2331 if (($network != '') && ($ret['network'] != $network)) {
2332 Logger::log('Expected network ' . $network . ' does not match actual network ' . $ret['network']);
2336 // check if we already have a contact
2337 // the poll url is more reliable than the profile url, as we may have
2338 // indirect links or webfinger links
2340 $condition = ['uid' => $user['uid'], 'poll' => [$ret['poll'], Strings::normaliseLink($ret['poll'])], 'network' => $ret['network'], 'pending' => false];
2341 $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
2342 if (!DBA::isResult($contact)) {
2343 $condition = ['uid' => $user['uid'], 'nurl' => Strings::normaliseLink($ret['url']), 'network' => $ret['network'], 'pending' => false];
2344 $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
2347 $protocol = self::getProtocol($ret['url'], $ret['network']);
2349 if (($protocol === Protocol::DFRN) && !DBA::isResult($contact)) {
2351 if (strlen(DI::baseUrl()->getUrlPath())) {
2352 $myaddr = bin2hex(DI::baseUrl() . '/profile/' . $user['nickname']);
2354 $myaddr = bin2hex($user['nickname'] . '@' . DI::baseUrl()->getHostname());
2357 DI::baseUrl()->redirect($ret['request'] . "&addr=$myaddr");
2361 } elseif (DI::config()->get('system', 'dfrn_only') && ($ret['network'] != Protocol::DFRN)) {
2362 $result['message'] = DI::l10n()->t('This site is not configured to allow communications with other networks.') . EOL;
2363 $result['message'] .= DI::l10n()->t('No compatible communication protocols or feeds were discovered.') . EOL;
2367 // This extra param just confuses things, remove it
2368 if ($protocol === Protocol::DIASPORA) {
2369 $ret['url'] = str_replace('?absolute=true', '', $ret['url']);
2372 // do we have enough information?
2373 if (empty($ret['name']) || empty($ret['poll']) || (empty($ret['url']) && empty($ret['addr']))) {
2374 $result['message'] .= DI::l10n()->t('The profile address specified does not provide adequate information.') . EOL;
2375 if (empty($ret['poll'])) {
2376 $result['message'] .= DI::l10n()->t('No compatible communication protocols or feeds were discovered.') . EOL;
2378 if (empty($ret['name'])) {
2379 $result['message'] .= DI::l10n()->t('An author or name was not found.') . EOL;
2381 if (empty($ret['url'])) {
2382 $result['message'] .= DI::l10n()->t('No browser URL could be matched to this address.') . EOL;
2384 if (strpos($ret['url'], '@') !== false) {
2385 $result['message'] .= DI::l10n()->t('Unable to match @-style Identity Address with a known protocol or email contact.') . EOL;
2386 $result['message'] .= DI::l10n()->t('Use mailto: in front of address to force email check.') . EOL;
2391 if ($protocol === Protocol::OSTATUS && DI::config()->get('system', 'ostatus_disabled')) {
2392 $result['message'] .= DI::l10n()->t('The profile address specified belongs to a network which has been disabled on this site.') . EOL;
2393 $ret['notify'] = '';
2396 if (!$ret['notify']) {
2397 $result['message'] .= DI::l10n()->t('Limited profile. This person will be unable to receive direct/personal notifications from you.') . EOL;
2400 $writeable = ((($protocol === Protocol::OSTATUS) && ($ret['notify'])) ? 1 : 0);
2402 $subhub = (($protocol === Protocol::OSTATUS) ? true : false);
2404 $hidden = (($protocol === Protocol::MAIL) ? 1 : 0);
2407 if ($protocol == Protocol::ACTIVITYPUB) {
2408 $apcontact = APContact::getByURL($ret['url'], false);
2409 if (isset($apcontact['manually-approve'])) {
2410 $pending = (bool)$apcontact['manually-approve'];
2414 if (in_array($protocol, [Protocol::MAIL, Protocol::DIASPORA, Protocol::ACTIVITYPUB])) {
2418 if (DBA::isResult($contact)) {
2420 $new_relation = (($contact['rel'] == self::FOLLOWER) ? self::FRIEND : self::SHARING);
2422 $fields = ['rel' => $new_relation, 'subhub' => $subhub, 'readonly' => false];
2423 DBA::update('contact', $fields, ['id' => $contact['id']]);
2425 $new_relation = (in_array($protocol, [Protocol::MAIL]) ? self::FRIEND : self::SHARING);
2427 // create contact record
2429 'uid' => $user['uid'],
2430 'created' => DateTimeFormat::utcNow(),
2431 'url' => $ret['url'],
2432 'nurl' => Strings::normaliseLink($ret['url']),
2433 'addr' => $ret['addr'],
2434 'alias' => $ret['alias'],
2435 'batch' => $ret['batch'],
2436 'notify' => $ret['notify'],
2437 'poll' => $ret['poll'],
2438 'poco' => $ret['poco'],
2439 'name' => $ret['name'],
2440 'nick' => $ret['nick'],
2441 'network' => $ret['network'],
2442 'baseurl' => $ret['baseurl'],
2443 'gsid' => $ret['gsid'] ?? null,
2444 'protocol' => $protocol,
2445 'pubkey' => $ret['pubkey'],
2446 'rel' => $new_relation,
2447 'priority'=> $ret['priority'],
2448 'writable'=> $writeable,
2449 'hidden' => $hidden,
2452 'pending' => $pending,
2457 $contact = DBA::selectFirst('contact', [], ['url' => $ret['url'], 'network' => $ret['network'], 'uid' => $user['uid']]);
2458 if (!DBA::isResult($contact)) {
2459 $result['message'] .= DI::l10n()->t('Unable to retrieve contact information.') . EOL;
2463 $contact_id = $contact['id'];
2464 $result['cid'] = $contact_id;
2466 Group::addMember(User::getDefaultGroup($user['uid'], $contact["network"]), $contact_id);
2468 // Update the avatar
2469 self::updateAvatar($contact_id, $ret['photo']);
2471 // pull feed and consume it, which should subscribe to the hub.
2473 Worker::add(PRIORITY_HIGH, "OnePoll", $contact_id, "force");
2475 $owner = User::getOwnerDataById($user['uid']);
2477 if (DBA::isResult($owner)) {
2478 if (in_array($protocol, [Protocol::OSTATUS, Protocol::DFRN])) {
2479 // create a follow slap
2481 $item['verb'] = Activity::FOLLOW;
2482 $item['gravity'] = GRAVITY_ACTIVITY;
2483 $item['follow'] = $contact["url"];
2485 $item['title'] = '';
2487 $item['uri-id'] = 0;
2488 $item['attach'] = '';
2490 $slap = OStatus::salmon($item, $owner);
2492 if (!empty($contact['notify'])) {
2493 Salmon::slapper($owner, $contact['notify'], $slap);
2495 } elseif ($protocol == Protocol::DIASPORA) {
2496 $ret = Diaspora::sendShare($owner, $contact);
2497 Logger::log('share returns: ' . $ret);
2498 } elseif ($protocol == Protocol::ACTIVITYPUB) {
2499 $activity_id = ActivityPub\Transmitter::activityIDFromContact($contact_id);
2500 if (empty($activity_id)) {
2501 // This really should never happen
2505 $ret = ActivityPub\Transmitter::sendActivity('Follow', $contact['url'], $user['uid'], $activity_id);
2506 Logger::log('Follow returns: ' . $ret);
2510 $result['success'] = true;
2515 * Updated contact's SSL policy
2517 * @param array $contact Contact array
2518 * @param string $new_policy New policy, valid: self,full
2520 * @return array Contact array with updated values
2521 * @throws \Exception
2523 public static function updateSslPolicy(array $contact, $new_policy)
2525 $ssl_changed = false;
2526 if ((intval($new_policy) == BaseURL::SSL_POLICY_SELFSIGN || $new_policy === 'self') && strstr($contact['url'], 'https:')) {
2527 $ssl_changed = true;
2528 $contact['url'] = str_replace('https:', 'http:', $contact['url']);
2529 $contact['request'] = str_replace('https:', 'http:', $contact['request']);
2530 $contact['notify'] = str_replace('https:', 'http:', $contact['notify']);
2531 $contact['poll'] = str_replace('https:', 'http:', $contact['poll']);
2532 $contact['confirm'] = str_replace('https:', 'http:', $contact['confirm']);
2533 $contact['poco'] = str_replace('https:', 'http:', $contact['poco']);
2536 if ((intval($new_policy) == BaseURL::SSL_POLICY_FULL || $new_policy === 'full') && strstr($contact['url'], 'http:')) {
2537 $ssl_changed = true;
2538 $contact['url'] = str_replace('http:', 'https:', $contact['url']);
2539 $contact['request'] = str_replace('http:', 'https:', $contact['request']);
2540 $contact['notify'] = str_replace('http:', 'https:', $contact['notify']);
2541 $contact['poll'] = str_replace('http:', 'https:', $contact['poll']);
2542 $contact['confirm'] = str_replace('http:', 'https:', $contact['confirm']);
2543 $contact['poco'] = str_replace('http:', 'https:', $contact['poco']);
2547 $fields = ['url' => $contact['url'], 'request' => $contact['request'],
2548 'notify' => $contact['notify'], 'poll' => $contact['poll'],
2549 'confirm' => $contact['confirm'], 'poco' => $contact['poco']];
2550 DBA::update('contact', $fields, ['id' => $contact['id']]);
2557 * @param array $importer Owner (local user) data
2558 * @param array $contact Existing owner-specific contact data we want to expand the relationship with. Optional.
2559 * @param array $datarray An item-like array with at least the 'author-id' and 'author-url' keys for the contact. Mandatory.
2560 * @param bool $sharing True: Contact is now sharing with Owner; False: Contact is now following Owner (default)
2561 * @param string $note Introduction additional message
2562 * @return bool|null True: follow request is accepted; False: relationship is rejected; Null: relationship is pending
2563 * @throws HTTPException\InternalServerErrorException
2564 * @throws \ImagickException
2566 public static function addRelationship(array $importer, array $contact, array $datarray, $sharing = false, $note = '')
2568 // Should always be set
2569 if (empty($datarray['author-id'])) {
2573 $fields = ['url', 'name', 'nick', 'avatar', 'photo', 'network', 'blocked'];
2574 $pub_contact = DBA::selectFirst('contact', $fields, ['id' => $datarray['author-id']]);
2575 if (!DBA::isResult($pub_contact)) {
2576 // Should never happen
2580 // Contact is blocked at node-level
2581 if (self::isBlocked($datarray['author-id'])) {
2585 $url = ($datarray['author-link'] ?? '') ?: $pub_contact['url'];
2586 $name = $pub_contact['name'];
2587 $photo = ($pub_contact['avatar'] ?? '') ?: $pub_contact["photo"];
2588 $nick = $pub_contact['nick'];
2589 $network = $pub_contact['network'];
2591 // Ensure that we don't create a new contact when there already is one
2592 $cid = self::getIdForURL($url, $importer['uid']);
2594 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
2597 if (!empty($contact)) {
2598 if (!empty($contact['pending'])) {
2599 Logger::info('Pending contact request already exists.', ['url' => $url, 'uid' => $importer['uid']]);
2603 // Contact is blocked at user-level
2604 if (!empty($contact['id']) && !empty($importer['id']) &&
2605 self::isBlockedByUser($contact['id'], $importer['id'])) {
2609 // Make sure that the existing contact isn't archived
2610 self::unmarkForArchival($contact);
2612 if (($contact['rel'] == self::SHARING)
2613 || ($sharing && $contact['rel'] == self::FOLLOWER)) {
2614 DBA::update('contact', ['rel' => self::FRIEND, 'writable' => true, 'pending' => false],
2615 ['id' => $contact['id'], 'uid' => $importer['uid']]);
2618 // Ensure to always have the correct network type, independent from the connection request method
2619 self::updateFromProbe($contact['id'], '', true);
2623 // send email notification to owner?
2624 if (DBA::exists('contact', ['nurl' => Strings::normaliseLink($url), 'uid' => $importer['uid'], 'pending' => true])) {
2625 Logger::log('ignoring duplicated connection request from pending contact ' . $url);
2629 // create contact record
2630 DBA::insert('contact', [
2631 'uid' => $importer['uid'],
2632 'created' => DateTimeFormat::utcNow(),
2634 'nurl' => Strings::normaliseLink($url),
2637 'network' => $network,
2638 'rel' => self::FOLLOWER,
2645 $contact_id = DBA::lastInsertId();
2647 // Ensure to always have the correct network type, independent from the connection request method
2648 self::updateFromProbe($contact_id, '', true);
2650 self::updateAvatar($contact_id, $photo, true);
2652 $contact_record = DBA::selectFirst('contact', ['id', 'network', 'name', 'url', 'photo'], ['id' => $contact_id]);
2654 /// @TODO Encapsulate this into a function/method
2655 $fields = ['uid', 'username', 'email', 'page-flags', 'notify-flags', 'language'];
2656 $user = DBA::selectFirst('user', $fields, ['uid' => $importer['uid']]);
2657 if (DBA::isResult($user) && !in_array($user['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_FREELOVE, User::PAGE_FLAGS_COMMUNITY])) {
2658 // create notification
2659 $hash = Strings::getRandomHex();
2661 if (is_array($contact_record)) {
2662 DBA::insert('intro', ['uid' => $importer['uid'], 'contact-id' => $contact_record['id'],
2663 'blocked' => false, 'knowyou' => false, 'note' => $note,
2664 'hash' => $hash, 'datetime' => DateTimeFormat::utcNow()]);
2667 Group::addMember(User::getDefaultGroup($importer['uid'], $contact_record["network"]), $contact_record['id']);
2669 if (($user['notify-flags'] & Type::INTRO) &&
2670 in_array($user['page-flags'], [User::PAGE_FLAGS_NORMAL])) {
2673 'type' => Type::INTRO,
2674 'notify_flags' => $user['notify-flags'],
2675 'language' => $user['language'],
2676 'to_name' => $user['username'],
2677 'to_email' => $user['email'],
2678 'uid' => $user['uid'],
2679 'link' => DI::baseUrl() . '/notifications/intros',
2680 'source_name' => ((strlen(stripslashes($contact_record['name']))) ? stripslashes($contact_record['name']) : DI::l10n()->t('[Name Withheld]')),
2681 'source_link' => $contact_record['url'],
2682 'source_photo' => $contact_record['photo'],
2683 'verb' => ($sharing ? Activity::FRIEND : Activity::FOLLOW),
2687 } elseif (DBA::isResult($user) && in_array($user['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_FREELOVE, User::PAGE_FLAGS_COMMUNITY])) {
2688 if (($user['page-flags'] == User::PAGE_FLAGS_FREELOVE) && ($network != Protocol::DIASPORA)) {
2689 self::createFromProbe($importer, $url, false, $network);
2692 $condition = ['uid' => $importer['uid'], 'url' => $url, 'pending' => true];
2693 $fields = ['pending' => false];
2694 if ($user['page-flags'] == User::PAGE_FLAGS_FREELOVE) {
2695 $fields['rel'] = Contact::FRIEND;
2698 DBA::update('contact', $fields, $condition);
2707 public static function removeFollower($importer, $contact, array $datarray = [], $item = "")
2709 if (($contact['rel'] == self::FRIEND) || ($contact['rel'] == self::SHARING)) {
2710 DBA::update('contact', ['rel' => self::SHARING], ['id' => $contact['id']]);
2712 Contact::remove($contact['id']);
2716 public static function removeSharer($importer, $contact, array $datarray = [], $item = "")
2718 if (($contact['rel'] == self::FRIEND) || ($contact['rel'] == self::FOLLOWER)) {
2719 DBA::update('contact', ['rel' => self::FOLLOWER], ['id' => $contact['id']]);
2721 Contact::remove($contact['id']);
2726 * Create a birthday event.
2728 * Update the year and the birthday.
2730 public static function updateBirthdays()
2734 AND `bd` > "0001-01-01"
2735 AND SUBSTRING(`bd`, 1, 4) != `bdyear`
2736 AND (`contact`.`rel` = ? OR `contact`.`rel` = ?)
2737 AND NOT `contact`.`pending`
2738 AND NOT `contact`.`hidden`
2739 AND NOT `contact`.`blocked`
2740 AND NOT `contact`.`archive`
2741 AND NOT `contact`.`deleted`',
2746 $contacts = DBA::select('contact', ['id', 'uid', 'name', 'url', 'bd'], $condition);
2748 while ($contact = DBA::fetch($contacts)) {
2749 Logger::log('update_contact_birthday: ' . $contact['bd']);
2751 $nextbd = DateTimeFormat::utcNow('Y') . substr($contact['bd'], 4);
2753 if (Event::createBirthday($contact, $nextbd)) {
2757 ['bdyear' => substr($nextbd, 0, 4), 'bd' => $nextbd],
2758 ['id' => $contact['id']]
2762 DBA::close($contacts);
2766 * Remove the unavailable contact ids from the provided list
2768 * @param array $contact_ids Contact id list
2770 * @throws \Exception
2772 public static function pruneUnavailable(array $contact_ids)
2774 if (empty($contact_ids)) {
2778 $contacts = Contact::selectToArray(['id'], [
2779 'id' => $contact_ids,
2785 return array_column($contacts, 'id');
2789 * Returns a magic link to authenticate remote visitors
2791 * @todo check if the return is either a fully qualified URL or a relative path to Friendica basedir
2793 * @param string $contact_url The address of the target contact profile
2794 * @param string $url An url that we will be redirected to after the authentication
2796 * @return string with "redir" link
2797 * @throws HTTPException\InternalServerErrorException
2798 * @throws \ImagickException
2800 public static function magicLink($contact_url, $url = '')
2802 if (!Session::isAuthenticated()) {
2803 return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
2806 $data = self::getProbeDataFromDatabase($contact_url);
2808 return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
2811 // Prevents endless loop in case only a non-public contact exists for the contact URL
2812 unset($data['uid']);
2814 return self::magicLinkByContact($data, $url ?: $contact_url);
2818 * Returns a magic link to authenticate remote visitors
2820 * @param integer $cid The contact id of the target contact profile
2821 * @param string $url An url that we will be redirected to after the authentication
2823 * @return string with "redir" link
2824 * @throws HTTPException\InternalServerErrorException
2825 * @throws \ImagickException
2827 public static function magicLinkbyId($cid, $url = '')
2829 $contact = DBA::selectFirst('contact', ['id', 'network', 'url', 'uid'], ['id' => $cid]);
2831 return self::magicLinkByContact($contact, $url);
2835 * Returns a magic link to authenticate remote visitors
2837 * @param array $contact The contact array with "uid", "network" and "url"
2838 * @param string $url An url that we will be redirected to after the authentication
2840 * @return string with "redir" link
2841 * @throws HTTPException\InternalServerErrorException
2842 * @throws \ImagickException
2844 public static function magicLinkByContact($contact, $url = '')
2846 $destination = $url ?: $contact['url']; // Equivalent to ($url != '') ? $url : $contact['url'];
2848 if (!Session::isAuthenticated() || ($contact['network'] != Protocol::DFRN)) {
2849 return $destination;
2852 // Only redirections to the same host do make sense
2853 if (($url != '') && (parse_url($url, PHP_URL_HOST) != parse_url($contact['url'], PHP_URL_HOST))) {
2857 if (!empty($contact['uid'])) {
2858 return self::magicLink($contact['url'], $url);
2861 if (empty($contact['id'])) {
2862 return $destination;
2865 $redirect = 'redir/' . $contact['id'];
2867 if (($url != '') && !Strings::compareLink($contact['url'], $url)) {
2868 $redirect .= '?url=' . $url;
2875 * Remove a contact from all groups
2877 * @param integer $contact_id
2879 * @return boolean Success
2881 public static function removeFromGroups($contact_id)
2883 return DBA::delete('group_member', ['contact-id' => $contact_id]);
2887 * Is the contact a forum?
2889 * @param integer $contactid ID of the contact
2891 * @return boolean "true" if it is a forum
2893 public static function isForum($contactid)
2895 $fields = ['forum', 'prv'];
2896 $condition = ['id' => $contactid];
2897 $contact = DBA::selectFirst('contact', $fields, $condition);
2898 if (!DBA::isResult($contact)) {
2903 return ($contact['forum'] || $contact['prv']);
2907 * Can the remote contact receive private messages?
2909 * @param array $contact
2912 public static function canReceivePrivateMessages(array $contact)
2914 $protocol = $contact['network'] ?? $contact['protocol'] ?? Protocol::PHANTOM;
2915 $self = $contact['self'] ?? false;
2917 return in_array($protocol, [Protocol::DFRN, Protocol::DIASPORA, Protocol::ACTIVITYPUB]) && !$self;
2921 * Search contact table by nick or name
2923 * @param string $search Name or nick
2924 * @param string $mode Search mode (e.g. "community")
2926 * @return array with search results
2927 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2929 public static function searchByName($search, $mode = '')
2931 if (empty($search)) {
2935 // check supported networks
2936 if (DI::config()->get('system', 'diaspora_enabled')) {
2937 $diaspora = Protocol::DIASPORA;
2939 $diaspora = Protocol::DFRN;
2942 if (!DI::config()->get('system', 'ostatus_disabled')) {
2943 $ostatus = Protocol::OSTATUS;
2945 $ostatus = Protocol::DFRN;
2948 // check if we search only communities or every contact
2949 if ($mode === 'community') {
2950 $extra_sql = sprintf(' AND `contact-type` = %d', Contact::TYPE_COMMUNITY);
2957 $results = DBA::p("SELECT * FROM `contact`
2958 WHERE NOT `unsearchable` AND `network` IN (?, ?, ?, ?) AND
2959 NOT `failed` AND `uid` = ? AND
2960 (`addr` LIKE ? OR `name` LIKE ? OR `nick` LIKE ?) $extra_sql
2961 ORDER BY `nurl` DESC LIMIT 1000",
2962 Protocol::DFRN, Protocol::ACTIVITYPUB, $ostatus, $diaspora, 0, $search, $search, $search
2965 $contacts = DBA::toArray($results);
2970 * @param int $uid user
2971 * @param int $start optional, default 0
2972 * @param int $limit optional, default 80
2975 static public function getSuggestions(int $uid, int $start = 0, int $limit = 80)
2977 $cid = self::getPublicIdByUserId($uid);
2978 $totallimit = $start + $limit;
2981 Logger::info('Collecting suggestions', ['uid' => $uid, 'cid' => $cid, 'start' => $start, 'limit' => $limit]);
2983 $diaspora = DI::config()->get('system', 'diaspora_enabled') ? Protocol::DIASPORA : Protocol::ACTIVITYPUB;
2984 $ostatus = !DI::config()->get('system', 'ostatus_disabled') ? Protocol::OSTATUS : Protocol::ACTIVITYPUB;
2986 // The query returns contacts where contacts interacted with who the given user follows.
2987 // Contacts who already are in the user's contact table are ignored.
2988 $results = DBA::select('contact', [],
2989 ["`id` IN (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` IN
2990 (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` = ?)
2991 AND NOT `cid` IN (SELECT `id` FROM `contact` WHERE `uid` = ? AND `nurl` IN
2992 (SELECT `nurl` FROM `contact` WHERE `uid` = ? AND `rel` IN (?, ?))))
2993 AND NOT `hidden` AND `network` IN (?, ?, ?, ?)",
2994 $cid, 0, $uid, Contact::FRIEND, Contact::SHARING,
2995 Protocol::ACTIVITYPUB, Protocol::DFRN, $diaspora, $ostatus],
2996 ['order' => ['last-item' => true], 'limit' => $totallimit]
2999 while ($contact = DBA::fetch($results)) {
3000 $contacts[$contact['id']] = $contact;
3002 DBA::close($results);
3004 Logger::info('Contacts of contacts who are followed by the given user', ['uid' => $uid, 'cid' => $cid, 'count' => count($contacts)]);
3006 if (count($contacts) >= $totallimit) {
3007 return array_slice($contacts, $start, $limit);
3010 // The query returns contacts where contacts interacted with who also interacted with the given user.
3011 // Contacts who already are in the user's contact table are ignored.
3012 $results = DBA::select('contact', [],
3013 ["`id` IN (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` IN
3014 (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ?)
3015 AND NOT `cid` IN (SELECT `id` FROM `contact` WHERE `uid` = ? AND `nurl` IN
3016 (SELECT `nurl` FROM `contact` WHERE `uid` = ? AND `rel` IN (?, ?))))
3017 AND NOT `hidden` AND `network` IN (?, ?, ?, ?)",
3018 $cid, 0, $uid, Contact::FRIEND, Contact::SHARING,
3019 Protocol::ACTIVITYPUB, Protocol::DFRN, $diaspora, $ostatus],
3020 ['order' => ['last-item' => true], 'limit' => $totallimit]
3023 while ($contact = DBA::fetch($results)) {
3024 $contacts[$contact['id']] = $contact;
3026 DBA::close($results);
3028 Logger::info('Contacts of contacts who are following the given user', ['uid' => $uid, 'cid' => $cid, 'count' => count($contacts)]);
3030 if (count($contacts) >= $totallimit) {
3031 return array_slice($contacts, $start, $limit);
3034 // The query returns contacts that follow the given user but aren't followed by that user.
3035 $results = DBA::select('contact', [],
3036 ["`nurl` IN (SELECT `nurl` FROM `contact` WHERE `uid` = ? AND `rel` = ?)
3037 AND NOT `hidden` AND `uid` = ? AND `network` IN (?, ?, ?, ?)",
3038 $uid, Contact::FOLLOWER, 0,
3039 Protocol::ACTIVITYPUB, Protocol::DFRN, $diaspora, $ostatus],
3040 ['order' => ['last-item' => true], 'limit' => $totallimit]
3043 while ($contact = DBA::fetch($results)) {
3044 $contacts[$contact['id']] = $contact;
3046 DBA::close($results);
3048 Logger::info('Followers that are not followed by the given user', ['uid' => $uid, 'cid' => $cid, 'count' => count($contacts)]);
3050 if (count($contacts) >= $totallimit) {
3051 return array_slice($contacts, $start, $limit);
3054 // The query returns any contact that isn't followed by that user.
3055 $results = DBA::select('contact', [],
3056 ["NOT `nurl` IN (SELECT `nurl` FROM `contact` WHERE `uid` = ? AND `rel` IN (?, ?))
3057 AND NOT `hidden` AND `uid` = ? AND `network` IN (?, ?, ?, ?)",
3058 $uid, Contact::FRIEND, Contact::SHARING, 0,
3059 Protocol::ACTIVITYPUB, Protocol::DFRN, $diaspora, $ostatus],
3060 ['order' => ['last-item' => true], 'limit' => $totallimit]
3063 while ($contact = DBA::fetch($results)) {
3064 $contacts[$contact['id']] = $contact;
3066 DBA::close($results);
3068 Logger::info('Any contact', ['uid' => $uid, 'cid' => $cid, 'count' => count($contacts)]);
3070 return array_slice($contacts, $start, $limit);
3073 public static function getTemplateData(array $contact, int $id)
3076 'url' => self::magicLink($contact['url']),
3077 'itemurl' => $contact['addr'] ?: $contact['url'],
3078 'name' => $contact['name'],
3079 'thumb' => self::getThumb($contact),
3080 'img_hover' => $contact['url'],
3081 'details' => $contact['location'],
3082 'tags' => $contact['keywords'],
3083 'about' => $contact['about'],
3084 'account_type' => self::getAccountType($contact),
3085 'network' => ContactSelector::networkToName($contact['network'], $contact['url']),
3086 'photo_menu' => self::photoMenu($contact),