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)) {
84 if (!self::isDiscoverable($url, $contact)) {
88 $uid = User::getIdForURL($url);
90 Logger::info('Fetch the followers/followings locally', ['url' => $url]);
91 $followers = self::getContacts($uid, [Contact::FOLLOWER, Contact::FRIEND]);
92 $followings = self::getContacts($uid, [Contact::SHARING, Contact::FRIEND]);
93 } elseif (!Contact::isLocal($url)) {
94 Logger::info('Fetch the followers/followings by polling the endpoints', ['url' => $url]);
95 $apcontact = APContact::getByURL($url, false);
97 if (!empty($apcontact['followers']) && is_string($apcontact['followers'])) {
98 $followers = ActivityPub::fetchItems($apcontact['followers']);
103 if (!empty($apcontact['following']) && is_string($apcontact['following'])) {
104 $followings = ActivityPub::fetchItems($apcontact['following']);
109 Logger::notice('Contact seems to be local but could not be found here', ['url' => $url]);
114 if (empty($followers) && empty($followings)) {
115 DBA::update('contact', ['last-discovery' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
116 Logger::info('The contact does not offer discoverable data', ['id' => $contact['id'], 'url' => $url, 'network' => $contact['network']]);
120 $target = $contact['id'];
122 if (!empty($followers)) {
123 // Clear the follower list, since it will be recreated in the next step
124 DBA::update('contact-relation', ['follows' => false], ['cid' => $target]);
128 foreach (array_merge($followers, $followings) as $contact) {
129 if (is_string($contact)) {
130 $contacts[] = $contact;
131 } elseif (!empty($contact['url']) && is_string($contact['url'])) {
132 $contacts[] = $contact['url'];
135 $contacts = array_unique($contacts);
137 $follower_counter = 0;
138 $following_counter = 0;
140 Logger::info('Discover contacts', ['id' => $target, 'url' => $url, 'contacts' => count($contacts)]);
141 foreach ($contacts as $contact) {
142 $actor = Contact::getIdForURL($contact);
143 if (!empty($actor)) {
144 if (in_array($contact, $followers)) {
145 $fields = ['cid' => $target, 'relation-cid' => $actor, 'follows' => true, 'follow-updated' => DateTimeFormat::utcNow()];
146 DBA::insert('contact-relation', $fields, Database::INSERT_UPDATE);
150 if (in_array($contact, $followings)) {
151 $fields = ['cid' => $actor, 'relation-cid' => $target, 'follows' => true, 'follow-updated' => DateTimeFormat::utcNow()];
152 DBA::insert('contact-relation', $fields, Database::INSERT_UPDATE);
153 $following_counter++;
158 if (!empty($followers)) {
159 // Delete all followers that aren't followers anymore (and aren't interacting)
160 DBA::delete('contact-relation', ['cid' => $target, 'follows' => false, 'last-interaction' => DBA::NULL_DATETIME]);
163 DBA::update('contact', ['last-discovery' => DateTimeFormat::utcNow()], ['id' => $target]);
164 Logger::info('Contacts discovery finished', ['id' => $target, 'url' => $url, 'follower' => $follower_counter, 'following' => $following_counter]);
169 * Fetch contact url list from the given local user
171 * @param integer $uid
173 * @return array contact list
175 private static function getContacts(int $uid, array $rel)
178 $profile = Profile::getByUID($uid);
179 if (!empty($profile['hide-friends'])) {
183 $condition = ['rel' => $rel, 'uid' => $uid, 'self' => false, 'deleted' => false,
184 'hidden' => false, 'archive' => false, 'pending' => false];
185 $condition = DBA::mergeConditions($condition, ["`url` IN (SELECT `url` FROM `apcontact`)"]);
186 $contacts = DBA::select('contact', ['url'], $condition);
187 while ($contact = DBA::fetch($contacts)) {
188 $list[] = $contact['url'];
190 DBA::close($contacts);
196 * Tests if a given contact url is discoverable
198 * @param string $url Contact url
199 * @param array $contact Contact array
200 * @return boolean True if contact is discoverable
202 public static function isDiscoverable(string $url, array $contact = [])
204 $contact_discovery = DI::config()->get('system', 'contact_discovery');
206 if ($contact_discovery == self::DISCOVERY_NONE) {
210 if (empty($contact)) {
211 $contact = Contact::getByURL($url, false);
214 if (empty($contact)) {
218 if ($contact['last-discovery'] > DateTimeFormat::utc('now - 1 month')) {
219 Logger::info('No discovery - Last was less than a month ago.', ['id' => $contact['id'], 'url' => $url, 'discovery' => $contact['last-discovery']]);
223 if ($contact_discovery != self::DISCOVERY_ALL) {
224 $local = DBA::exists('contact', ["`nurl` = ? AND `uid` != ?", Strings::normaliseLink($url), 0]);
225 if (($contact_discovery == self::DISCOVERY_LOCAL) && !$local) {
226 Logger::info('No discovery - This contact is not followed/following locally.', ['id' => $contact['id'], 'url' => $url]);
230 if ($contact_discovery == self::DISCOVERY_INTERACTOR) {
231 $interactor = DBA::exists('contact-relation', ["`relation-cid` = ? AND `last-interaction` > ?", $contact['id'], DBA::NULL_DATETIME]);
232 if (!$local && !$interactor) {
233 Logger::info('No discovery - This contact is not interacting locally.', ['id' => $contact['id'], 'url' => $url]);
237 } elseif ($contact['created'] > DateTimeFormat::utc('now - 1 day')) {
238 // Newly created contacts are not discovered to avoid DDoS attacks
239 Logger::info('No discovery - Contact record is less than a day old.', ['id' => $contact['id'], 'url' => $url, 'discovery' => $contact['created']]);
243 if (!in_array($contact['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::OSTATUS])) {
244 $apcontact = APContact::getByURL($url, false);
245 if (empty($apcontact)) {
246 Logger::info('No discovery - The contact does not seem to speak ActivityPub.', ['id' => $contact['id'], 'url' => $url, 'network' => $contact['network']]);
255 * @param int $uid user
256 * @param int $start optional, default 0
257 * @param int $limit optional, default 80
260 static public function getSuggestions(int $uid, int $start = 0, int $limit = 80)
262 $cid = Contact::getPublicIdByUserId($uid);
263 $totallimit = $start + $limit;
266 Logger::info('Collecting suggestions', ['uid' => $uid, 'cid' => $cid, 'start' => $start, 'limit' => $limit]);
268 $diaspora = DI::config()->get('system', 'diaspora_enabled') ? Protocol::DIASPORA : Protocol::ACTIVITYPUB;
269 $ostatus = !DI::config()->get('system', 'ostatus_disabled') ? Protocol::OSTATUS : Protocol::ACTIVITYPUB;
271 // The query returns contacts where contacts interacted with whom the given user follows.
272 // Contacts who already are in the user's contact table are ignored.
273 $results = DBA::select('contact', [],
274 ["`id` IN (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` IN
275 (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` = ?)
276 AND NOT `cid` IN (SELECT `id` FROM `contact` WHERE `uid` = ? AND `nurl` IN
277 (SELECT `nurl` FROM `contact` WHERE `uid` = ? AND `rel` IN (?, ?))))
278 AND NOT `hidden` AND `network` IN (?, ?, ?, ?)",
279 $cid, 0, $uid, Contact::FRIEND, Contact::SHARING,
280 Protocol::ACTIVITYPUB, Protocol::DFRN, $diaspora, $ostatus],
281 ['order' => ['last-item' => true], 'limit' => $totallimit]
284 while ($contact = DBA::fetch($results)) {
285 $contacts[$contact['id']] = $contact;
287 DBA::close($results);
289 Logger::info('Contacts of contacts who are followed by the given user', ['uid' => $uid, 'cid' => $cid, 'count' => count($contacts)]);
291 if (count($contacts) >= $totallimit) {
292 return array_slice($contacts, $start, $limit);
295 // The query returns contacts where contacts interacted with whom also interacted with the given user.
296 // Contacts who already are in the user's contact table are ignored.
297 $results = DBA::select('contact', [],
298 ["`id` IN (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` IN
299 (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ?)
300 AND NOT `cid` IN (SELECT `id` FROM `contact` WHERE `uid` = ? AND `nurl` IN
301 (SELECT `nurl` FROM `contact` WHERE `uid` = ? AND `rel` IN (?, ?))))
302 AND NOT `hidden` AND `network` IN (?, ?, ?, ?)",
303 $cid, 0, $uid, Contact::FRIEND, Contact::SHARING,
304 Protocol::ACTIVITYPUB, Protocol::DFRN, $diaspora, $ostatus],
305 ['order' => ['last-item' => true], 'limit' => $totallimit]
308 while ($contact = DBA::fetch($results)) {
309 $contacts[$contact['id']] = $contact;
311 DBA::close($results);
313 Logger::info('Contacts of contacts who are following the given user', ['uid' => $uid, 'cid' => $cid, 'count' => count($contacts)]);
315 if (count($contacts) >= $totallimit) {
316 return array_slice($contacts, $start, $limit);
319 // The query returns contacts that follow the given user but aren't followed by that user.
320 $results = DBA::select('contact', [],
321 ["`nurl` IN (SELECT `nurl` FROM `contact` WHERE `uid` = ? AND `rel` = ?)
322 AND NOT `hidden` AND `uid` = ? AND `network` IN (?, ?, ?, ?)",
323 $uid, Contact::FOLLOWER, 0,
324 Protocol::ACTIVITYPUB, Protocol::DFRN, $diaspora, $ostatus],
325 ['order' => ['last-item' => true], 'limit' => $totallimit]
328 while ($contact = DBA::fetch($results)) {
329 $contacts[$contact['id']] = $contact;
331 DBA::close($results);
333 Logger::info('Followers that are not followed by the given user', ['uid' => $uid, 'cid' => $cid, 'count' => count($contacts)]);
335 if (count($contacts) >= $totallimit) {
336 return array_slice($contacts, $start, $limit);
339 // The query returns any contact that isn't followed by that user.
340 $results = DBA::select('contact', [],
341 ["NOT `nurl` IN (SELECT `nurl` FROM `contact` WHERE `uid` = ? AND `rel` IN (?, ?))
342 AND NOT `hidden` AND `uid` = ? AND `network` IN (?, ?, ?, ?)",
343 $uid, Contact::FRIEND, Contact::SHARING, 0,
344 Protocol::ACTIVITYPUB, Protocol::DFRN, $diaspora, $ostatus],
345 ['order' => ['last-item' => true], 'limit' => $totallimit]
348 while ($contact = DBA::fetch($results)) {
349 $contacts[$contact['id']] = $contact;
351 DBA::close($results);
353 Logger::info('Any contact', ['uid' => $uid, 'cid' => $cid, 'count' => count($contacts)]);
355 return array_slice($contacts, $start, $limit);
359 * Counts all the known follows of the provided public contact
361 * @param int $cid Public contact id
362 * @param array $condition Additional condition on the contact table
366 public static function countFollows(int $cid, array $condition = [])
368 $condition = DBA::mergeConditions($condition,
369 ['`id` IN (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ? AND `follows`)',
373 return DI::dba()->count('contact', $condition);
377 * Returns a paginated list of contacts that are followed the provided public contact.
379 * @param int $cid Public contact id
380 * @param array $condition Additional condition on the contact table
383 * @param bool $shuffle
387 public static function listFollows(int $cid, array $condition = [], int $count = 30, int $offset = 0, bool $shuffle = false)
389 $condition = DBA::mergeConditions($condition,
390 ['`id` IN (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ? AND `follows`)',
394 return DI::dba()->selectToArray('contact', [], $condition,
395 ['limit' => [$offset, $count], 'order' => [$shuffle ? 'RAND()' : 'name']]
400 * Counts all the known followers of the provided public contact
402 * @param int $cid Public contact id
403 * @param array $condition Additional condition on the contact table
407 public static function countFollowers(int $cid, array $condition = [])
409 $condition = DBA::mergeConditions($condition,
410 ['`id` IN (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` = ? AND `follows`)',
414 return DI::dba()->count('contact', $condition);
418 * Returns a paginated list of contacts that follow the provided public contact.
420 * @param int $cid Public contact id
421 * @param array $condition Additional condition on the contact table
424 * @param bool $shuffle
428 public static function listFollowers(int $cid, array $condition = [], int $count = 30, int $offset = 0, bool $shuffle = false)
430 $condition = DBA::mergeConditions($condition,
431 ['`id` IN (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` = ? AND `follows`)', $cid]
434 return DI::dba()->selectToArray('contact', [], $condition,
435 ['limit' => [$offset, $count], 'order' => [$shuffle ? 'RAND()' : 'name']]
440 * Counts the number of contacts that are known mutuals with the provided public contact.
442 * @param int $cid Public contact id
443 * @param array $condition Additional condition array on the contact table
447 public static function countMutuals(int $cid, array $condition = [])
449 $condition = DBA::mergeConditions($condition,
450 ['`id` IN (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ? AND `follows`)
451 AND `id` IN (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` = ? AND `follows`)',
455 return DI::dba()->count('contact', $condition);
459 * Returns a paginated list of contacts that are known mutuals with the provided public contact.
461 * @param int $cid Public contact id
462 * @param array $condition Additional condition on the contact table
465 * @param bool $shuffle
469 public static function listMutuals(int $cid, array $condition = [], int $count = 30, int $offset = 0, bool $shuffle = false)
471 $condition = DBA::mergeConditions($condition,
472 ['`id` IN (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ? AND `follows`)
473 AND `id` IN (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` = ? AND `follows`)',
477 return DI::dba()->selectToArray('contact', [], $condition,
478 ['limit' => [$offset, $count], 'order' => [$shuffle ? 'RAND()' : 'name']]
484 * Counts the number of contacts with any relationship with the provided public contact.
486 * @param int $cid Public contact id
487 * @param array $condition Additional condition array on the contact table
491 public static function countAll(int $cid, array $condition = [])
493 $condition = DBA::mergeConditions($condition,
494 ['(`id` IN (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ? AND `follows`)
495 OR `id` IN (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` = ? AND `follows`))',
499 return DI::dba()->count('contact', $condition);
503 * Returns a paginated list of contacts with any relationship with the provided public contact.
505 * @param int $cid Public contact id
506 * @param array $condition Additional condition on the contact table
509 * @param bool $shuffle
513 public static function listAll(int $cid, array $condition = [], int $count = 30, int $offset = 0, bool $shuffle = false)
515 $condition = DBA::mergeConditions($condition,
516 ['(`id` IN (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ? AND `follows`)
517 OR `id` IN (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` = ? AND `follows`))',
521 return DI::dba()->selectToArray('contact', [], $condition,
522 ['limit' => [$offset, $count], 'order' => [$shuffle ? 'RAND()' : 'name']]
527 * Counts the number of contacts that both provided public contacts have interacted with at least once.
528 * Interactions include follows and likes and comments on public posts.
530 * @param int $sourceId Public contact id
531 * @param int $targetId Public contact id
532 * @param array $condition Additional condition array on the contact table
536 public static function countCommon(int $sourceId, int $targetId, array $condition = [])
538 $condition = DBA::mergeConditions($condition,
539 ['`id` IN (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ?)
540 AND `id` IN (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ?)',
541 $sourceId, $targetId]
544 return DI::dba()->count('contact', $condition);
548 * Returns a paginated list of contacts that both provided public contacts have interacted with at least once.
549 * Interactions include follows and likes and comments on public posts.
551 * @param int $sourceId Public contact id
552 * @param int $targetId Public contact id
553 * @param array $condition Additional condition on the contact table
556 * @param bool $shuffle
560 public static function listCommon(int $sourceId, int $targetId, array $condition = [], int $count = 30, int $offset = 0, bool $shuffle = false)
562 $condition = DBA::mergeConditions($condition,
563 ["`id` IN (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ?)
564 AND `id` IN (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ?)",
565 $sourceId, $targetId]
568 return DI::dba()->selectToArray('contact', [], $condition,
569 ['limit' => [$offset, $count], 'order' => [$shuffle ? 'RAND()' : 'name']]
574 * Counts the number of contacts that are followed by both provided public contacts.
576 * @param int $sourceId Public contact id
577 * @param int $targetId Public contact id
578 * @param array $condition Additional condition array on the contact table
582 public static function countCommonFollows(int $sourceId, int $targetId, array $condition = [])
584 $condition = DBA::mergeConditions($condition,
585 ['`id` IN (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ? AND `follows`)
586 AND `id` IN (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ? AND `follows`)',
587 $sourceId, $targetId]
590 return DI::dba()->count('contact', $condition);
594 * Returns a paginated list of contacts that are followed by both provided public contacts.
596 * @param int $sourceId Public contact id
597 * @param int $targetId Public contact id
598 * @param array $condition Additional condition array on the contact table
601 * @param bool $shuffle
605 public static function listCommonFollows(int $sourceId, int $targetId, array $condition = [], int $count = 30, int $offset = 0, bool $shuffle = false)
607 $condition = DBA::mergeConditions($condition,
608 ["`id` IN (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ? AND `follows`)
609 AND `id` IN (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ? AND `follows`)",
610 $sourceId, $targetId]
613 return DI::dba()->selectToArray('contact', [], $condition,
614 ['limit' => [$offset, $count], 'order' => [$shuffle ? 'RAND()' : 'name']]
619 * Counts the number of contacts that follow both provided public contacts.
621 * @param int $sourceId Public contact id
622 * @param int $targetId Public contact id
623 * @param array $condition Additional condition on the contact table
627 public static function countCommonFollowers(int $sourceId, int $targetId, array $condition = [])
629 $condition = DBA::mergeConditions($condition,
630 ["`id` IN (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` = ? AND `follows`)
631 AND `id` IN (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` = ? AND `follows`)",
632 $sourceId, $targetId]
635 return DI::dba()->count('contact', $condition);
639 * Returns a paginated list of contacts that follow both provided public contacts.
641 * @param int $sourceId Public contact id
642 * @param int $targetId Public contact id
643 * @param array $condition Additional condition on the contact table
646 * @param bool $shuffle
650 public static function listCommonFollowers(int $sourceId, int $targetId, array $condition = [], int $count = 30, int $offset = 0, bool $shuffle = false)
652 $condition = DBA::mergeConditions($condition,
653 ["`id` IN (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` = ? AND `follows`)
654 AND `id` IN (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` = ? AND `follows`)",
655 $sourceId, $targetId]
658 return DI::dba()->selectToArray('contact', [], $condition,
659 ['limit' => [$offset, $count], 'order' => [$shuffle ? 'RAND()' : 'name']]