]> git.mxchange.org Git - friendica.git/blob - src/Model/Contact/Relation.php
More logging for the contact discovery
[friendica.git] / src / Model / Contact / Relation.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2021, 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::notice('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                         DBA::update('contact', ['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                 DBA::update('contact', ['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)
178         {
179                 $list = [];
180                 $profile = Profile::getByUID($uid);
181                 if (!empty($profile['hide-friends'])) {
182                         return $list;
183                 }
184
185                 $condition = ['rel' => $rel, 'uid' => $uid, 'self' => false, 'deleted' => false,
186                         'hidden' => false, 'archive' => false, 'pending' => false];
187                 $condition = DBA::mergeConditions($condition, ["`url` IN (SELECT `url` FROM `apcontact`)"]);
188                 $contacts = DBA::select('contact', ['url'], $condition);
189                 while ($contact = DBA::fetch($contacts)) {
190                         $list[] = $contact['url'];
191                 }
192                 DBA::close($contacts);
193
194                 return $list;
195         }
196
197         /**
198          * Tests if a given contact url is discoverable
199          *
200          * @param string $url     Contact url
201          * @param array  $contact Contact array
202          * @return boolean True if contact is discoverable
203          */
204         public static function isDiscoverable(string $url, array $contact = [])
205         {
206                 $contact_discovery = DI::config()->get('system', 'contact_discovery');
207
208                 if ($contact_discovery == self::DISCOVERY_NONE) {
209                         return false;
210                 }
211
212                 if (empty($contact)) {
213                         $contact = Contact::getByURL($url, false);
214                 }
215
216                 if (empty($contact)) {
217                         return false;
218                 }
219
220                 if ($contact['last-discovery'] > DateTimeFormat::utc('now - 1 month')) {
221                         Logger::info('No discovery - Last was less than a month ago.', ['id' => $contact['id'], 'url' => $url, 'discovery' => $contact['last-discovery']]);
222                         return false;
223                 }
224
225                 if ($contact_discovery != self::DISCOVERY_ALL) {
226                         $local = DBA::exists('contact', ["`nurl` = ? AND `uid` != ?", Strings::normaliseLink($url), 0]);
227                         if (($contact_discovery == self::DISCOVERY_LOCAL) && !$local) {
228                                 Logger::info('No discovery - This contact is not followed/following locally.', ['id' => $contact['id'], 'url' => $url]);
229                                 return false;
230                         }
231
232                         if ($contact_discovery == self::DISCOVERY_INTERACTOR) {
233                                 $interactor = DBA::exists('contact-relation', ["`relation-cid` = ? AND `last-interaction` > ?", $contact['id'], DBA::NULL_DATETIME]);
234                                 if (!$local && !$interactor) {
235                                         Logger::info('No discovery - This contact is not interacting locally.', ['id' => $contact['id'], 'url' => $url]);
236                                         return false;
237                                 }
238                         }
239                 } elseif ($contact['created'] > DateTimeFormat::utc('now - 1 day')) {
240                         // Newly created contacts are not discovered to avoid DDoS attacks
241                         Logger::info('No discovery - Contact record is less than a day old.', ['id' => $contact['id'], 'url' => $url, 'discovery' => $contact['created']]);
242                         return false;
243                 }
244
245                 if (!in_array($contact['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::OSTATUS])) {
246                         $apcontact = APContact::getByURL($url, false);
247                         if (empty($apcontact)) {
248                                 Logger::info('No discovery - The contact does not seem to speak ActivityPub.', ['id' => $contact['id'], 'url' => $url, 'network' => $contact['network']]);
249                                 return false;
250                         }
251                 }
252
253                 return true;
254         }
255
256         /**
257          * @param int $uid   user
258          * @param int $start optional, default 0
259          * @param int $limit optional, default 80
260          * @return array
261          */
262         static public function getSuggestions(int $uid, int $start = 0, int $limit = 80)
263         {
264                 $cid = Contact::getPublicIdByUserId($uid);
265                 $totallimit = $start + $limit;
266                 $contacts = [];
267
268                 Logger::info('Collecting suggestions', ['uid' => $uid, 'cid' => $cid, 'start' => $start, 'limit' => $limit]);
269
270                 $diaspora = DI::config()->get('system', 'diaspora_enabled') ? Protocol::DIASPORA : Protocol::ACTIVITYPUB;
271                 $ostatus = !DI::config()->get('system', 'ostatus_disabled') ? Protocol::OSTATUS : Protocol::ACTIVITYPUB;
272
273                 // The query returns contacts where contacts interacted with whom the given user follows.
274                 // Contacts who already are in the user's contact table are ignored.
275                 $results = DBA::select('contact', [],
276                         ["`id` IN (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` IN
277                                 (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` = ?)
278                                         AND NOT `cid` IN (SELECT `id` FROM `contact` WHERE `uid` = ? AND `nurl` IN
279                                                 (SELECT `nurl` FROM `contact` WHERE `uid` = ? AND `rel` IN (?, ?))))
280                         AND NOT `hidden` AND `network` IN (?, ?, ?, ?)",
281                         $cid, 0, $uid, Contact::FRIEND, Contact::SHARING,
282                         Protocol::ACTIVITYPUB, Protocol::DFRN, $diaspora, $ostatus],
283                         ['order' => ['last-item' => true], 'limit' => $totallimit]
284                 );
285
286                 while ($contact = DBA::fetch($results)) {
287                         $contacts[$contact['id']] = $contact;
288                 }
289                 DBA::close($results);
290
291                 Logger::info('Contacts of contacts who are followed by the given user', ['uid' => $uid, 'cid' => $cid, 'count' => count($contacts)]);
292
293                 if (count($contacts) >= $totallimit) {
294                         return array_slice($contacts, $start, $limit);
295                 }
296
297                 // The query returns contacts where contacts interacted with whom also interacted with the given user.
298                 // Contacts who already are in the user's contact table are ignored.
299                 $results = DBA::select('contact', [],
300                         ["`id` IN (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` IN
301                                 (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ?)
302                                         AND NOT `cid` IN (SELECT `id` FROM `contact` WHERE `uid` = ? AND `nurl` IN
303                                                 (SELECT `nurl` FROM `contact` WHERE `uid` = ? AND `rel` IN (?, ?))))
304                         AND NOT `hidden` AND `network` IN (?, ?, ?, ?)",
305                         $cid, 0, $uid, Contact::FRIEND, Contact::SHARING,
306                         Protocol::ACTIVITYPUB, Protocol::DFRN, $diaspora, $ostatus],
307                         ['order' => ['last-item' => true], 'limit' => $totallimit]
308                 );
309
310                 while ($contact = DBA::fetch($results)) {
311                         $contacts[$contact['id']] = $contact;
312                 }
313                 DBA::close($results);
314
315                 Logger::info('Contacts of contacts who are following the given user', ['uid' => $uid, 'cid' => $cid, 'count' => count($contacts)]);
316
317                 if (count($contacts) >= $totallimit) {
318                         return array_slice($contacts, $start, $limit);
319                 }
320
321                 // The query returns contacts that follow the given user but aren't followed by that user.
322                 $results = DBA::select('contact', [],
323                         ["`nurl` IN (SELECT `nurl` FROM `contact` WHERE `uid` = ? AND `rel` = ?)
324                         AND NOT `hidden` AND `uid` = ? AND `network` IN (?, ?, ?, ?)",
325                         $uid, Contact::FOLLOWER, 0, 
326                         Protocol::ACTIVITYPUB, Protocol::DFRN, $diaspora, $ostatus],
327                         ['order' => ['last-item' => true], 'limit' => $totallimit]
328                 );
329
330                 while ($contact = DBA::fetch($results)) {
331                         $contacts[$contact['id']] = $contact;
332                 }
333                 DBA::close($results);
334
335                 Logger::info('Followers that are not followed by the given user', ['uid' => $uid, 'cid' => $cid, 'count' => count($contacts)]);
336
337                 if (count($contacts) >= $totallimit) {
338                         return array_slice($contacts, $start, $limit);
339                 }
340
341                 // The query returns any contact that isn't followed by that user.
342                 $results = DBA::select('contact', [],
343                         ["NOT `nurl` IN (SELECT `nurl` FROM `contact` WHERE `uid` = ? AND `rel` IN (?, ?))
344                         AND NOT `hidden` AND `uid` = ? AND `network` IN (?, ?, ?, ?)",
345                         $uid, Contact::FRIEND, Contact::SHARING, 0, 
346                         Protocol::ACTIVITYPUB, Protocol::DFRN, $diaspora, $ostatus],
347                         ['order' => ['last-item' => true], 'limit' => $totallimit]
348                 );
349
350                 while ($contact = DBA::fetch($results)) {
351                         $contacts[$contact['id']] = $contact;
352                 }
353                 DBA::close($results);
354
355                 Logger::info('Any contact', ['uid' => $uid, 'cid' => $cid, 'count' => count($contacts)]);
356
357                 return array_slice($contacts, $start, $limit);
358         }
359
360         /**
361          * Counts all the known follows of the provided public contact
362          *
363          * @param int   $cid       Public contact id
364          * @param array $condition Additional condition on the contact table
365          * @return int
366          * @throws Exception
367          */
368         public static function countFollows(int $cid, array $condition = [])
369         {
370                 $condition = DBA::mergeConditions($condition,
371                         ['`id` IN (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ? AND `follows`)', 
372                         $cid]
373                 );
374
375                 return DI::dba()->count('contact', $condition);
376         }
377
378         /**
379          * Returns a paginated list of contacts that are followed the provided public contact.
380          *
381          * @param int   $cid       Public contact id
382          * @param array $condition Additional condition on the contact table
383          * @param int   $count
384          * @param int   $offset
385          * @param bool  $shuffle
386          * @return array
387          * @throws Exception
388          */
389         public static function listFollows(int $cid, array $condition = [], int $count = 30, int $offset = 0, bool $shuffle = false)
390         {
391                 $condition = DBA::mergeConditions($condition,
392                         ['`id` IN (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ? AND `follows`)', 
393                         $cid]
394                 );
395
396                 return DI::dba()->selectToArray('contact', [], $condition,
397                         ['limit' => [$offset, $count], 'order' => [$shuffle ? 'RAND()' : 'name']]
398                 );
399         }
400
401         /**
402          * Counts all the known followers of the provided public contact
403          *
404          * @param int   $cid       Public contact id
405          * @param array $condition Additional condition on the contact table
406          * @return int
407          * @throws Exception
408          */
409         public static function countFollowers(int $cid, array $condition = [])
410         {
411                 $condition = DBA::mergeConditions($condition,
412                         ['`id` IN (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` = ? AND `follows`)',
413                         $cid]
414                 );
415
416                 return DI::dba()->count('contact', $condition);
417         }
418
419         /**
420          * Returns a paginated list of contacts that follow the provided public contact.
421          *
422          * @param int   $cid       Public contact id
423          * @param array $condition Additional condition on the contact table
424          * @param int   $count
425          * @param int   $offset
426          * @param bool  $shuffle
427          * @return array
428          * @throws Exception
429          */
430         public static function listFollowers(int $cid, array $condition = [], int $count = 30, int $offset = 0, bool $shuffle = false)
431         {
432                 $condition = DBA::mergeConditions($condition,
433                         ['`id` IN (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` = ? AND `follows`)', $cid]
434                 );
435
436                 return DI::dba()->selectToArray('contact', [], $condition,
437                         ['limit' => [$offset, $count], 'order' => [$shuffle ? 'RAND()' : 'name']]
438                 );
439         }
440
441         /**
442          * Counts the number of contacts that are known mutuals with the provided public contact.
443          *
444          * @param int   $cid       Public contact id
445          * @param array $condition Additional condition array on the contact table
446          * @return int
447          * @throws Exception
448          */
449         public static function countMutuals(int $cid, array $condition = [])
450         {
451                 $condition = DBA::mergeConditions($condition,
452                         ['`id` IN (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ? AND `follows`) 
453                         AND `id` IN (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` = ? AND `follows`)',
454                         $cid, $cid]
455                 );
456
457                 return DI::dba()->count('contact', $condition);
458         }
459
460         /**
461          * Returns a paginated list of contacts that are known mutuals with the provided public contact.
462          *
463          * @param int   $cid       Public contact id
464          * @param array $condition Additional condition on the contact table
465          * @param int   $count
466          * @param int   $offset
467          * @param bool  $shuffle
468          * @return array
469          * @throws Exception
470          */
471         public static function listMutuals(int $cid, array $condition = [], int $count = 30, int $offset = 0, bool $shuffle = false)
472         {
473                 $condition = DBA::mergeConditions($condition,
474                         ['`id` IN (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ? AND `follows`) 
475                         AND `id` IN (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` = ? AND `follows`)',
476                         $cid, $cid]
477                 );
478
479                 return DI::dba()->selectToArray('contact', [], $condition,
480                         ['limit' => [$offset, $count], 'order' => [$shuffle ? 'RAND()' : 'name']]
481                 );
482         }
483
484
485         /**
486          * Counts the number of contacts with any relationship with the provided public contact.
487          *
488          * @param int   $cid       Public contact id
489          * @param array $condition Additional condition array on the contact table
490          * @return int
491          * @throws Exception
492          */
493         public static function countAll(int $cid, array $condition = [])
494         {
495                 $condition = DBA::mergeConditions($condition,
496                         ['(`id` IN (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ? AND `follows`) 
497                         OR `id` IN (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` = ? AND `follows`))',
498                                 $cid, $cid]
499                 );
500
501                 return DI::dba()->count('contact', $condition);
502         }
503
504         /**
505          * Returns a paginated list of contacts with any relationship with the provided public contact.
506          *
507          * @param int   $cid       Public contact id
508          * @param array $condition Additional condition on the contact table
509          * @param int   $count
510          * @param int   $offset
511          * @param bool  $shuffle
512          * @return array
513          * @throws Exception
514          */
515         public static function listAll(int $cid, array $condition = [], int $count = 30, int $offset = 0, bool $shuffle = false)
516         {
517                 $condition = DBA::mergeConditions($condition,
518                         ['(`id` IN (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ? AND `follows`) 
519                         OR `id` IN (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` = ? AND `follows`))',
520                                 $cid, $cid]
521                 );
522
523                 return DI::dba()->selectToArray('contact', [], $condition,
524                         ['limit' => [$offset, $count], 'order' => [$shuffle ? 'RAND()' : 'name']]
525                 );
526         }
527
528         /**
529          * Counts the number of contacts that both provided public contacts have interacted with at least once.
530          * Interactions include follows and likes and comments on public posts.
531          *
532          * @param int   $sourceId  Public contact id
533          * @param int   $targetId  Public contact id
534          * @param array $condition Additional condition array on the contact table
535          * @return int
536          * @throws Exception
537          */
538         public static function countCommon(int $sourceId, int $targetId, array $condition = [])
539         {
540                 $condition = DBA::mergeConditions($condition,
541                         ['`id` IN (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ?) 
542                         AND `id` IN (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ?)',
543                         $sourceId, $targetId]
544                 );
545
546                 return DI::dba()->count('contact', $condition);
547         }
548
549         /**
550          * Returns a paginated list of contacts that both provided public contacts have interacted with at least once.
551          * Interactions include follows and likes and comments on public posts.
552          *
553          * @param int   $sourceId  Public contact id
554          * @param int   $targetId  Public contact id
555          * @param array $condition Additional condition on the contact table
556          * @param int   $count
557          * @param int   $offset
558          * @param bool  $shuffle
559          * @return array
560          * @throws Exception
561          */
562         public static function listCommon(int $sourceId, int $targetId, array $condition = [], int $count = 30, int $offset = 0, bool $shuffle = false)
563         {
564                 $condition = DBA::mergeConditions($condition,
565                         ["`id` IN (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ?) 
566                         AND `id` IN (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ?)",
567                         $sourceId, $targetId]
568                 );
569
570                 return DI::dba()->selectToArray('contact', [], $condition,
571                         ['limit' => [$offset, $count], 'order' => [$shuffle ? 'RAND()' : 'name']]
572                 );
573         }
574
575         /**
576          * Counts the number of contacts that are followed by both provided public contacts.
577          *
578          * @param int   $sourceId  Public contact id
579          * @param int   $targetId  Public contact id
580          * @param array $condition Additional condition array on the contact table
581          * @return int
582          * @throws Exception
583          */
584         public static function countCommonFollows(int $sourceId, int $targetId, array $condition = [])
585         {
586                 $condition = DBA::mergeConditions($condition,
587                         ['`id` IN (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ? AND `follows`) 
588                         AND `id` IN (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ? AND `follows`)',
589                         $sourceId, $targetId]
590                 );
591
592                 return DI::dba()->count('contact', $condition);
593         }
594
595         /**
596          * Returns a paginated list of contacts that are followed by both provided public contacts.
597          *
598          * @param int   $sourceId  Public contact id
599          * @param int   $targetId  Public contact id
600          * @param array $condition Additional condition array on the contact table
601          * @param int   $count
602          * @param int   $offset
603          * @param bool  $shuffle
604          * @return array
605          * @throws Exception
606          */
607         public static function listCommonFollows(int $sourceId, int $targetId, array $condition = [], int $count = 30, int $offset = 0, bool $shuffle = false)
608         {
609                 $condition = DBA::mergeConditions($condition,
610                         ["`id` IN (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ? AND `follows`) 
611                         AND `id` IN (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ? AND `follows`)",
612                         $sourceId, $targetId]
613                 );
614
615                 return DI::dba()->selectToArray('contact', [], $condition,
616                         ['limit' => [$offset, $count], 'order' => [$shuffle ? 'RAND()' : 'name']]
617                 );
618         }
619
620         /**
621          * Counts the number of contacts that follow both provided public contacts.
622          *
623          * @param int   $sourceId  Public contact id
624          * @param int   $targetId  Public contact id
625          * @param array $condition Additional condition on the contact table
626          * @return int
627          * @throws Exception
628          */
629         public static function countCommonFollowers(int $sourceId, int $targetId, array $condition = [])
630         {
631                 $condition = DBA::mergeConditions($condition,
632                         ["`id` IN (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` = ? AND `follows`) 
633                         AND `id` IN (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` = ? AND `follows`)",
634                         $sourceId, $targetId]
635                 );
636
637                 return DI::dba()->count('contact', $condition);
638         }
639
640         /**
641          * Returns a paginated list of contacts that follow both provided public contacts.
642          *
643          * @param int   $sourceId  Public contact id
644          * @param int   $targetId  Public contact id
645          * @param array $condition Additional condition on the contact table
646          * @param int   $count
647          * @param int   $offset
648          * @param bool  $shuffle
649          * @return array
650          * @throws Exception
651          */
652         public static function listCommonFollowers(int $sourceId, int $targetId, array $condition = [], int $count = 30, int $offset = 0, bool $shuffle = false)
653         {
654                 $condition = DBA::mergeConditions($condition,
655                         ["`id` IN (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` = ? AND `follows`) 
656                         AND `id` IN (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` = ? AND `follows`)",
657                         $sourceId, $targetId]
658                 );
659
660                 return DI::dba()->selectToArray('contact', [], $condition,
661                         ['limit' => [$offset, $count],  'order' => [$shuffle ? 'RAND()' : 'name']]
662                 );
663         }
664 }