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