3 * @copyright Copyright (C) 2010-2021, the Friendica project
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\Contact;
25 use Friendica\Core\Logger;
26 use Friendica\Core\Protocol;
27 use Friendica\Database\Database;
28 use Friendica\Database\DBA;
30 use Friendica\Model\APContact;
31 use Friendica\Model\Contact;
32 use Friendica\Model\Profile;
33 use Friendica\Model\User;
34 use Friendica\Protocol\ActivityPub;
35 use Friendica\Util\DateTimeFormat;
36 use Friendica\Util\Strings;
39 * This class provides relationship information based on the `contact-relation` table.
40 * This table is directional (cid = source, relation-cid = target), references public contacts (with uid=0) and records both
41 * follows and the last interaction (likes/comments) on public posts.
46 * No discovery of followers/followings
48 const DISCOVERY_NONE = 0;
50 * Discover followers/followings of local contacts
52 const DISCOVERY_LOCAL = 1;
54 * Discover followers/followings of local contacts and contacts that visibly interacted on the system
56 const DISCOVERY_INTERACTOR = 2;
58 * Discover followers/followings of all contacts
60 const DISCOVERY_ALL = 3;
62 public static function store(int $target, int $actor, string $interaction_date)
64 if ($actor == $target) {
68 DBA::insert('contact-relation', ['last-interaction' => $interaction_date, 'cid' => $target, 'relation-cid' => $actor], Database::INSERT_UPDATE);
72 * Fetches the followers of a given profile and adds them
74 * @param string $url URL of a profile
77 public static function discoverByUrl(string $url)
79 $contact = Contact::getByURL($url);
80 if (empty($contact)) {
81 Logger::info('Contact not found', ['url' => $url]);
85 if (!self::isDiscoverable($url, $contact)) {
86 Logger::info('Contact is not discoverable', ['url' => $url]);
90 $uid = User::getIdForURL($url);
92 Logger::info('Fetch the followers/followings locally', ['url' => $url]);
93 $followers = self::getContacts($uid, [Contact::FOLLOWER, Contact::FRIEND]);
94 $followings = self::getContacts($uid, [Contact::SHARING, Contact::FRIEND]);
95 } elseif (!Contact::isLocal($url)) {
96 Logger::info('Fetch the followers/followings by polling the endpoints', ['url' => $url]);
97 $apcontact = APContact::getByURL($url, false);
99 if (!empty($apcontact['followers']) && is_string($apcontact['followers'])) {
100 $followers = ActivityPub::fetchItems($apcontact['followers']);
105 if (!empty($apcontact['following']) && is_string($apcontact['following'])) {
106 $followings = ActivityPub::fetchItems($apcontact['following']);
111 Logger::notice('Contact seems to be local but could not be found here', ['url' => $url]);
116 if (empty($followers) && empty($followings)) {
117 DBA::update('contact', ['last-discovery' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
118 Logger::info('The contact does not offer discoverable data', ['id' => $contact['id'], 'url' => $url, 'network' => $contact['network']]);
122 $target = $contact['id'];
124 if (!empty($followers)) {
125 // Clear the follower list, since it will be recreated in the next step
126 DBA::update('contact-relation', ['follows' => false], ['cid' => $target]);
130 foreach (array_merge($followers, $followings) as $contact) {
131 if (is_string($contact)) {
132 $contacts[] = $contact;
133 } elseif (!empty($contact['url']) && is_string($contact['url'])) {
134 $contacts[] = $contact['url'];
137 $contacts = array_unique($contacts);
139 $follower_counter = 0;
140 $following_counter = 0;
142 Logger::info('Discover contacts', ['id' => $target, 'url' => $url, 'contacts' => count($contacts)]);
143 foreach ($contacts as $contact) {
144 $actor = Contact::getIdForURL($contact);
145 if (!empty($actor)) {
146 if (in_array($contact, $followers)) {
147 $fields = ['cid' => $target, 'relation-cid' => $actor, 'follows' => true, 'follow-updated' => DateTimeFormat::utcNow()];
148 DBA::insert('contact-relation', $fields, Database::INSERT_UPDATE);
152 if (in_array($contact, $followings)) {
153 $fields = ['cid' => $actor, 'relation-cid' => $target, 'follows' => true, 'follow-updated' => DateTimeFormat::utcNow()];
154 DBA::insert('contact-relation', $fields, Database::INSERT_UPDATE);
155 $following_counter++;
160 if (!empty($followers)) {
161 // Delete all followers that aren't followers anymore (and aren't interacting)
162 DBA::delete('contact-relation', ['cid' => $target, 'follows' => false, 'last-interaction' => DBA::NULL_DATETIME]);
165 DBA::update('contact', ['last-discovery' => DateTimeFormat::utcNow()], ['id' => $target]);
166 Logger::info('Contacts discovery finished', ['id' => $target, 'url' => $url, 'follower' => $follower_counter, 'following' => $following_counter]);
171 * Fetch contact url list from the given local user
173 * @param integer $uid
175 * @return array contact list
177 private static function getContacts(int $uid, array $rel)
180 $profile = Profile::getByUID($uid);
181 if (!empty($profile['hide-friends'])) {
185 $condition = ['rel' => $rel, 'uid' => $uid, 'self' => false, 'deleted' => false,
186 'hidden' => false, 'archive' => false, 'pending' => false];
187 $condition = DBA::mergeConditions($condition, ["`url` IN (SELECT `url` FROM `apcontact`)"]);
188 $contacts = DBA::select('contact', ['url'], $condition);
189 while ($contact = DBA::fetch($contacts)) {
190 $list[] = $contact['url'];
192 DBA::close($contacts);
198 * Tests if a given contact url is discoverable
200 * @param string $url Contact url
201 * @param array $contact Contact array
202 * @return boolean True if contact is discoverable
204 public static function isDiscoverable(string $url, array $contact = [])
206 $contact_discovery = DI::config()->get('system', 'contact_discovery');
208 if ($contact_discovery == self::DISCOVERY_NONE) {
212 if (empty($contact)) {
213 $contact = Contact::getByURL($url, false);
216 if (empty($contact)) {
220 if ($contact['last-discovery'] > DateTimeFormat::utc('now - 1 month')) {
221 Logger::info('No discovery - Last was less than a month ago.', ['id' => $contact['id'], 'url' => $url, 'discovery' => $contact['last-discovery']]);
225 if ($contact_discovery != self::DISCOVERY_ALL) {
226 $local = DBA::exists('contact', ["`nurl` = ? AND `uid` != ?", Strings::normaliseLink($url), 0]);
227 if (($contact_discovery == self::DISCOVERY_LOCAL) && !$local) {
228 Logger::info('No discovery - This contact is not followed/following locally.', ['id' => $contact['id'], 'url' => $url]);
232 if ($contact_discovery == self::DISCOVERY_INTERACTOR) {
233 $interactor = DBA::exists('contact-relation', ["`relation-cid` = ? AND `last-interaction` > ?", $contact['id'], DBA::NULL_DATETIME]);
234 if (!$local && !$interactor) {
235 Logger::info('No discovery - This contact is not interacting locally.', ['id' => $contact['id'], 'url' => $url]);
239 } elseif ($contact['created'] > DateTimeFormat::utc('now - 1 day')) {
240 // Newly created contacts are not discovered to avoid DDoS attacks
241 Logger::info('No discovery - Contact record is less than a day old.', ['id' => $contact['id'], 'url' => $url, 'discovery' => $contact['created']]);
245 if (!in_array($contact['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::OSTATUS])) {
246 $apcontact = APContact::getByURL($url, false);
247 if (empty($apcontact)) {
248 Logger::info('No discovery - The contact does not seem to speak ActivityPub.', ['id' => $contact['id'], 'url' => $url, 'network' => $contact['network']]);
257 * @param int $uid user
258 * @param int $start optional, default 0
259 * @param int $limit optional, default 80
262 static public function getSuggestions(int $uid, int $start = 0, int $limit = 80)
264 $cid = Contact::getPublicIdByUserId($uid);
265 $totallimit = $start + $limit;
268 Logger::info('Collecting suggestions', ['uid' => $uid, 'cid' => $cid, 'start' => $start, 'limit' => $limit]);
270 $diaspora = DI::config()->get('system', 'diaspora_enabled') ? Protocol::DIASPORA : Protocol::ACTIVITYPUB;
271 $ostatus = !DI::config()->get('system', 'ostatus_disabled') ? Protocol::OSTATUS : Protocol::ACTIVITYPUB;
273 // The query returns contacts where contacts interacted with whom the given user follows.
274 // Contacts who already are in the user's contact table are ignored.
275 $results = DBA::select('contact', [],
276 ["`id` IN (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` IN
277 (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` = ?)
278 AND NOT `cid` IN (SELECT `id` FROM `contact` WHERE `uid` = ? AND `nurl` IN
279 (SELECT `nurl` FROM `contact` WHERE `uid` = ? AND `rel` IN (?, ?))))
280 AND NOT `hidden` AND `network` IN (?, ?, ?, ?)",
281 $cid, 0, $uid, Contact::FRIEND, Contact::SHARING,
282 Protocol::ACTIVITYPUB, Protocol::DFRN, $diaspora, $ostatus],
283 ['order' => ['last-item' => true], 'limit' => $totallimit]
286 while ($contact = DBA::fetch($results)) {
287 $contacts[$contact['id']] = $contact;
289 DBA::close($results);
291 Logger::info('Contacts of contacts who are followed by the given user', ['uid' => $uid, 'cid' => $cid, 'count' => count($contacts)]);
293 if (count($contacts) >= $totallimit) {
294 return array_slice($contacts, $start, $limit);
297 // The query returns contacts where contacts interacted with whom also interacted with the given user.
298 // Contacts who already are in the user's contact table are ignored.
299 $results = DBA::select('contact', [],
300 ["`id` IN (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` IN
301 (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ?)
302 AND NOT `cid` IN (SELECT `id` FROM `contact` WHERE `uid` = ? AND `nurl` IN
303 (SELECT `nurl` FROM `contact` WHERE `uid` = ? AND `rel` IN (?, ?))))
304 AND NOT `hidden` AND `network` IN (?, ?, ?, ?)",
305 $cid, 0, $uid, Contact::FRIEND, Contact::SHARING,
306 Protocol::ACTIVITYPUB, Protocol::DFRN, $diaspora, $ostatus],
307 ['order' => ['last-item' => true], 'limit' => $totallimit]
310 while ($contact = DBA::fetch($results)) {
311 $contacts[$contact['id']] = $contact;
313 DBA::close($results);
315 Logger::info('Contacts of contacts who are following the given user', ['uid' => $uid, 'cid' => $cid, 'count' => count($contacts)]);
317 if (count($contacts) >= $totallimit) {
318 return array_slice($contacts, $start, $limit);
321 // The query returns contacts that follow the given user but aren't followed by that user.
322 $results = DBA::select('contact', [],
323 ["`nurl` IN (SELECT `nurl` FROM `contact` WHERE `uid` = ? AND `rel` = ?)
324 AND NOT `hidden` AND `uid` = ? AND `network` IN (?, ?, ?, ?)",
325 $uid, Contact::FOLLOWER, 0,
326 Protocol::ACTIVITYPUB, Protocol::DFRN, $diaspora, $ostatus],
327 ['order' => ['last-item' => true], 'limit' => $totallimit]
330 while ($contact = DBA::fetch($results)) {
331 $contacts[$contact['id']] = $contact;
333 DBA::close($results);
335 Logger::info('Followers that are not followed by the given user', ['uid' => $uid, 'cid' => $cid, 'count' => count($contacts)]);
337 if (count($contacts) >= $totallimit) {
338 return array_slice($contacts, $start, $limit);
341 // The query returns any contact that isn't followed by that user.
342 $results = DBA::select('contact', [],
343 ["NOT `nurl` IN (SELECT `nurl` FROM `contact` WHERE `uid` = ? AND `rel` IN (?, ?))
344 AND NOT `hidden` AND `uid` = ? AND `network` IN (?, ?, ?, ?)",
345 $uid, Contact::FRIEND, Contact::SHARING, 0,
346 Protocol::ACTIVITYPUB, Protocol::DFRN, $diaspora, $ostatus],
347 ['order' => ['last-item' => true], 'limit' => $totallimit]
350 while ($contact = DBA::fetch($results)) {
351 $contacts[$contact['id']] = $contact;
353 DBA::close($results);
355 Logger::info('Any contact', ['uid' => $uid, 'cid' => $cid, 'count' => count($contacts)]);
357 return array_slice($contacts, $start, $limit);
361 * Counts all the known follows of the provided public contact
363 * @param int $cid Public contact id
364 * @param array $condition Additional condition on the contact table
368 public static function countFollows(int $cid, array $condition = [])
370 $condition = DBA::mergeConditions($condition,
371 ['`id` IN (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ? AND `follows`)',
375 return DI::dba()->count('contact', $condition);
379 * Returns a paginated list of contacts that are followed the provided public contact.
381 * @param int $cid Public contact id
382 * @param array $condition Additional condition on the contact table
385 * @param bool $shuffle
389 public static function listFollows(int $cid, array $condition = [], int $count = 30, int $offset = 0, bool $shuffle = false)
391 $condition = DBA::mergeConditions($condition,
392 ['`id` IN (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ? AND `follows`)',
396 return DI::dba()->selectToArray('contact', [], $condition,
397 ['limit' => [$offset, $count], 'order' => [$shuffle ? 'RAND()' : 'name']]
402 * Counts all the known followers of the provided public contact
404 * @param int $cid Public contact id
405 * @param array $condition Additional condition on the contact table
409 public static function countFollowers(int $cid, array $condition = [])
411 $condition = DBA::mergeConditions($condition,
412 ['`id` IN (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` = ? AND `follows`)',
416 return DI::dba()->count('contact', $condition);
420 * Returns a paginated list of contacts that follow the provided public contact.
422 * @param int $cid Public contact id
423 * @param array $condition Additional condition on the contact table
426 * @param bool $shuffle
430 public static function listFollowers(int $cid, array $condition = [], int $count = 30, int $offset = 0, bool $shuffle = false)
432 $condition = DBA::mergeConditions($condition,
433 ['`id` IN (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` = ? AND `follows`)', $cid]
436 return DI::dba()->selectToArray('contact', [], $condition,
437 ['limit' => [$offset, $count], 'order' => [$shuffle ? 'RAND()' : 'name']]
442 * Counts the number of contacts that are known mutuals with the provided public contact.
444 * @param int $cid Public contact id
445 * @param array $condition Additional condition array on the contact table
449 public static function countMutuals(int $cid, array $condition = [])
451 $condition = DBA::mergeConditions($condition,
452 ['`id` IN (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ? AND `follows`)
453 AND `id` IN (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` = ? AND `follows`)',
457 return DI::dba()->count('contact', $condition);
461 * Returns a paginated list of contacts that are known mutuals with the provided public contact.
463 * @param int $cid Public contact id
464 * @param array $condition Additional condition on the contact table
467 * @param bool $shuffle
471 public static function listMutuals(int $cid, array $condition = [], int $count = 30, int $offset = 0, bool $shuffle = false)
473 $condition = DBA::mergeConditions($condition,
474 ['`id` IN (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ? AND `follows`)
475 AND `id` IN (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` = ? AND `follows`)',
479 return DI::dba()->selectToArray('contact', [], $condition,
480 ['limit' => [$offset, $count], 'order' => [$shuffle ? 'RAND()' : 'name']]
486 * Counts the number of contacts with any relationship with the provided public contact.
488 * @param int $cid Public contact id
489 * @param array $condition Additional condition array on the contact table
493 public static function countAll(int $cid, array $condition = [])
495 $condition = DBA::mergeConditions($condition,
496 ['(`id` IN (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ? AND `follows`)
497 OR `id` IN (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` = ? AND `follows`))',
501 return DI::dba()->count('contact', $condition);
505 * Returns a paginated list of contacts with any relationship with the provided public contact.
507 * @param int $cid Public contact id
508 * @param array $condition Additional condition on the contact table
511 * @param bool $shuffle
515 public static function listAll(int $cid, array $condition = [], int $count = 30, int $offset = 0, bool $shuffle = false)
517 $condition = DBA::mergeConditions($condition,
518 ['(`id` IN (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ? AND `follows`)
519 OR `id` IN (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` = ? AND `follows`))',
523 return DI::dba()->selectToArray('contact', [], $condition,
524 ['limit' => [$offset, $count], 'order' => [$shuffle ? 'RAND()' : 'name']]
529 * Counts the number of contacts that both provided public contacts have interacted with at least once.
530 * Interactions include follows and likes and comments on public posts.
532 * @param int $sourceId Public contact id
533 * @param int $targetId Public contact id
534 * @param array $condition Additional condition array on the contact table
538 public static function countCommon(int $sourceId, int $targetId, array $condition = [])
540 $condition = DBA::mergeConditions($condition,
541 ['`id` IN (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ?)
542 AND `id` IN (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ?)',
543 $sourceId, $targetId]
546 return DI::dba()->count('contact', $condition);
550 * Returns a paginated list of contacts that both provided public contacts have interacted with at least once.
551 * Interactions include follows and likes and comments on public posts.
553 * @param int $sourceId Public contact id
554 * @param int $targetId Public contact id
555 * @param array $condition Additional condition on the contact table
558 * @param bool $shuffle
562 public static function listCommon(int $sourceId, int $targetId, array $condition = [], int $count = 30, int $offset = 0, bool $shuffle = false)
564 $condition = DBA::mergeConditions($condition,
565 ["`id` IN (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ?)
566 AND `id` IN (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ?)",
567 $sourceId, $targetId]
570 return DI::dba()->selectToArray('contact', [], $condition,
571 ['limit' => [$offset, $count], 'order' => [$shuffle ? 'RAND()' : 'name']]
576 * Counts the number of contacts that are followed by both provided public contacts.
578 * @param int $sourceId Public contact id
579 * @param int $targetId Public contact id
580 * @param array $condition Additional condition array on the contact table
584 public static function countCommonFollows(int $sourceId, int $targetId, array $condition = [])
586 $condition = DBA::mergeConditions($condition,
587 ['`id` IN (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ? AND `follows`)
588 AND `id` IN (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ? AND `follows`)',
589 $sourceId, $targetId]
592 return DI::dba()->count('contact', $condition);
596 * Returns a paginated list of contacts that are followed by both provided public contacts.
598 * @param int $sourceId Public contact id
599 * @param int $targetId Public contact id
600 * @param array $condition Additional condition array on the contact table
603 * @param bool $shuffle
607 public static function listCommonFollows(int $sourceId, int $targetId, array $condition = [], int $count = 30, int $offset = 0, bool $shuffle = false)
609 $condition = DBA::mergeConditions($condition,
610 ["`id` IN (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ? AND `follows`)
611 AND `id` IN (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ? AND `follows`)",
612 $sourceId, $targetId]
615 return DI::dba()->selectToArray('contact', [], $condition,
616 ['limit' => [$offset, $count], 'order' => [$shuffle ? 'RAND()' : 'name']]
621 * Counts the number of contacts that follow both provided public contacts.
623 * @param int $sourceId Public contact id
624 * @param int $targetId Public contact id
625 * @param array $condition Additional condition on the contact table
629 public static function countCommonFollowers(int $sourceId, int $targetId, array $condition = [])
631 $condition = DBA::mergeConditions($condition,
632 ["`id` IN (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` = ? AND `follows`)
633 AND `id` IN (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` = ? AND `follows`)",
634 $sourceId, $targetId]
637 return DI::dba()->count('contact', $condition);
641 * Returns a paginated list of contacts that follow both provided public contacts.
643 * @param int $sourceId Public contact id
644 * @param int $targetId Public contact id
645 * @param array $condition Additional condition on the contact table
648 * @param bool $shuffle
652 public static function listCommonFollowers(int $sourceId, int $targetId, array $condition = [], int $count = 30, int $offset = 0, bool $shuffle = false)
654 $condition = DBA::mergeConditions($condition,
655 ["`id` IN (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` = ? AND `follows`)
656 AND `id` IN (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` = ? AND `follows`)",
657 $sourceId, $targetId]
660 return DI::dba()->selectToArray('contact', [], $condition,
661 ['limit' => [$offset, $count], 'order' => [$shuffle ? 'RAND()' : 'name']]