]> git.mxchange.org Git - friendica.git/blob - src/Model/Contact/Relation.php
bae59f48c57e727df52fbc7ac53548264be3c44e
[friendica.git] / src / Model / Contact / Relation.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2022, the Friendica project
4  *
5  * @license GNU AGPL version 3 or any later version
6  *
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.
11  *
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.
16  *
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/>.
19  *
20  */
21
22 namespace Friendica\Model\Contact;
23
24 use Exception;
25 use Friendica\Core\Logger;
26 use Friendica\Core\Protocol;
27 use Friendica\Database\Database;
28 use Friendica\Database\DBA;
29 use Friendica\DI;
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;
37
38 /**
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.
42  */
43 class Relation
44 {
45         /**
46          * No discovery of followers/followings
47          */
48         const DISCOVERY_NONE = 0;
49         /**
50          * Discover followers/followings of local contacts
51          */
52         const DISCOVERY_LOCAL = 1;
53         /**
54          * Discover followers/followings of local contacts and contacts that visibly interacted on the system
55          */
56         const DISCOVERY_INTERACTOR = 2;
57         /**
58          * Discover followers/followings of all contacts
59          */
60         const DISCOVERY_ALL = 3;
61
62         public static function store(int $target, int $actor, string $interaction_date)
63         {
64                 if ($actor == $target) {
65                         return;
66                 }
67
68                 DBA::insert('contact-relation', ['last-interaction' => $interaction_date, 'cid' => $target, 'relation-cid' => $actor], Database::INSERT_UPDATE);
69         }
70
71         /**
72          * Fetches the followers of a given profile and adds them
73          *
74          * @param string $url URL of a profile
75          * @return void
76          */
77         public static function discoverByUrl(string $url)
78         {
79                 $contact = Contact::getByURL($url);
80                 if (empty($contact)) {
81                         Logger::info('Contact not found', ['url' => $url]);
82                         return;
83                 }
84
85                 if (!self::isDiscoverable($url, $contact)) {
86                         Logger::info('Contact is not discoverable', ['url' => $url]);
87                         return;
88                 }
89
90                 $uid = User::getIdForURL($url);
91                 if (!empty($uid)) {
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);
98
99                         if (!empty($apcontact['followers']) && is_string($apcontact['followers'])) {
100                                 $followers = ActivityPub::fetchItems($apcontact['followers']);
101                         } else {
102                                 $followers = [];
103                         }
104
105                         if (!empty($apcontact['following']) && is_string($apcontact['following'])) {
106                                 $followings = ActivityPub::fetchItems($apcontact['following']);
107                         } else {
108                                 $followings = [];
109                         }
110                 } else {
111                         Logger::warning('Contact seems to be local but could not be found here', ['url' => $url]);
112                         $followers = [];
113                         $followings = [];
114                 }
115
116                 if (empty($followers) && empty($followings)) {
117                         Contact::update(['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']]);
119                         return;
120                 }
121
122                 $target = $contact['id'];
123
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]);
127                 }
128
129                 $contacts = [];
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'];
135                         }
136                 }
137                 $contacts = array_unique($contacts);
138
139                 $follower_counter = 0;
140                 $following_counter = 0;
141
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);
149                                         $follower_counter++;
150                                 }
151
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++;
156                                 }
157                         }
158                 }
159
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]);
163                 }
164
165                 Contact::update(['last-discovery' => DateTimeFormat::utcNow()], ['id' => $target]);
166                 Logger::info('Contacts discovery finished', ['id' => $target, 'url' => $url, 'follower' => $follower_counter, 'following' => $following_counter]);
167                 return;
168         }
169
170         /**
171          * Fetch contact url list from the given local user
172          *
173          * @param integer $uid
174          * @param array $rel
175          * @return array contact list
176          */
177         private static function getContacts(int $uid, array $rel): array
178         {
179                 $list = [];
180                 $profile = Profile::getByUID($uid);
181                 if (!empty($profile['hide-friends'])) {
182                         return $list;
183                 }
184
185                 $condition = [
186                         'rel' => $rel,
187                         'uid' => $uid,
188                         'self' => false,
189                         'deleted' => false,
190                         'hidden' => false,
191                         'archive' => false,
192                         'pending' => false,
193                 ];
194                 $condition = DBA::mergeConditions($condition, ["`url` IN (SELECT `url` FROM `apcontact`)"]);
195                 $contacts = DBA::select('contact', ['url'], $condition);
196                 while ($contact = DBA::fetch($contacts)) {
197                         $list[] = $contact['url'];
198                 }
199                 DBA::close($contacts);
200
201                 return $list;
202         }
203
204         /**
205          * Tests if a given contact url is discoverable
206          *
207          * @param string $url     Contact url
208          * @param array  $contact Contact array
209          * @return boolean True if contact is discoverable
210          */
211         public static function isDiscoverable(string $url, array $contact = []): bool
212         {
213                 $contact_discovery = DI::config()->get('system', 'contact_discovery');
214
215                 if ($contact_discovery == self::DISCOVERY_NONE) {
216                         return false;
217                 }
218
219                 if (empty($contact)) {
220                         $contact = Contact::getByURL($url, false);
221                 }
222
223                 if (empty($contact)) {
224                         return false;
225                 }
226
227                 if ($contact['last-discovery'] > DateTimeFormat::utc('now - 1 month')) {
228                         Logger::info('No discovery - Last was less than a month ago.', ['id' => $contact['id'], 'url' => $url, 'discovery' => $contact['last-discovery']]);
229                         return false;
230                 }
231
232                 if ($contact_discovery != self::DISCOVERY_ALL) {
233                         $local = DBA::exists('contact', ["`nurl` = ? AND `uid` != ?", Strings::normaliseLink($url), 0]);
234                         if (($contact_discovery == self::DISCOVERY_LOCAL) && !$local) {
235                                 Logger::info('No discovery - This contact is not followed/following locally.', ['id' => $contact['id'], 'url' => $url]);
236                                 return false;
237                         }
238
239                         if ($contact_discovery == self::DISCOVERY_INTERACTOR) {
240                                 $interactor = DBA::exists('contact-relation', ["`relation-cid` = ? AND `last-interaction` > ?", $contact['id'], DBA::NULL_DATETIME]);
241                                 if (!$local && !$interactor) {
242                                         Logger::info('No discovery - This contact is not interacting locally.', ['id' => $contact['id'], 'url' => $url]);
243                                         return false;
244                                 }
245                         }
246                 } elseif ($contact['created'] > DateTimeFormat::utc('now - 1 day')) {
247                         // Newly created contacts are not discovered to avoid DDoS attacks
248                         Logger::info('No discovery - Contact record is less than a day old.', ['id' => $contact['id'], 'url' => $url, 'discovery' => $contact['created']]);
249                         return false;
250                 }
251
252                 if (!in_array($contact['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::OSTATUS])) {
253                         $apcontact = APContact::getByURL($url, false);
254                         if (empty($apcontact)) {
255                                 Logger::info('No discovery - The contact does not seem to speak ActivityPub.', ['id' => $contact['id'], 'url' => $url, 'network' => $contact['network']]);
256                                 return false;
257                         }
258                 }
259
260                 return true;
261         }
262
263         /**
264          * Check if the cached suggestion is outdated
265          *
266          * @param integer $uid
267          * @return boolean
268          */
269         static public function areSuggestionsOutdated(int $uid): bool
270         {
271                 return DI::pConfig()->get($uid, 'suggestion', 'last_update') + 3600 < time();
272         }
273
274         /**
275          * Update contact suggestions for a given user
276          *
277          * @param integer $uid
278          * @return void
279          */
280         static public function updateCachedSuggestions(int $uid)
281         {
282                 if (!self::areSuggestionsOutdated($uid)) {
283                         return;
284                 }
285
286                 DBA::delete('account-suggestion', ['uid' => $uid, 'ignore' => false]);
287
288                 foreach (self::getSuggestions($uid) as $contact) {
289                         DBA::insert('account-suggestion', ['uri-id' => $contact['uri-id'], 'uid' => $uid, 'level' => 1], Database::INSERT_IGNORE);
290                 }
291
292                 DI::pConfig()->set($uid, 'suggestion', 'last_update', time());
293         }
294
295         /**
296          * Returns a cached array of suggested contacts for given user id
297          *
298          * @param int $uid   User id
299          * @param int $start optional, default 0
300          * @param int $limit optional, default 80
301          * @return array
302          */
303         static public function getCachedSuggestions(int $uid, int $start = 0, int $limit = 80): array
304         {
305                 $condition = ["`uid` = ? AND `uri-id` IN (SELECT `uri-id` FROM `account-suggestion` WHERE NOT `ignore` AND `uid` = ?)", 0, $uid];
306                 $params = ['limit' => [$start, $limit]];
307                 $cached = DBA::selectToArray('contact', [], $condition, $params);
308
309                 if (!empty($cached)) {
310                         return $cached;
311                 } else {
312                         return self::getSuggestions($uid, $start, $limit);
313                 }
314         }
315
316         /**
317          * Returns an array of suggested contacts for given user id
318          *
319          * @param int $uid   User id
320          * @param int $start optional, default 0
321          * @param int $limit optional, default 80
322          * @return array
323          */
324         static public function getSuggestions(int $uid, int $start = 0, int $limit = 80): array
325         {
326                 $cid = Contact::getPublicIdByUserId($uid);
327                 $totallimit = $start + $limit;
328                 $contacts = [];
329
330                 Logger::info('Collecting suggestions', ['uid' => $uid, 'cid' => $cid, 'start' => $start, 'limit' => $limit]);
331
332                 $diaspora = DI::config()->get('system', 'diaspora_enabled') ? Protocol::DIASPORA : Protocol::ACTIVITYPUB;
333                 $ostatus = !DI::config()->get('system', 'ostatus_disabled') ? Protocol::OSTATUS : Protocol::ACTIVITYPUB;
334
335                 // The query returns contacts where contacts interacted with whom the given user follows.
336                 // Contacts who already are in the user's contact table are ignored.
337                 $results = DBA::select('contact', [], ["`id` IN (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` IN
338                                 (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` = ?)
339                                         AND NOT `cid` IN (SELECT `id` FROM `contact` WHERE `uid` = ? AND `nurl` IN
340                                                 (SELECT `nurl` FROM `contact` WHERE `uid` = ? AND `rel` IN (?, ?))) AND `id` = `cid`)
341                         AND NOT `hidden` AND `network` IN (?, ?, ?, ?)
342                         AND NOT `uri-id` IN (SELECT `uri-id` FROM `account-suggestion` WHERE `uri-id` = `contact`.`uri-id` AND `uid` = ?)",
343                         $cid,
344                         0,
345                         $uid, Contact::FRIEND, Contact::SHARING,
346                         Protocol::ACTIVITYPUB, Protocol::DFRN, $diaspora, $ostatus, $uid
347                         ], [
348                                 'order' => ['last-item' => true],
349                                 'limit' => $totallimit,
350                         ]
351                 );
352
353                 while ($contact = DBA::fetch($results)) {
354                         $contacts[$contact['id']] = $contact;
355                 }
356
357                 DBA::close($results);
358
359                 Logger::info('Contacts of contacts who are followed by the given user', ['uid' => $uid, 'cid' => $cid, 'count' => count($contacts)]);
360
361                 if (count($contacts) >= $totallimit) {
362                         return array_slice($contacts, $start, $limit);
363                 }
364
365                 // The query returns contacts where contacts interacted with whom also interacted with the given user.
366                 // Contacts who already are in the user's contact table are ignored.
367                 $results = DBA::select('contact', [],
368                         ["`id` IN (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` IN
369                                 (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ?)
370                                         AND NOT `cid` IN (SELECT `id` FROM `contact` WHERE `uid` = ? AND `nurl` IN
371                                                 (SELECT `nurl` FROM `contact` WHERE `uid` = ? AND `rel` IN (?, ?))) AND `id` = `cid`)
372                         AND NOT `hidden` AND `network` IN (?, ?, ?, ?)
373                         AND NOT `uri-id` IN (SELECT `uri-id` FROM `account-suggestion` WHERE `uri-id` = `contact`.`uri-id` AND `uid` = ?)",
374                         $cid, 0, $uid, Contact::FRIEND, Contact::SHARING,
375                         Protocol::ACTIVITYPUB, Protocol::DFRN, $diaspora, $ostatus, $uid],
376                         ['order' => ['last-item' => true], 'limit' => $totallimit]
377                 );
378
379                 while ($contact = DBA::fetch($results)) {
380                         $contacts[$contact['id']] = $contact;
381                 }
382                 DBA::close($results);
383
384                 Logger::info('Contacts of contacts who are following the given user', ['uid' => $uid, 'cid' => $cid, 'count' => count($contacts)]);
385
386                 if (count($contacts) >= $totallimit) {
387                         return array_slice($contacts, $start, $limit);
388                 }
389
390                 // The query returns contacts that follow the given user but aren't followed by that user.
391                 $results = DBA::select('contact', [],
392                         ["`nurl` IN (SELECT `nurl` FROM `contact` WHERE `uid` = ? AND `rel` = ?)
393                         AND NOT `hidden` AND `uid` = ? AND `network` IN (?, ?, ?, ?)
394                         AND NOT `uri-id` IN (SELECT `uri-id` FROM `account-suggestion` WHERE `uri-id` = `contact`.`uri-id` AND `uid` = ?)",
395                         $uid, Contact::FOLLOWER, 0, 
396                         Protocol::ACTIVITYPUB, Protocol::DFRN, $diaspora, $ostatus, $uid],
397                         ['order' => ['last-item' => true], 'limit' => $totallimit]
398                 );
399
400                 while ($contact = DBA::fetch($results)) {
401                         $contacts[$contact['id']] = $contact;
402                 }
403                 DBA::close($results);
404
405                 Logger::info('Followers that are not followed by the given user', ['uid' => $uid, 'cid' => $cid, 'count' => count($contacts)]);
406
407                 if (count($contacts) >= $totallimit) {
408                         return array_slice($contacts, $start, $limit);
409                 }
410
411                 // The query returns any contact that isn't followed by that user.
412                 $results = DBA::select('contact', [],
413                         ["NOT `nurl` IN (SELECT `nurl` FROM `contact` WHERE `uid` = ? AND `rel` IN (?, ?) AND `nurl` = `nurl`)
414                         AND NOT `hidden` AND `uid` = ? AND `network` IN (?, ?, ?, ?)
415                         AND NOT `uri-id` IN (SELECT `uri-id` FROM `account-suggestion` WHERE `uri-id` = `contact`.`uri-id` AND `uid` = ?)",
416                         $uid, Contact::FRIEND, Contact::SHARING, 0, 
417                         Protocol::ACTIVITYPUB, Protocol::DFRN, $diaspora, $ostatus, $uid],
418                         ['order' => ['last-item' => true], 'limit' => $totallimit]
419                 );
420
421                 while ($contact = DBA::fetch($results)) {
422                         $contacts[$contact['id']] = $contact;
423                 }
424                 DBA::close($results);
425
426                 Logger::info('Any contact', ['uid' => $uid, 'cid' => $cid, 'count' => count($contacts)]);
427
428                 return array_slice($contacts, $start, $limit);
429         }
430
431         /**
432          * Counts all the known follows of the provided public contact
433          *
434          * @param int   $cid       Public contact id
435          * @param array $condition Additional condition on the contact table
436          * @return int
437          * @throws Exception
438          */
439         public static function countFollows(int $cid, array $condition = []): int
440         {
441                 $condition = DBA::mergeConditions($condition, [
442                         '`id` IN (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ? AND `follows`)', 
443                         $cid,
444                 ]);
445
446                 return DI::dba()->count('contact', $condition);
447         }
448
449         /**
450          * Returns a paginated list of contacts that are followed the provided public contact.
451          *
452          * @param int   $cid       Public contact id
453          * @param array $condition Additional condition on the contact table
454          * @param int   $count
455          * @param int   $offset
456          * @param bool  $shuffle
457          * @return array
458          * @throws Exception
459          */
460         public static function listFollows(int $cid, array $condition = [], int $count = 30, int $offset = 0, bool $shuffle = false)
461         {
462                 $condition = DBA::mergeConditions($condition,
463                         ['`id` IN (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ? AND `follows`)', 
464                         $cid]
465                 );
466
467                 return DI::dba()->selectToArray('contact', [], $condition,
468                         ['limit' => [$offset, $count], 'order' => [$shuffle ? 'RAND()' : 'name']]
469                 );
470         }
471
472         /**
473          * Counts all the known followers of the provided public contact
474          *
475          * @param int   $cid       Public contact id
476          * @param array $condition Additional condition on the contact table
477          * @return int
478          * @throws Exception
479          */
480         public static function countFollowers(int $cid, array $condition = [])
481         {
482                 $condition = DBA::mergeConditions($condition,
483                         ['`id` IN (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` = ? AND `follows`)',
484                         $cid]
485                 );
486
487                 return DI::dba()->count('contact', $condition);
488         }
489
490         /**
491          * Returns a paginated list of contacts that follow the provided public contact.
492          *
493          * @param int   $cid       Public contact id
494          * @param array $condition Additional condition on the contact table
495          * @param int   $count
496          * @param int   $offset
497          * @param bool  $shuffle
498          * @return array
499          * @throws Exception
500          */
501         public static function listFollowers(int $cid, array $condition = [], int $count = 30, int $offset = 0, bool $shuffle = false)
502         {
503                 $condition = DBA::mergeConditions($condition,
504                         ['`id` IN (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` = ? AND `follows`)', $cid]
505                 );
506
507                 return DI::dba()->selectToArray('contact', [], $condition,
508                         ['limit' => [$offset, $count], 'order' => [$shuffle ? 'RAND()' : 'name']]
509                 );
510         }
511
512         /**
513          * Counts the number of contacts that are known mutuals with the provided public contact.
514          *
515          * @param int   $cid       Public contact id
516          * @param array $condition Additional condition array on the contact table
517          * @return int
518          * @throws Exception
519          */
520         public static function countMutuals(int $cid, array $condition = [])
521         {
522                 $condition = DBA::mergeConditions($condition,
523                         ['`id` IN (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ? AND `follows`) 
524                         AND `id` IN (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` = ? AND `follows`)',
525                         $cid, $cid]
526                 );
527
528                 return DI::dba()->count('contact', $condition);
529         }
530
531         /**
532          * Returns a paginated list of contacts that are known mutuals with the provided public contact.
533          *
534          * @param int   $cid       Public contact id
535          * @param array $condition Additional condition on the contact table
536          * @param int   $count
537          * @param int   $offset
538          * @param bool  $shuffle
539          * @return array
540          * @throws Exception
541          */
542         public static function listMutuals(int $cid, array $condition = [], int $count = 30, int $offset = 0, bool $shuffle = false)
543         {
544                 $condition = DBA::mergeConditions($condition,
545                         ['`id` IN (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ? AND `follows`) 
546                         AND `id` IN (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` = ? AND `follows`)',
547                         $cid, $cid]
548                 );
549
550                 return DI::dba()->selectToArray('contact', [], $condition,
551                         ['limit' => [$offset, $count], 'order' => [$shuffle ? 'RAND()' : 'name']]
552                 );
553         }
554
555
556         /**
557          * Counts the number of contacts with any relationship with the provided public contact.
558          *
559          * @param int   $cid       Public contact id
560          * @param array $condition Additional condition array on the contact table
561          * @return int
562          * @throws Exception
563          */
564         public static function countAll(int $cid, array $condition = [])
565         {
566                 $condition = DBA::mergeConditions($condition,
567                         ['(`id` IN (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ? AND `follows`) 
568                         OR `id` IN (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` = ? AND `follows`))',
569                                 $cid, $cid]
570                 );
571
572                 return DI::dba()->count('contact', $condition);
573         }
574
575         /**
576          * Returns a paginated list of contacts with any relationship with the provided public contact.
577          *
578          * @param int   $cid       Public contact id
579          * @param array $condition Additional condition on the contact table
580          * @param int   $count
581          * @param int   $offset
582          * @param bool  $shuffle
583          * @return array
584          * @throws Exception
585          */
586         public static function listAll(int $cid, array $condition = [], int $count = 30, int $offset = 0, bool $shuffle = false)
587         {
588                 $condition = DBA::mergeConditions($condition,
589                         ['(`id` IN (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ? AND `follows`) 
590                         OR `id` IN (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` = ? AND `follows`))',
591                                 $cid, $cid]
592                 );
593
594                 return DI::dba()->selectToArray('contact', [], $condition,
595                         ['limit' => [$offset, $count], 'order' => [$shuffle ? 'RAND()' : 'name']]
596                 );
597         }
598
599         /**
600          * Counts the number of contacts that both provided public contacts have interacted with at least once.
601          * Interactions include follows and likes and comments on public posts.
602          *
603          * @param int   $sourceId  Public contact id
604          * @param int   $targetId  Public contact id
605          * @param array $condition Additional condition array on the contact table
606          * @return int
607          * @throws Exception
608          */
609         public static function countCommon(int $sourceId, int $targetId, array $condition = [])
610         {
611                 $condition = DBA::mergeConditions($condition,
612                         ['`id` IN (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ?) 
613                         AND `id` IN (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ?)',
614                         $sourceId, $targetId]
615                 );
616
617                 return DI::dba()->count('contact', $condition);
618         }
619
620         /**
621          * Returns a paginated list of contacts that both provided public contacts have interacted with at least once.
622          * Interactions include follows and likes and comments on public posts.
623          *
624          * @param int   $sourceId  Public contact id
625          * @param int   $targetId  Public contact id
626          * @param array $condition Additional condition on the contact table
627          * @param int   $count
628          * @param int   $offset
629          * @param bool  $shuffle
630          * @return array|bool Array on success, false on failure
631          * @throws Exception
632          */
633         public static function listCommon(int $sourceId, int $targetId, array $condition = [], int $count = 30, int $offset = 0, bool $shuffle = false)
634         {
635                 $condition = DBA::mergeConditions($condition,
636                         ["`id` IN (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ?) 
637                         AND `id` IN (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ?)",
638                         $sourceId, $targetId]
639                 );
640
641                 return DI::dba()->selectToArray('contact', [], $condition,
642                         ['limit' => [$offset, $count], 'order' => [$shuffle ? 'RAND()' : 'name']]
643                 );
644         }
645
646         /**
647          * Counts the number of contacts that are followed by both provided public contacts.
648          *
649          * @param int   $sourceId  Public contact id
650          * @param int   $targetId  Public contact id
651          * @param array $condition Additional condition array on the contact table
652          * @return int
653          * @throws Exception
654          */
655         public static function countCommonFollows(int $sourceId, int $targetId, array $condition = []): int
656         {
657                 $condition = DBA::mergeConditions($condition,
658                         ['`id` IN (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ? AND `follows`) 
659                         AND `id` IN (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ? AND `follows`)',
660                         $sourceId, $targetId]
661                 );
662
663                 return DI::dba()->count('contact', $condition);
664         }
665
666         /**
667          * Returns a paginated list of contacts that are followed by both provided public contacts.
668          *
669          * @param int   $sourceId  Public contact id
670          * @param int   $targetId  Public contact id
671          * @param array $condition Additional condition array on the contact table
672          * @param int   $count
673          * @param int   $offset
674          * @param bool  $shuffle
675          * @return array|bool Array on success, false on failure
676          * @throws Exception
677          */
678         public static function listCommonFollows(int $sourceId, int $targetId, array $condition = [], int $count = 30, int $offset = 0, bool $shuffle = false)
679         {
680                 $condition = DBA::mergeConditions($condition,
681                         ["`id` IN (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ? AND `follows`) 
682                         AND `id` IN (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ? AND `follows`)",
683                         $sourceId, $targetId]
684                 );
685
686                 return DI::dba()->selectToArray('contact', [], $condition,
687                         ['limit' => [$offset, $count], 'order' => [$shuffle ? 'RAND()' : 'name']]
688                 );
689         }
690
691         /**
692          * Counts the number of contacts that follow both provided public contacts.
693          *
694          * @param int   $sourceId  Public contact id
695          * @param int   $targetId  Public contact id
696          * @param array $condition Additional condition on the contact table
697          * @return int
698          * @throws Exception
699          */
700         public static function countCommonFollowers(int $sourceId, int $targetId, array $condition = []): int
701         {
702                 $condition = DBA::mergeConditions($condition,
703                         ["`id` IN (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` = ? AND `follows`) 
704                         AND `id` IN (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` = ? AND `follows`)",
705                         $sourceId, $targetId]
706                 );
707
708                 return DI::dba()->count('contact', $condition);
709         }
710
711         /**
712          * Returns a paginated list of contacts that follow both provided public contacts.
713          *
714          * @param int   $sourceId  Public contact id
715          * @param int   $targetId  Public contact id
716          * @param array $condition Additional condition on the contact table
717          * @param int   $count
718          * @param int   $offset
719          * @param bool  $shuffle
720          * @return array|bool Array on success, false on failure
721          * @throws Exception
722          */
723         public static function listCommonFollowers(int $sourceId, int $targetId, array $condition = [], int $count = 30, int $offset = 0, bool $shuffle = false)
724         {
725                 $condition = DBA::mergeConditions($condition,
726                         ["`id` IN (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` = ? AND `follows`) 
727                         AND `id` IN (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` = ? AND `follows`)",
728                         $sourceId, $targetId]
729                 );
730
731                 return DI::dba()->selectToArray('contact', [], $condition,
732                         ['limit' => [$offset, $count],  'order' => [$shuffle ? 'RAND()' : 'name']]
733                 );
734         }
735 }