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\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 // Fetch the followers/followings locally
91 $followers = self::getContacts($uid, [Contact::FOLLOWER, Contact::FRIEND]);
92 $followings = self::getContacts($uid, [Contact::SHARING, Contact::FRIEND]);
94 $apcontact = APContact::getByURL($url, false);
96 if (!empty($apcontact['followers']) && is_string($apcontact['followers'])) {
97 $followers = ActivityPub::fetchItems($apcontact['followers']);
102 if (!empty($apcontact['following']) && is_string($apcontact['following'])) {
103 $followings = ActivityPub::fetchItems($apcontact['following']);
109 if (empty($followers) && empty($followings)) {
110 DBA::update('contact', ['last-discovery' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
111 Logger::info('The contact does not offer discoverable data', ['id' => $contact['id'], 'url' => $url, 'network' => $contact['network']]);
115 $target = $contact['id'];
117 if (!empty($followers)) {
118 // Clear the follower list, since it will be recreated in the next step
119 DBA::update('contact-relation', ['follows' => false], ['cid' => $target]);
123 foreach (array_merge($followers, $followings) as $contact) {
124 if (is_string($contact)) {
125 $contacts[] = $contact;
126 } elseif (!empty($contact['url']) && is_string($contact['url'])) {
127 $contacts[] = $contact['url'];
130 $contacts = array_unique($contacts);
132 $follower_counter = 0;
133 $following_counter = 0;
135 Logger::info('Discover contacts', ['id' => $target, 'url' => $url, 'contacts' => count($contacts)]);
136 foreach ($contacts as $contact) {
137 $actor = Contact::getIdForURL($contact);
138 if (!empty($actor)) {
139 if (in_array($contact, $followers)) {
140 $condition = ['cid' => $target, 'relation-cid' => $actor];
141 DBA::insert('contact-relation', $condition, Database::INSERT_IGNORE);
142 DBA::update('contact-relation', ['follows' => true, 'follow-updated' => DateTimeFormat::utcNow()], $condition);
146 if (in_array($contact, $followings)) {
147 $condition = ['cid' => $actor, 'relation-cid' => $target];
148 DBA::insert('contact-relation', $condition, Database::INSERT_IGNORE);
149 DBA::update('contact-relation', ['follows' => true, 'follow-updated' => DateTimeFormat::utcNow()], $condition);
150 $following_counter++;
155 if (!empty($followers)) {
156 // Delete all followers that aren't followers anymore (and aren't interacting)
157 DBA::delete('contact-relation', ['cid' => $target, 'follows' => false, 'last-interaction' => DBA::NULL_DATETIME]);
160 DBA::update('contact', ['last-discovery' => DateTimeFormat::utcNow()], ['id' => $target]);
161 Logger::info('Contacts discovery finished', ['id' => $target, 'url' => $url, 'follower' => $follower_counter, 'following' => $following_counter]);
166 * Fetch contact url list from the given local user
168 * @param integer $uid
170 * @return array contact list
172 private static function getContacts(int $uid, array $rel)
175 $profile = Profile::getByUID($uid);
176 if (!empty($profile['hide-friends'])) {
180 $condition = ['rel' => $rel, 'uid' => $uid, 'self' => false, 'deleted' => false,
181 'hidden' => false, 'archive' => false, 'pending' => false];
182 $condition = DBA::mergeConditions($condition, ["`url` IN (SELECT `url` FROM `apcontact`)"]);
183 $contacts = DBA::select('contact', ['url'], $condition);
184 while ($contact = DBA::fetch($contacts)) {
185 $list[] = $contact['url'];
187 DBA::close($contacts);
193 * Tests if a given contact url is discoverable
195 * @param string $url Contact url
196 * @param array $contact Contact array
197 * @return boolean True if contact is discoverable
199 public static function isDiscoverable(string $url, array $contact = [])
201 $contact_discovery = DI::config()->get('system', 'contact_discovery');
203 if ($contact_discovery == self::DISCOVERY_NONE) {
207 if (empty($contact)) {
208 $contact = Contact::getByURL($url, false);
211 if (empty($contact)) {
215 if ($contact['last-discovery'] > DateTimeFormat::utc('now - 1 month')) {
216 Logger::info('No discovery - Last was less than a month ago.', ['id' => $contact['id'], 'url' => $url, 'discovery' => $contact['last-discovery']]);
220 if ($contact_discovery != self::DISCOVERY_ALL) {
221 $local = DBA::exists('contact', ["`nurl` = ? AND `uid` != ?", Strings::normaliseLink($url), 0]);
222 if (($contact_discovery == self::DISCOVERY_LOCAL) && !$local) {
223 Logger::info('No discovery - This contact is not followed/following locally.', ['id' => $contact['id'], 'url' => $url]);
227 if ($contact_discovery == self::DISCOVERY_INTERACTOR) {
228 $interactor = DBA::exists('contact-relation', ["`relation-cid` = ? AND `last-interaction` > ?", $contact['id'], DBA::NULL_DATETIME]);
229 if (!$local && !$interactor) {
230 Logger::info('No discovery - This contact is not interacting locally.', ['id' => $contact['id'], 'url' => $url]);
234 } elseif ($contact['created'] > DateTimeFormat::utc('now - 1 day')) {
235 // Newly created contacts are not discovered to avoid DDoS attacks
236 Logger::info('No discovery - Contact record is less than a day old.', ['id' => $contact['id'], 'url' => $url, 'discovery' => $contact['created']]);
240 if (!in_array($contact['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::OSTATUS])) {
241 $apcontact = APContact::getByURL($url, false);
242 if (empty($apcontact)) {
243 Logger::info('No discovery - The contact does not seem to speak ActivityPub.', ['id' => $contact['id'], 'url' => $url, 'network' => $contact['network']]);
252 * @param int $uid user
253 * @param int $start optional, default 0
254 * @param int $limit optional, default 80
257 static public function getSuggestions(int $uid, int $start = 0, int $limit = 80)
259 $cid = Contact::getPublicIdByUserId($uid);
260 $totallimit = $start + $limit;
263 Logger::info('Collecting suggestions', ['uid' => $uid, 'cid' => $cid, 'start' => $start, 'limit' => $limit]);
265 $diaspora = DI::config()->get('system', 'diaspora_enabled') ? Protocol::DIASPORA : Protocol::ACTIVITYPUB;
266 $ostatus = !DI::config()->get('system', 'ostatus_disabled') ? Protocol::OSTATUS : Protocol::ACTIVITYPUB;
268 // The query returns contacts where contacts interacted with whom the given user follows.
269 // Contacts who already are in the user's contact table are ignored.
270 $results = DBA::select('contact', [],
271 ["`id` IN (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` IN
272 (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` = ?)
273 AND NOT `cid` IN (SELECT `id` FROM `contact` WHERE `uid` = ? AND `nurl` IN
274 (SELECT `nurl` FROM `contact` WHERE `uid` = ? AND `rel` IN (?, ?))))
275 AND NOT `hidden` AND `network` IN (?, ?, ?, ?)",
276 $cid, 0, $uid, Contact::FRIEND, Contact::SHARING,
277 Protocol::ACTIVITYPUB, Protocol::DFRN, $diaspora, $ostatus],
278 ['order' => ['last-item' => true], 'limit' => $totallimit]
281 while ($contact = DBA::fetch($results)) {
282 $contacts[$contact['id']] = $contact;
284 DBA::close($results);
286 Logger::info('Contacts of contacts who are followed by the given user', ['uid' => $uid, 'cid' => $cid, 'count' => count($contacts)]);
288 if (count($contacts) >= $totallimit) {
289 return array_slice($contacts, $start, $limit);
292 // The query returns contacts where contacts interacted with whom also interacted with the given user.
293 // Contacts who already are in the user's contact table are ignored.
294 $results = DBA::select('contact', [],
295 ["`id` IN (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` IN
296 (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ?)
297 AND NOT `cid` IN (SELECT `id` FROM `contact` WHERE `uid` = ? AND `nurl` IN
298 (SELECT `nurl` FROM `contact` WHERE `uid` = ? AND `rel` IN (?, ?))))
299 AND NOT `hidden` AND `network` IN (?, ?, ?, ?)",
300 $cid, 0, $uid, Contact::FRIEND, Contact::SHARING,
301 Protocol::ACTIVITYPUB, Protocol::DFRN, $diaspora, $ostatus],
302 ['order' => ['last-item' => true], 'limit' => $totallimit]
305 while ($contact = DBA::fetch($results)) {
306 $contacts[$contact['id']] = $contact;
308 DBA::close($results);
310 Logger::info('Contacts of contacts who are following the given user', ['uid' => $uid, 'cid' => $cid, 'count' => count($contacts)]);
312 if (count($contacts) >= $totallimit) {
313 return array_slice($contacts, $start, $limit);
316 // The query returns contacts that follow the given user but aren't followed by that user.
317 $results = DBA::select('contact', [],
318 ["`nurl` IN (SELECT `nurl` FROM `contact` WHERE `uid` = ? AND `rel` = ?)
319 AND NOT `hidden` AND `uid` = ? AND `network` IN (?, ?, ?, ?)",
320 $uid, Contact::FOLLOWER, 0,
321 Protocol::ACTIVITYPUB, Protocol::DFRN, $diaspora, $ostatus],
322 ['order' => ['last-item' => true], 'limit' => $totallimit]
325 while ($contact = DBA::fetch($results)) {
326 $contacts[$contact['id']] = $contact;
328 DBA::close($results);
330 Logger::info('Followers that are not followed by the given user', ['uid' => $uid, 'cid' => $cid, 'count' => count($contacts)]);
332 if (count($contacts) >= $totallimit) {
333 return array_slice($contacts, $start, $limit);
336 // The query returns any contact that isn't followed by that user.
337 $results = DBA::select('contact', [],
338 ["NOT `nurl` IN (SELECT `nurl` FROM `contact` WHERE `uid` = ? AND `rel` IN (?, ?))
339 AND NOT `hidden` AND `uid` = ? AND `network` IN (?, ?, ?, ?)",
340 $uid, Contact::FRIEND, Contact::SHARING, 0,
341 Protocol::ACTIVITYPUB, Protocol::DFRN, $diaspora, $ostatus],
342 ['order' => ['last-item' => true], 'limit' => $totallimit]
345 while ($contact = DBA::fetch($results)) {
346 $contacts[$contact['id']] = $contact;
348 DBA::close($results);
350 Logger::info('Any contact', ['uid' => $uid, 'cid' => $cid, 'count' => count($contacts)]);
352 return array_slice($contacts, $start, $limit);
356 * Counts all the known follows of the provided public contact
358 * @param int $cid Public contact id
359 * @param array $condition Additional condition on the contact table
363 public static function countFollows(int $cid, array $condition = [])
365 $condition = DBA::mergeConditions($condition,
366 ['`id` IN (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ? AND `follows`)',
370 return DI::dba()->count('contact', $condition);
374 * Returns a paginated list of contacts that are followed the provided public contact.
376 * @param int $cid Public contact id
377 * @param array $condition Additional condition on the contact table
380 * @param bool $shuffle
384 public static function listFollows(int $cid, array $condition = [], int $count = 30, int $offset = 0, bool $shuffle = false)
386 $condition = DBA::mergeConditions($condition,
387 ['`id` IN (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ? AND `follows`)',
391 return DI::dba()->selectToArray('contact', [], $condition,
392 ['limit' => [$offset, $count], 'order' => [$shuffle ? 'RAND()' : 'name']]
397 * Counts all the known followers of the provided public contact
399 * @param int $cid Public contact id
400 * @param array $condition Additional condition on the contact table
404 public static function countFollowers(int $cid, array $condition = [])
406 $condition = DBA::mergeConditions($condition,
407 ['`id` IN (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` = ? AND `follows`)',
411 return DI::dba()->count('contact', $condition);
415 * Returns a paginated list of contacts that follow the provided public contact.
417 * @param int $cid Public contact id
418 * @param array $condition Additional condition on the contact table
421 * @param bool $shuffle
425 public static function listFollowers(int $cid, array $condition = [], int $count = 30, int $offset = 0, bool $shuffle = false)
427 $condition = DBA::mergeConditions($condition,
428 ['`id` IN (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` = ? AND `follows`)', $cid]
431 return DI::dba()->selectToArray('contact', [], $condition,
432 ['limit' => [$offset, $count], 'order' => [$shuffle ? 'RAND()' : 'name']]
437 * Counts the number of contacts that are known mutuals with the provided public contact.
439 * @param int $cid Public contact id
440 * @param array $condition Additional condition array on the contact table
444 public static function countMutuals(int $cid, array $condition = [])
446 $condition = DBA::mergeConditions($condition,
447 ['`id` IN (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ? AND `follows`)
448 AND `id` IN (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` = ? AND `follows`)',
452 return DI::dba()->count('contact', $condition);
456 * Returns a paginated list of contacts that are known mutuals with the provided public contact.
458 * @param int $cid Public contact id
459 * @param array $condition Additional condition on the contact table
462 * @param bool $shuffle
466 public static function listMutuals(int $cid, array $condition = [], int $count = 30, int $offset = 0, bool $shuffle = false)
468 $condition = DBA::mergeConditions($condition,
469 ['`id` IN (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ? AND `follows`)
470 AND `id` IN (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` = ? AND `follows`)',
474 return DI::dba()->selectToArray('contact', [], $condition,
475 ['limit' => [$offset, $count], 'order' => [$shuffle ? 'RAND()' : 'name']]
481 * Counts the number of contacts with any relationship with the provided public contact.
483 * @param int $cid Public contact id
484 * @param array $condition Additional condition array on the contact table
488 public static function countAll(int $cid, array $condition = [])
490 $condition = DBA::mergeConditions($condition,
491 ['(`id` IN (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ? AND `follows`)
492 OR `id` IN (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` = ? AND `follows`))',
496 return DI::dba()->count('contact', $condition);
500 * Returns a paginated list of contacts with any relationship with the provided public contact.
502 * @param int $cid Public contact id
503 * @param array $condition Additional condition on the contact table
506 * @param bool $shuffle
510 public static function listAll(int $cid, array $condition = [], int $count = 30, int $offset = 0, bool $shuffle = false)
512 $condition = DBA::mergeConditions($condition,
513 ['(`id` IN (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ? AND `follows`)
514 OR `id` IN (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` = ? AND `follows`))',
518 return DI::dba()->selectToArray('contact', [], $condition,
519 ['limit' => [$offset, $count], 'order' => [$shuffle ? 'RAND()' : 'name']]
524 * Counts the number of contacts that both provided public contacts have interacted with at least once.
525 * Interactions include follows and likes and comments on public posts.
527 * @param int $sourceId Public contact id
528 * @param int $targetId Public contact id
529 * @param array $condition Additional condition array on the contact table
533 public static function countCommon(int $sourceId, int $targetId, array $condition = [])
535 $condition = DBA::mergeConditions($condition,
536 ['`id` IN (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ?)
537 AND `id` IN (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ?)',
538 $sourceId, $targetId]
541 return DI::dba()->count('contact', $condition);
545 * Returns a paginated list of contacts that both provided public contacts have interacted with at least once.
546 * Interactions include follows and likes and comments on public posts.
548 * @param int $sourceId Public contact id
549 * @param int $targetId Public contact id
550 * @param array $condition Additional condition on the contact table
553 * @param bool $shuffle
557 public static function listCommon(int $sourceId, int $targetId, array $condition = [], int $count = 30, int $offset = 0, bool $shuffle = false)
559 $condition = DBA::mergeConditions($condition,
560 ["`id` IN (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ?)
561 AND `id` IN (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ?)",
562 $sourceId, $targetId]
565 return DI::dba()->selectToArray('contact', [], $condition,
566 ['limit' => [$offset, $count], 'order' => [$shuffle ? 'RAND()' : 'name']]
571 * Counts the number of contacts that are followed by both provided public contacts.
573 * @param int $sourceId Public contact id
574 * @param int $targetId Public contact id
575 * @param array $condition Additional condition array on the contact table
579 public static function countCommonFollows(int $sourceId, int $targetId, array $condition = [])
581 $condition = DBA::mergeConditions($condition,
582 ['`id` IN (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ? AND `follows`)
583 AND `id` IN (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ? AND `follows`)',
584 $sourceId, $targetId]
587 return DI::dba()->count('contact', $condition);
591 * Returns a paginated list of contacts that are followed by both provided public contacts.
593 * @param int $sourceId Public contact id
594 * @param int $targetId Public contact id
595 * @param array $condition Additional condition array on the contact table
598 * @param bool $shuffle
602 public static function listCommonFollows(int $sourceId, int $targetId, array $condition = [], int $count = 30, int $offset = 0, bool $shuffle = false)
604 $condition = DBA::mergeConditions($condition,
605 ["`id` IN (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ? AND `follows`)
606 AND `id` IN (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ? AND `follows`)",
607 $sourceId, $targetId]
610 return DI::dba()->selectToArray('contact', [], $condition,
611 ['limit' => [$offset, $count], 'order' => [$shuffle ? 'RAND()' : 'name']]
616 * Counts the number of contacts that follow both provided public contacts.
618 * @param int $sourceId Public contact id
619 * @param int $targetId Public contact id
620 * @param array $condition Additional condition on the contact table
624 public static function countCommonFollowers(int $sourceId, int $targetId, array $condition = [])
626 $condition = DBA::mergeConditions($condition,
627 ["`id` IN (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` = ? AND `follows`)
628 AND `id` IN (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` = ? AND `follows`)",
629 $sourceId, $targetId]
632 return DI::dba()->count('contact', $condition);
636 * Returns a paginated list of contacts that follow both provided public contacts.
638 * @param int $sourceId Public contact id
639 * @param int $targetId Public contact id
640 * @param array $condition Additional condition on the contact table
643 * @param bool $shuffle
647 public static function listCommonFollowers(int $sourceId, int $targetId, array $condition = [], int $count = 30, int $offset = 0, bool $shuffle = false)
649 $condition = DBA::mergeConditions($condition,
650 ["`id` IN (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` = ? AND `follows`)
651 AND `id` IN (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` = ? AND `follows`)",
652 $sourceId, $targetId]
655 return DI::dba()->selectToArray('contact', [], $condition,
656 ['limit' => [$offset, $count], 'order' => [$shuffle ? 'RAND()' : 'name']]