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\DBA;
29 use Friendica\Model\APContact;
30 use Friendica\Model\Contact;
31 use Friendica\Model\Profile;
32 use Friendica\Model\User;
33 use Friendica\Protocol\ActivityPub;
34 use Friendica\Util\DateTimeFormat;
35 use Friendica\Util\Strings;
38 * This class provides relationship information based on the `contact-relation` table.
39 * This table is directional (cid = source, relation-cid = target), references public contacts (with uid=0) and records both
40 * follows and the last interaction (likes/comments) on public posts.
45 * No discovery of followers/followings
47 const DISCOVERY_NONE = 0;
49 * Discover followers/followings of local contacts
51 const DISCOVERY_LOCAL = 1;
53 * Discover followers/followings of local contacts and contacts that visibly interacted on the system
55 const DISCOVERY_INTERACTOR = 2;
57 * Discover followers/followings of all contacts
59 const DISCOVERY_ALL = 3;
61 public static function store(int $target, int $actor, string $interaction_date)
63 if ($actor == $target) {
67 DBA::update('contact-relation', ['last-interaction' => $interaction_date], ['cid' => $target, 'relation-cid' => $actor], true);
71 * Fetches the followers of a given profile and adds them
73 * @param string $url URL of a profile
76 public static function discoverByUrl(string $url)
78 $contact = Contact::getByURL($url);
79 if (empty($contact)) {
83 if (!self::isDiscoverable($url, $contact)) {
87 $uid = User::getIdForURL($url);
89 // Fetch the followers/followings locally
90 $followers = self::getContacts($uid, [Contact::FOLLOWER, Contact::FRIEND]);
91 $followings = self::getContacts($uid, [Contact::SHARING, Contact::FRIEND]);
93 $apcontact = APContact::getByURL($url, false);
95 if (!empty($apcontact['followers']) && is_string($apcontact['followers'])) {
96 $followers = ActivityPub::fetchItems($apcontact['followers']);
101 if (!empty($apcontact['following']) && is_string($apcontact['following'])) {
102 $followings = ActivityPub::fetchItems($apcontact['following']);
108 if (empty($followers) && empty($followings)) {
109 DBA::update('contact', ['last-discovery' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
110 Logger::info('The contact does not offer discoverable data', ['id' => $contact['id'], 'url' => $url, 'network' => $contact['network']]);
114 $target = $contact['id'];
116 if (!empty($followers)) {
117 // Clear the follower list, since it will be recreated in the next step
118 DBA::update('contact-relation', ['follows' => false], ['cid' => $target]);
122 foreach (array_merge($followers, $followings) as $contact) {
123 if (is_string($contact)) {
124 $contacts[] = $contact;
125 } elseif (!empty($contact['url']) && is_string($contact['url'])) {
126 $contacts[] = $contact['url'];
129 $contacts = array_unique($contacts);
131 $follower_counter = 0;
132 $following_counter = 0;
134 Logger::info('Discover contacts', ['id' => $target, 'url' => $url, 'contacts' => count($contacts)]);
135 foreach ($contacts as $contact) {
136 $actor = Contact::getIdForURL($contact);
137 if (!empty($actor)) {
138 if (in_array($contact, $followers)) {
139 $fields = ['cid' => $target, 'relation-cid' => $actor];
140 DBA::update('contact-relation', ['follows' => true, 'follow-updated' => DateTimeFormat::utcNow()], $fields, true);
144 if (in_array($contact, $followings)) {
145 $fields = ['cid' => $actor, 'relation-cid' => $target];
146 DBA::update('contact-relation', ['follows' => true, 'follow-updated' => DateTimeFormat::utcNow()], $fields, true);
147 $following_counter++;
152 if (!empty($followers)) {
153 // Delete all followers that aren't followers anymore (and aren't interacting)
154 DBA::delete('contact-relation', ['cid' => $target, 'follows' => false, 'last-interaction' => DBA::NULL_DATETIME]);
157 DBA::update('contact', ['last-discovery' => DateTimeFormat::utcNow()], ['id' => $target]);
158 Logger::info('Contacts discovery finished', ['id' => $target, 'url' => $url, 'follower' => $follower_counter, 'following' => $following_counter]);
163 * Fetch contact url list from the given local user
165 * @param integer $uid
167 * @return array contact list
169 private static function getContacts(int $uid, array $rel)
172 $profile = Profile::getByUID($uid);
173 if (!empty($profile['hide-friends'])) {
177 $condition = ['rel' => $rel, 'uid' => $uid, 'self' => false, 'deleted' => false,
178 'hidden' => false, 'archive' => false, 'pending' => false];
179 $condition = DBA::mergeConditions($condition, ["`url` IN (SELECT `url` FROM `apcontact`)"]);
180 $contacts = DBA::select('contact', ['url'], $condition);
181 while ($contact = DBA::fetch($contacts)) {
182 $list[] = $contact['url'];
184 DBA::close($contacts);
190 * Tests if a given contact url is discoverable
192 * @param string $url Contact url
193 * @param array $contact Contact array
194 * @return boolean True if contact is discoverable
196 public static function isDiscoverable(string $url, array $contact = [])
198 $contact_discovery = DI::config()->get('system', 'contact_discovery');
200 if ($contact_discovery == self::DISCOVERY_NONE) {
204 if (empty($contact)) {
205 $contact = Contact::getByURL($url, false);
208 if (empty($contact)) {
212 if ($contact['last-discovery'] > DateTimeFormat::utc('now - 1 month')) {
213 Logger::info('No discovery - Last was less than a month ago.', ['id' => $contact['id'], 'url' => $url, 'discovery' => $contact['last-discovery']]);
217 if ($contact_discovery != self::DISCOVERY_ALL) {
218 $local = DBA::exists('contact', ["`nurl` = ? AND `uid` != ?", Strings::normaliseLink($url), 0]);
219 if (($contact_discovery == self::DISCOVERY_LOCAL) && !$local) {
220 Logger::info('No discovery - This contact is not followed/following locally.', ['id' => $contact['id'], 'url' => $url]);
224 if ($contact_discovery == self::DISCOVERY_INTERACTOR) {
225 $interactor = DBA::exists('contact-relation', ["`relation-cid` = ? AND `last-interaction` > ?", $contact['id'], DBA::NULL_DATETIME]);
226 if (!$local && !$interactor) {
227 Logger::info('No discovery - This contact is not interacting locally.', ['id' => $contact['id'], 'url' => $url]);
231 } elseif ($contact['created'] > DateTimeFormat::utc('now - 1 day')) {
232 // Newly created contacts are not discovered to avoid DDoS attacks
233 Logger::info('No discovery - Contact record is less than a day old.', ['id' => $contact['id'], 'url' => $url, 'discovery' => $contact['created']]);
237 if (!in_array($contact['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::OSTATUS])) {
238 $apcontact = APContact::getByURL($url, false);
239 if (empty($apcontact)) {
240 Logger::info('No discovery - The contact does not seem to speak ActivityPub.', ['id' => $contact['id'], 'url' => $url, 'network' => $contact['network']]);
249 * @param int $uid user
250 * @param int $start optional, default 0
251 * @param int $limit optional, default 80
254 static public function getSuggestions(int $uid, int $start = 0, int $limit = 80)
256 $cid = Contact::getPublicIdByUserId($uid);
257 $totallimit = $start + $limit;
260 Logger::info('Collecting suggestions', ['uid' => $uid, 'cid' => $cid, 'start' => $start, 'limit' => $limit]);
262 $diaspora = DI::config()->get('system', 'diaspora_enabled') ? Protocol::DIASPORA : Protocol::ACTIVITYPUB;
263 $ostatus = !DI::config()->get('system', 'ostatus_disabled') ? Protocol::OSTATUS : Protocol::ACTIVITYPUB;
265 // The query returns contacts where contacts interacted with whom the given user follows.
266 // Contacts who already are in the user's contact table are ignored.
267 $results = DBA::select('contact', [],
268 ["`id` IN (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` IN
269 (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` = ?)
270 AND NOT `cid` IN (SELECT `id` FROM `contact` WHERE `uid` = ? AND `nurl` IN
271 (SELECT `nurl` FROM `contact` WHERE `uid` = ? AND `rel` IN (?, ?))))
272 AND NOT `hidden` AND `network` IN (?, ?, ?, ?)",
273 $cid, 0, $uid, Contact::FRIEND, Contact::SHARING,
274 Protocol::ACTIVITYPUB, Protocol::DFRN, $diaspora, $ostatus],
275 ['order' => ['last-item' => true], 'limit' => $totallimit]
278 while ($contact = DBA::fetch($results)) {
279 $contacts[$contact['id']] = $contact;
281 DBA::close($results);
283 Logger::info('Contacts of contacts who are followed by the given user', ['uid' => $uid, 'cid' => $cid, 'count' => count($contacts)]);
285 if (count($contacts) >= $totallimit) {
286 return array_slice($contacts, $start, $limit);
289 // The query returns contacts where contacts interacted with whom also interacted with the given user.
290 // Contacts who already are in the user's contact table are ignored.
291 $results = DBA::select('contact', [],
292 ["`id` IN (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` IN
293 (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ?)
294 AND NOT `cid` IN (SELECT `id` FROM `contact` WHERE `uid` = ? AND `nurl` IN
295 (SELECT `nurl` FROM `contact` WHERE `uid` = ? AND `rel` IN (?, ?))))
296 AND NOT `hidden` AND `network` IN (?, ?, ?, ?)",
297 $cid, 0, $uid, Contact::FRIEND, Contact::SHARING,
298 Protocol::ACTIVITYPUB, Protocol::DFRN, $diaspora, $ostatus],
299 ['order' => ['last-item' => true], 'limit' => $totallimit]
302 while ($contact = DBA::fetch($results)) {
303 $contacts[$contact['id']] = $contact;
305 DBA::close($results);
307 Logger::info('Contacts of contacts who are following the given user', ['uid' => $uid, 'cid' => $cid, 'count' => count($contacts)]);
309 if (count($contacts) >= $totallimit) {
310 return array_slice($contacts, $start, $limit);
313 // The query returns contacts that follow the given user but aren't followed by that user.
314 $results = DBA::select('contact', [],
315 ["`nurl` IN (SELECT `nurl` FROM `contact` WHERE `uid` = ? AND `rel` = ?)
316 AND NOT `hidden` AND `uid` = ? AND `network` IN (?, ?, ?, ?)",
317 $uid, Contact::FOLLOWER, 0,
318 Protocol::ACTIVITYPUB, Protocol::DFRN, $diaspora, $ostatus],
319 ['order' => ['last-item' => true], 'limit' => $totallimit]
322 while ($contact = DBA::fetch($results)) {
323 $contacts[$contact['id']] = $contact;
325 DBA::close($results);
327 Logger::info('Followers that are not followed by the given user', ['uid' => $uid, 'cid' => $cid, 'count' => count($contacts)]);
329 if (count($contacts) >= $totallimit) {
330 return array_slice($contacts, $start, $limit);
333 // The query returns any contact that isn't followed by that user.
334 $results = DBA::select('contact', [],
335 ["NOT `nurl` IN (SELECT `nurl` FROM `contact` WHERE `uid` = ? AND `rel` IN (?, ?))
336 AND NOT `hidden` AND `uid` = ? AND `network` IN (?, ?, ?, ?)",
337 $uid, Contact::FRIEND, Contact::SHARING, 0,
338 Protocol::ACTIVITYPUB, Protocol::DFRN, $diaspora, $ostatus],
339 ['order' => ['last-item' => true], 'limit' => $totallimit]
342 while ($contact = DBA::fetch($results)) {
343 $contacts[$contact['id']] = $contact;
345 DBA::close($results);
347 Logger::info('Any contact', ['uid' => $uid, 'cid' => $cid, 'count' => count($contacts)]);
349 return array_slice($contacts, $start, $limit);
353 * Counts all the known follows of the provided public contact
355 * @param int $cid Public contact id
356 * @param array $condition Additional condition on the contact table
360 public static function countFollows(int $cid, array $condition = [])
362 $condition = DBA::mergeConditions($condition,
363 ['`id` IN (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ? AND `follows`)',
367 return DI::dba()->count('contact', $condition);
371 * Returns a paginated list of contacts that are followed the provided public contact.
373 * @param int $cid Public contact id
374 * @param array $condition Additional condition on the contact table
377 * @param bool $shuffle
381 public static function listFollows(int $cid, array $condition = [], int $count = 30, int $offset = 0, bool $shuffle = false)
383 $condition = DBA::mergeConditions($condition,
384 ['`id` IN (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ? AND `follows`)',
388 return DI::dba()->selectToArray('contact', [], $condition,
389 ['limit' => [$offset, $count], 'order' => [$shuffle ? 'RAND()' : 'name']]
394 * Counts all the known followers of the provided public contact
396 * @param int $cid Public contact id
397 * @param array $condition Additional condition on the contact table
401 public static function countFollowers(int $cid, array $condition = [])
403 $condition = DBA::mergeConditions($condition,
404 ['`id` IN (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` = ? AND `follows`)',
408 return DI::dba()->count('contact', $condition);
412 * Returns a paginated list of contacts that follow the provided public contact.
414 * @param int $cid Public contact id
415 * @param array $condition Additional condition on the contact table
418 * @param bool $shuffle
422 public static function listFollowers(int $cid, array $condition = [], int $count = 30, int $offset = 0, bool $shuffle = false)
424 $condition = DBA::mergeConditions($condition,
425 ['`id` IN (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` = ? AND `follows`)', $cid]
428 return DI::dba()->selectToArray('contact', [], $condition,
429 ['limit' => [$offset, $count], 'order' => [$shuffle ? 'RAND()' : 'name']]
434 * Counts the number of contacts that are known mutuals with the provided public contact.
436 * @param int $cid Public contact id
437 * @param array $condition Additional condition array on the contact table
441 public static function countMutuals(int $cid, array $condition = [])
443 $condition = DBA::mergeConditions($condition,
444 ['`id` IN (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ? AND `follows`)
445 AND `id` IN (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` = ? AND `follows`)',
449 return DI::dba()->count('contact', $condition);
453 * Returns a paginated list of contacts that are known mutuals with the provided public contact.
455 * @param int $cid Public contact id
456 * @param array $condition Additional condition on the contact table
459 * @param bool $shuffle
463 public static function listMutuals(int $cid, array $condition = [], int $count = 30, int $offset = 0, bool $shuffle = false)
465 $condition = DBA::mergeConditions($condition,
466 ['`id` IN (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ? AND `follows`)
467 AND `id` IN (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` = ? AND `follows`)',
471 return DI::dba()->selectToArray('contact', [], $condition,
472 ['limit' => [$offset, $count], 'order' => [$shuffle ? 'RAND()' : 'name']]
478 * Counts the number of contacts with any relationship with the provided public contact.
480 * @param int $cid Public contact id
481 * @param array $condition Additional condition array on the contact table
485 public static function countAll(int $cid, array $condition = [])
487 $condition = DBA::mergeConditions($condition,
488 ['(`id` IN (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ? AND `follows`)
489 OR `id` IN (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` = ? AND `follows`))',
493 return DI::dba()->count('contact', $condition);
497 * Returns a paginated list of contacts with any relationship with the provided public contact.
499 * @param int $cid Public contact id
500 * @param array $condition Additional condition on the contact table
503 * @param bool $shuffle
507 public static function listAll(int $cid, array $condition = [], int $count = 30, int $offset = 0, bool $shuffle = false)
509 $condition = DBA::mergeConditions($condition,
510 ['(`id` IN (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ? AND `follows`)
511 OR `id` IN (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` = ? AND `follows`))',
515 return DI::dba()->selectToArray('contact', [], $condition,
516 ['limit' => [$offset, $count], 'order' => [$shuffle ? 'RAND()' : 'name']]
521 * Counts the number of contacts that both provided public contacts have interacted with at least once.
522 * Interactions include follows and likes and comments on public posts.
524 * @param int $sourceId Public contact id
525 * @param int $targetId Public contact id
526 * @param array $condition Additional condition array on the contact table
530 public static function countCommon(int $sourceId, int $targetId, array $condition = [])
532 $condition = DBA::mergeConditions($condition,
533 ['`id` IN (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ?)
534 AND `id` IN (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ?)',
535 $sourceId, $targetId]
538 return DI::dba()->count('contact', $condition);
542 * Returns a paginated list of contacts that both provided public contacts have interacted with at least once.
543 * Interactions include follows and likes and comments on public posts.
545 * @param int $sourceId Public contact id
546 * @param int $targetId Public contact id
547 * @param array $condition Additional condition on the contact table
550 * @param bool $shuffle
554 public static function listCommon(int $sourceId, int $targetId, array $condition = [], int $count = 30, int $offset = 0, bool $shuffle = false)
556 $condition = DBA::mergeConditions($condition,
557 ["`id` IN (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ?)
558 AND `id` IN (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ?)",
559 $sourceId, $targetId]
562 return DI::dba()->selectToArray('contact', [], $condition,
563 ['limit' => [$offset, $count], 'order' => [$shuffle ? 'RAND()' : 'name']]
568 * Counts the number of contacts that are followed by both provided public contacts.
570 * @param int $sourceId Public contact id
571 * @param int $targetId Public contact id
572 * @param array $condition Additional condition array on the contact table
576 public static function countCommonFollows(int $sourceId, int $targetId, array $condition = [])
578 $condition = DBA::mergeConditions($condition,
579 ['`id` IN (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ? AND `follows`)
580 AND `id` IN (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ? AND `follows`)',
581 $sourceId, $targetId]
584 return DI::dba()->count('contact', $condition);
588 * Returns a paginated list of contacts that are followed by both provided public contacts.
590 * @param int $sourceId Public contact id
591 * @param int $targetId Public contact id
592 * @param array $condition Additional condition array on the contact table
595 * @param bool $shuffle
599 public static function listCommonFollows(int $sourceId, int $targetId, array $condition = [], int $count = 30, int $offset = 0, bool $shuffle = false)
601 $condition = DBA::mergeConditions($condition,
602 ["`id` IN (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ? AND `follows`)
603 AND `id` IN (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ? AND `follows`)",
604 $sourceId, $targetId]
607 return DI::dba()->selectToArray('contact', [], $condition,
608 ['limit' => [$offset, $count], 'order' => [$shuffle ? 'RAND()' : 'name']]
613 * Counts the number of contacts that follow both provided public contacts.
615 * @param int $sourceId Public contact id
616 * @param int $targetId Public contact id
617 * @param array $condition Additional condition on the contact table
621 public static function countCommonFollowers(int $sourceId, int $targetId, array $condition = [])
623 $condition = DBA::mergeConditions($condition,
624 ["`id` IN (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` = ? AND `follows`)
625 AND `id` IN (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` = ? AND `follows`)",
626 $sourceId, $targetId]
629 return DI::dba()->count('contact', $condition);
633 * Returns a paginated list of contacts that follow both provided public contacts.
635 * @param int $sourceId Public contact id
636 * @param int $targetId Public contact id
637 * @param array $condition Additional condition on the contact table
640 * @param bool $shuffle
644 public static function listCommonFollowers(int $sourceId, int $targetId, array $condition = [], int $count = 30, int $offset = 0, bool $shuffle = false)
646 $condition = DBA::mergeConditions($condition,
647 ["`id` IN (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` = ? AND `follows`)
648 AND `id` IN (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` = ? AND `follows`)",
649 $sourceId, $targetId]
652 return DI::dba()->selectToArray('contact', [], $condition,
653 ['limit' => [$offset, $count], 'order' => [$shuffle ? 'RAND()' : 'name']]