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 // 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 $fields = ['cid' => $target, 'relation-cid' => $actor, 'follows' => true, 'follow-updated' => DateTimeFormat::utcNow()];
141 DBA::insert('contact-relation', $fields, Database::INSERT_UPDATE);
145 if (in_array($contact, $followings)) {
146 $fields = ['cid' => $actor, 'relation-cid' => $target, 'follows' => true, 'follow-updated' => DateTimeFormat::utcNow()];
147 DBA::insert('contact-relation', $fields, Database::INSERT_UPDATE);
148 $following_counter++;
153 if (!empty($followers)) {
154 // Delete all followers that aren't followers anymore (and aren't interacting)
155 DBA::delete('contact-relation', ['cid' => $target, 'follows' => false, 'last-interaction' => DBA::NULL_DATETIME]);
158 DBA::update('contact', ['last-discovery' => DateTimeFormat::utcNow()], ['id' => $target]);
159 Logger::info('Contacts discovery finished', ['id' => $target, 'url' => $url, 'follower' => $follower_counter, 'following' => $following_counter]);
164 * Fetch contact url list from the given local user
166 * @param integer $uid
168 * @return array contact list
170 private static function getContacts(int $uid, array $rel)
173 $profile = Profile::getByUID($uid);
174 if (!empty($profile['hide-friends'])) {
178 $condition = ['rel' => $rel, 'uid' => $uid, 'self' => false, 'deleted' => false,
179 'hidden' => false, 'archive' => false, 'pending' => false];
180 $condition = DBA::mergeConditions($condition, ["`url` IN (SELECT `url` FROM `apcontact`)"]);
181 $contacts = DBA::select('contact', ['url'], $condition);
182 while ($contact = DBA::fetch($contacts)) {
183 $list[] = $contact['url'];
185 DBA::close($contacts);
191 * Tests if a given contact url is discoverable
193 * @param string $url Contact url
194 * @param array $contact Contact array
195 * @return boolean True if contact is discoverable
197 public static function isDiscoverable(string $url, array $contact = [])
199 $contact_discovery = DI::config()->get('system', 'contact_discovery');
201 if ($contact_discovery == self::DISCOVERY_NONE) {
205 if (empty($contact)) {
206 $contact = Contact::getByURL($url, false);
209 if (empty($contact)) {
213 if ($contact['last-discovery'] > DateTimeFormat::utc('now - 1 month')) {
214 Logger::info('No discovery - Last was less than a month ago.', ['id' => $contact['id'], 'url' => $url, 'discovery' => $contact['last-discovery']]);
218 if ($contact_discovery != self::DISCOVERY_ALL) {
219 $local = DBA::exists('contact', ["`nurl` = ? AND `uid` != ?", Strings::normaliseLink($url), 0]);
220 if (($contact_discovery == self::DISCOVERY_LOCAL) && !$local) {
221 Logger::info('No discovery - This contact is not followed/following locally.', ['id' => $contact['id'], 'url' => $url]);
225 if ($contact_discovery == self::DISCOVERY_INTERACTOR) {
226 $interactor = DBA::exists('contact-relation', ["`relation-cid` = ? AND `last-interaction` > ?", $contact['id'], DBA::NULL_DATETIME]);
227 if (!$local && !$interactor) {
228 Logger::info('No discovery - This contact is not interacting locally.', ['id' => $contact['id'], 'url' => $url]);
232 } elseif ($contact['created'] > DateTimeFormat::utc('now - 1 day')) {
233 // Newly created contacts are not discovered to avoid DDoS attacks
234 Logger::info('No discovery - Contact record is less than a day old.', ['id' => $contact['id'], 'url' => $url, 'discovery' => $contact['created']]);
238 if (!in_array($contact['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::OSTATUS])) {
239 $apcontact = APContact::getByURL($url, false);
240 if (empty($apcontact)) {
241 Logger::info('No discovery - The contact does not seem to speak ActivityPub.', ['id' => $contact['id'], 'url' => $url, 'network' => $contact['network']]);
250 * @param int $uid user
251 * @param int $start optional, default 0
252 * @param int $limit optional, default 80
255 static public function getSuggestions(int $uid, int $start = 0, int $limit = 80)
257 $cid = Contact::getPublicIdByUserId($uid);
258 $totallimit = $start + $limit;
261 Logger::info('Collecting suggestions', ['uid' => $uid, 'cid' => $cid, 'start' => $start, 'limit' => $limit]);
263 $diaspora = DI::config()->get('system', 'diaspora_enabled') ? Protocol::DIASPORA : Protocol::ACTIVITYPUB;
264 $ostatus = !DI::config()->get('system', 'ostatus_disabled') ? Protocol::OSTATUS : Protocol::ACTIVITYPUB;
266 // The query returns contacts where contacts interacted with whom the given user follows.
267 // Contacts who already are in the user's contact table are ignored.
268 $results = DBA::select('contact', [],
269 ["`id` IN (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` IN
270 (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` = ?)
271 AND NOT `cid` IN (SELECT `id` FROM `contact` WHERE `uid` = ? AND `nurl` IN
272 (SELECT `nurl` FROM `contact` WHERE `uid` = ? AND `rel` IN (?, ?))))
273 AND NOT `hidden` AND `network` IN (?, ?, ?, ?)",
274 $cid, 0, $uid, Contact::FRIEND, Contact::SHARING,
275 Protocol::ACTIVITYPUB, Protocol::DFRN, $diaspora, $ostatus],
276 ['order' => ['last-item' => true], 'limit' => $totallimit]
279 while ($contact = DBA::fetch($results)) {
280 $contacts[$contact['id']] = $contact;
282 DBA::close($results);
284 Logger::info('Contacts of contacts who are followed by the given user', ['uid' => $uid, 'cid' => $cid, 'count' => count($contacts)]);
286 if (count($contacts) >= $totallimit) {
287 return array_slice($contacts, $start, $limit);
290 // The query returns contacts where contacts interacted with whom also interacted with the given user.
291 // Contacts who already are in the user's contact table are ignored.
292 $results = DBA::select('contact', [],
293 ["`id` IN (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` IN
294 (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ?)
295 AND NOT `cid` IN (SELECT `id` FROM `contact` WHERE `uid` = ? AND `nurl` IN
296 (SELECT `nurl` FROM `contact` WHERE `uid` = ? AND `rel` IN (?, ?))))
297 AND NOT `hidden` AND `network` IN (?, ?, ?, ?)",
298 $cid, 0, $uid, Contact::FRIEND, Contact::SHARING,
299 Protocol::ACTIVITYPUB, Protocol::DFRN, $diaspora, $ostatus],
300 ['order' => ['last-item' => true], 'limit' => $totallimit]
303 while ($contact = DBA::fetch($results)) {
304 $contacts[$contact['id']] = $contact;
306 DBA::close($results);
308 Logger::info('Contacts of contacts who are following the given user', ['uid' => $uid, 'cid' => $cid, 'count' => count($contacts)]);
310 if (count($contacts) >= $totallimit) {
311 return array_slice($contacts, $start, $limit);
314 // The query returns contacts that follow the given user but aren't followed by that user.
315 $results = DBA::select('contact', [],
316 ["`nurl` IN (SELECT `nurl` FROM `contact` WHERE `uid` = ? AND `rel` = ?)
317 AND NOT `hidden` AND `uid` = ? AND `network` IN (?, ?, ?, ?)",
318 $uid, Contact::FOLLOWER, 0,
319 Protocol::ACTIVITYPUB, Protocol::DFRN, $diaspora, $ostatus],
320 ['order' => ['last-item' => true], 'limit' => $totallimit]
323 while ($contact = DBA::fetch($results)) {
324 $contacts[$contact['id']] = $contact;
326 DBA::close($results);
328 Logger::info('Followers that are not followed by the given user', ['uid' => $uid, 'cid' => $cid, 'count' => count($contacts)]);
330 if (count($contacts) >= $totallimit) {
331 return array_slice($contacts, $start, $limit);
334 // The query returns any contact that isn't followed by that user.
335 $results = DBA::select('contact', [],
336 ["NOT `nurl` IN (SELECT `nurl` FROM `contact` WHERE `uid` = ? AND `rel` IN (?, ?))
337 AND NOT `hidden` AND `uid` = ? AND `network` IN (?, ?, ?, ?)",
338 $uid, Contact::FRIEND, Contact::SHARING, 0,
339 Protocol::ACTIVITYPUB, Protocol::DFRN, $diaspora, $ostatus],
340 ['order' => ['last-item' => true], 'limit' => $totallimit]
343 while ($contact = DBA::fetch($results)) {
344 $contacts[$contact['id']] = $contact;
346 DBA::close($results);
348 Logger::info('Any contact', ['uid' => $uid, 'cid' => $cid, 'count' => count($contacts)]);
350 return array_slice($contacts, $start, $limit);
354 * Counts all the known follows of the provided public contact
356 * @param int $cid Public contact id
357 * @param array $condition Additional condition on the contact table
361 public static function countFollows(int $cid, array $condition = [])
363 $condition = DBA::mergeConditions($condition,
364 ['`id` IN (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ? AND `follows`)',
368 return DI::dba()->count('contact', $condition);
372 * Returns a paginated list of contacts that are followed the provided public contact.
374 * @param int $cid Public contact id
375 * @param array $condition Additional condition on the contact table
378 * @param bool $shuffle
382 public static function listFollows(int $cid, array $condition = [], int $count = 30, int $offset = 0, bool $shuffle = false)
384 $condition = DBA::mergeConditions($condition,
385 ['`id` IN (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ? AND `follows`)',
389 return DI::dba()->selectToArray('contact', [], $condition,
390 ['limit' => [$offset, $count], 'order' => [$shuffle ? 'RAND()' : 'name']]
395 * Counts all the known followers of the provided public contact
397 * @param int $cid Public contact id
398 * @param array $condition Additional condition on the contact table
402 public static function countFollowers(int $cid, array $condition = [])
404 $condition = DBA::mergeConditions($condition,
405 ['`id` IN (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` = ? AND `follows`)',
409 return DI::dba()->count('contact', $condition);
413 * Returns a paginated list of contacts that follow the provided public contact.
415 * @param int $cid Public contact id
416 * @param array $condition Additional condition on the contact table
419 * @param bool $shuffle
423 public static function listFollowers(int $cid, array $condition = [], int $count = 30, int $offset = 0, bool $shuffle = false)
425 $condition = DBA::mergeConditions($condition,
426 ['`id` IN (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` = ? AND `follows`)', $cid]
429 return DI::dba()->selectToArray('contact', [], $condition,
430 ['limit' => [$offset, $count], 'order' => [$shuffle ? 'RAND()' : 'name']]
435 * Counts the number of contacts that are known mutuals with the provided public contact.
437 * @param int $cid Public contact id
438 * @param array $condition Additional condition array on the contact table
442 public static function countMutuals(int $cid, array $condition = [])
444 $condition = DBA::mergeConditions($condition,
445 ['`id` IN (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ? AND `follows`)
446 AND `id` IN (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` = ? AND `follows`)',
450 return DI::dba()->count('contact', $condition);
454 * Returns a paginated list of contacts that are known mutuals with the provided public contact.
456 * @param int $cid Public contact id
457 * @param array $condition Additional condition on the contact table
460 * @param bool $shuffle
464 public static function listMutuals(int $cid, array $condition = [], int $count = 30, int $offset = 0, bool $shuffle = false)
466 $condition = DBA::mergeConditions($condition,
467 ['`id` IN (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ? AND `follows`)
468 AND `id` IN (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` = ? AND `follows`)',
472 return DI::dba()->selectToArray('contact', [], $condition,
473 ['limit' => [$offset, $count], 'order' => [$shuffle ? 'RAND()' : 'name']]
479 * Counts the number of contacts with any relationship with the provided public contact.
481 * @param int $cid Public contact id
482 * @param array $condition Additional condition array on the contact table
486 public static function countAll(int $cid, array $condition = [])
488 $condition = DBA::mergeConditions($condition,
489 ['(`id` IN (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ? AND `follows`)
490 OR `id` IN (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` = ? AND `follows`))',
494 return DI::dba()->count('contact', $condition);
498 * Returns a paginated list of contacts with any relationship with the provided public contact.
500 * @param int $cid Public contact id
501 * @param array $condition Additional condition on the contact table
504 * @param bool $shuffle
508 public static function listAll(int $cid, array $condition = [], int $count = 30, int $offset = 0, bool $shuffle = false)
510 $condition = DBA::mergeConditions($condition,
511 ['(`id` IN (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ? AND `follows`)
512 OR `id` IN (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` = ? AND `follows`))',
516 return DI::dba()->selectToArray('contact', [], $condition,
517 ['limit' => [$offset, $count], 'order' => [$shuffle ? 'RAND()' : 'name']]
522 * Counts the number of contacts that both provided public contacts have interacted with at least once.
523 * Interactions include follows and likes and comments on public posts.
525 * @param int $sourceId Public contact id
526 * @param int $targetId Public contact id
527 * @param array $condition Additional condition array on the contact table
531 public static function countCommon(int $sourceId, int $targetId, array $condition = [])
533 $condition = DBA::mergeConditions($condition,
534 ['`id` IN (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ?)
535 AND `id` IN (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ?)',
536 $sourceId, $targetId]
539 return DI::dba()->count('contact', $condition);
543 * Returns a paginated list of contacts that both provided public contacts have interacted with at least once.
544 * Interactions include follows and likes and comments on public posts.
546 * @param int $sourceId Public contact id
547 * @param int $targetId Public contact id
548 * @param array $condition Additional condition on the contact table
551 * @param bool $shuffle
555 public static function listCommon(int $sourceId, int $targetId, array $condition = [], int $count = 30, int $offset = 0, bool $shuffle = false)
557 $condition = DBA::mergeConditions($condition,
558 ["`id` IN (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ?)
559 AND `id` IN (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ?)",
560 $sourceId, $targetId]
563 return DI::dba()->selectToArray('contact', [], $condition,
564 ['limit' => [$offset, $count], 'order' => [$shuffle ? 'RAND()' : 'name']]
569 * Counts the number of contacts that are followed by both provided public contacts.
571 * @param int $sourceId Public contact id
572 * @param int $targetId Public contact id
573 * @param array $condition Additional condition array on the contact table
577 public static function countCommonFollows(int $sourceId, int $targetId, array $condition = [])
579 $condition = DBA::mergeConditions($condition,
580 ['`id` IN (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ? AND `follows`)
581 AND `id` IN (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ? AND `follows`)',
582 $sourceId, $targetId]
585 return DI::dba()->count('contact', $condition);
589 * Returns a paginated list of contacts that are followed by both provided public contacts.
591 * @param int $sourceId Public contact id
592 * @param int $targetId Public contact id
593 * @param array $condition Additional condition array on the contact table
596 * @param bool $shuffle
600 public static function listCommonFollows(int $sourceId, int $targetId, array $condition = [], int $count = 30, int $offset = 0, bool $shuffle = false)
602 $condition = DBA::mergeConditions($condition,
603 ["`id` IN (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ? AND `follows`)
604 AND `id` IN (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ? AND `follows`)",
605 $sourceId, $targetId]
608 return DI::dba()->selectToArray('contact', [], $condition,
609 ['limit' => [$offset, $count], 'order' => [$shuffle ? 'RAND()' : 'name']]
614 * Counts the number of contacts that follow both provided public contacts.
616 * @param int $sourceId Public contact id
617 * @param int $targetId Public contact id
618 * @param array $condition Additional condition on the contact table
622 public static function countCommonFollowers(int $sourceId, int $targetId, array $condition = [])
624 $condition = DBA::mergeConditions($condition,
625 ["`id` IN (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` = ? AND `follows`)
626 AND `id` IN (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` = ? AND `follows`)",
627 $sourceId, $targetId]
630 return DI::dba()->count('contact', $condition);
634 * Returns a paginated list of contacts that follow both provided public contacts.
636 * @param int $sourceId Public contact id
637 * @param int $targetId Public contact id
638 * @param array $condition Additional condition on the contact table
641 * @param bool $shuffle
645 public static function listCommonFollowers(int $sourceId, int $targetId, array $condition = [], int $count = 30, int $offset = 0, bool $shuffle = false)
647 $condition = DBA::mergeConditions($condition,
648 ["`id` IN (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` = ? AND `follows`)
649 AND `id` IN (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` = ? AND `follows`)",
650 $sourceId, $targetId]
653 return DI::dba()->selectToArray('contact', [], $condition,
654 ['limit' => [$offset, $count], 'order' => [$shuffle ? 'RAND()' : 'name']]