]> git.mxchange.org Git - friendica.git/blob - src/Model/Contact/Relation.php
Changes after code review
[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          * Update contact suggestions for a given user
265          *
266          * @param integer $uid
267          * @return void
268          */
269         static public function updateCachedSuggestions(int $uid)
270         {
271                 if (DI::pConfig()->get($uid, 'suggestion', 'last_update') + 3600 > time()) {
272                         return;
273                 }
274
275                 DBA::delete('account-suggestion', ['uid' => $uid, 'ignore' => false]);
276
277                 foreach (self::getSuggestions($uid) as $contact) {
278                         DBA::insert('account-suggestion', ['uri-id' => $contact['uri-id'], 'uid' => $uid, 'level' => 1], Database::INSERT_IGNORE);
279                 }
280
281                 DI::pConfig()->set($uid, 'suggestion', 'last_update', time());
282         }
283
284         /**
285          * Returns a cached array of suggested contacts for given user id
286          *
287          * @param int $uid   User id
288          * @param int $start optional, default 0
289          * @param int $limit optional, default 80
290          * @return array
291          */
292         static public function getCachedSuggestions(int $uid, int $start = 0, int $limit = 80): array
293         {
294                 $condition = ["`uid` = ? AND `uri-id` IN (SELECT `uri-id` FROM `account-suggestion` WHERE NOT `ignore` AND `uid` = ?)", 0, $uid];
295                 $params = ['limit' => [$start, $limit]];
296                 $cached = DBA::selectToArray('contact', [], $condition, $params);
297
298                 if (!empty($cached)) {
299                         return $cached;
300                 } else {
301                         return self::getSuggestions($uid, $start, $limit);
302                 }
303         }
304
305         /**
306          * Returns an array of suggested contacts for given user id
307          *
308          * @param int $uid   User id
309          * @param int $start optional, default 0
310          * @param int $limit optional, default 80
311          * @return array
312          */
313         static public function getSuggestions(int $uid, int $start = 0, int $limit = 80): array
314         {
315                 $cid = Contact::getPublicIdByUserId($uid);
316                 $totallimit = $start + $limit;
317                 $contacts = [];
318
319                 Logger::info('Collecting suggestions', ['uid' => $uid, 'cid' => $cid, 'start' => $start, 'limit' => $limit]);
320
321                 $diaspora = DI::config()->get('system', 'diaspora_enabled') ? Protocol::DIASPORA : Protocol::ACTIVITYPUB;
322                 $ostatus = !DI::config()->get('system', 'ostatus_disabled') ? Protocol::OSTATUS : Protocol::ACTIVITYPUB;
323
324                 // The query returns contacts where contacts interacted with whom the given user follows.
325                 // Contacts who already are in the user's contact table are ignored.
326                 $results = DBA::select('contact', [], ["`id` IN (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` IN
327                                 (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` = ?)
328                                         AND NOT `cid` IN (SELECT `id` FROM `contact` WHERE `uid` = ? AND `nurl` IN
329                                                 (SELECT `nurl` FROM `contact` WHERE `uid` = ? AND `rel` IN (?, ?))) AND `id` = `cid`)
330                         AND NOT `hidden` AND `network` IN (?, ?, ?, ?)
331                         AND NOT `uri-id` IN (SELECT `uri-id` FROM `account-suggestion` WHERE `uri-id` = `contact`.`uri-id` AND `uid` = ?)",
332                         $cid,
333                         0,
334                         $uid, Contact::FRIEND, Contact::SHARING,
335                         Protocol::ACTIVITYPUB, Protocol::DFRN, $diaspora, $ostatus, $uid
336                         ], [
337                                 'order' => ['last-item' => true],
338                                 'limit' => $totallimit,
339                         ]
340                 );
341
342                 while ($contact = DBA::fetch($results)) {
343                         $contacts[$contact['id']] = $contact;
344                 }
345
346                 DBA::close($results);
347
348                 Logger::info('Contacts of contacts who are followed by the given user', ['uid' => $uid, 'cid' => $cid, 'count' => count($contacts)]);
349
350                 if (count($contacts) >= $totallimit) {
351                         return array_slice($contacts, $start, $limit);
352                 }
353
354                 // The query returns contacts where contacts interacted with whom also interacted with the given user.
355                 // Contacts who already are in the user's contact table are ignored.
356                 $results = DBA::select('contact', [],
357                         ["`id` IN (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` IN
358                                 (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ?)
359                                         AND NOT `cid` IN (SELECT `id` FROM `contact` WHERE `uid` = ? AND `nurl` IN
360                                                 (SELECT `nurl` FROM `contact` WHERE `uid` = ? AND `rel` IN (?, ?))) AND `id` = `cid`)
361                         AND NOT `hidden` AND `network` IN (?, ?, ?, ?)
362                         AND NOT `uri-id` IN (SELECT `uri-id` FROM `account-suggestion` WHERE `uri-id` = `contact`.`uri-id` AND `uid` = ?)",
363                         $cid, 0, $uid, Contact::FRIEND, Contact::SHARING,
364                         Protocol::ACTIVITYPUB, Protocol::DFRN, $diaspora, $ostatus, $uid],
365                         ['order' => ['last-item' => true], 'limit' => $totallimit]
366                 );
367
368                 while ($contact = DBA::fetch($results)) {
369                         $contacts[$contact['id']] = $contact;
370                 }
371                 DBA::close($results);
372
373                 Logger::info('Contacts of contacts who are following the given user', ['uid' => $uid, 'cid' => $cid, 'count' => count($contacts)]);
374
375                 if (count($contacts) >= $totallimit) {
376                         return array_slice($contacts, $start, $limit);
377                 }
378
379                 // The query returns contacts that follow the given user but aren't followed by that user.
380                 $results = DBA::select('contact', [],
381                         ["`nurl` IN (SELECT `nurl` FROM `contact` WHERE `uid` = ? AND `rel` = ?)
382                         AND NOT `hidden` AND `uid` = ? AND `network` IN (?, ?, ?, ?)
383                         AND NOT `uri-id` IN (SELECT `uri-id` FROM `account-suggestion` WHERE `uri-id` = `contact`.`uri-id` AND `uid` = ?)",
384                         $uid, Contact::FOLLOWER, 0, 
385                         Protocol::ACTIVITYPUB, Protocol::DFRN, $diaspora, $ostatus, $uid],
386                         ['order' => ['last-item' => true], 'limit' => $totallimit]
387                 );
388
389                 while ($contact = DBA::fetch($results)) {
390                         $contacts[$contact['id']] = $contact;
391                 }
392                 DBA::close($results);
393
394                 Logger::info('Followers that are not followed by the given user', ['uid' => $uid, 'cid' => $cid, 'count' => count($contacts)]);
395
396                 if (count($contacts) >= $totallimit) {
397                         return array_slice($contacts, $start, $limit);
398                 }
399
400                 // The query returns any contact that isn't followed by that user.
401                 $results = DBA::select('contact', [],
402                         ["NOT `nurl` IN (SELECT `nurl` FROM `contact` WHERE `uid` = ? AND `rel` IN (?, ?) AND `nurl` = `nurl`)
403                         AND NOT `hidden` AND `uid` = ? AND `network` IN (?, ?, ?, ?)
404                         AND NOT `uri-id` IN (SELECT `uri-id` FROM `account-suggestion` WHERE `uri-id` = `contact`.`uri-id` AND `uid` = ?)",
405                         $uid, Contact::FRIEND, Contact::SHARING, 0, 
406                         Protocol::ACTIVITYPUB, Protocol::DFRN, $diaspora, $ostatus, $uid],
407                         ['order' => ['last-item' => true], 'limit' => $totallimit]
408                 );
409
410                 while ($contact = DBA::fetch($results)) {
411                         $contacts[$contact['id']] = $contact;
412                 }
413                 DBA::close($results);
414
415                 Logger::info('Any contact', ['uid' => $uid, 'cid' => $cid, 'count' => count($contacts)]);
416
417                 return array_slice($contacts, $start, $limit);
418         }
419
420         /**
421          * Counts all the known follows of the provided public contact
422          *
423          * @param int   $cid       Public contact id
424          * @param array $condition Additional condition on the contact table
425          * @return int
426          * @throws Exception
427          */
428         public static function countFollows(int $cid, array $condition = []): int
429         {
430                 $condition = DBA::mergeConditions($condition, [
431                         '`id` IN (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ? AND `follows`)', 
432                         $cid,
433                 ]);
434
435                 return DI::dba()->count('contact', $condition);
436         }
437
438         /**
439          * Returns a paginated list of contacts that are followed the provided public contact.
440          *
441          * @param int   $cid       Public contact id
442          * @param array $condition Additional condition on the contact table
443          * @param int   $count
444          * @param int   $offset
445          * @param bool  $shuffle
446          * @return array
447          * @throws Exception
448          */
449         public static function listFollows(int $cid, array $condition = [], int $count = 30, int $offset = 0, bool $shuffle = false)
450         {
451                 $condition = DBA::mergeConditions($condition,
452                         ['`id` IN (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ? AND `follows`)', 
453                         $cid]
454                 );
455
456                 return DI::dba()->selectToArray('contact', [], $condition,
457                         ['limit' => [$offset, $count], 'order' => [$shuffle ? 'RAND()' : 'name']]
458                 );
459         }
460
461         /**
462          * Counts all the known followers of the provided public contact
463          *
464          * @param int   $cid       Public contact id
465          * @param array $condition Additional condition on the contact table
466          * @return int
467          * @throws Exception
468          */
469         public static function countFollowers(int $cid, array $condition = [])
470         {
471                 $condition = DBA::mergeConditions($condition,
472                         ['`id` IN (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` = ? AND `follows`)',
473                         $cid]
474                 );
475
476                 return DI::dba()->count('contact', $condition);
477         }
478
479         /**
480          * Returns a paginated list of contacts that follow the provided public contact.
481          *
482          * @param int   $cid       Public contact id
483          * @param array $condition Additional condition on the contact table
484          * @param int   $count
485          * @param int   $offset
486          * @param bool  $shuffle
487          * @return array
488          * @throws Exception
489          */
490         public static function listFollowers(int $cid, array $condition = [], int $count = 30, int $offset = 0, bool $shuffle = false)
491         {
492                 $condition = DBA::mergeConditions($condition,
493                         ['`id` IN (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` = ? AND `follows`)', $cid]
494                 );
495
496                 return DI::dba()->selectToArray('contact', [], $condition,
497                         ['limit' => [$offset, $count], 'order' => [$shuffle ? 'RAND()' : 'name']]
498                 );
499         }
500
501         /**
502          * Counts the number of contacts that are known mutuals with the provided public contact.
503          *
504          * @param int   $cid       Public contact id
505          * @param array $condition Additional condition array on the contact table
506          * @return int
507          * @throws Exception
508          */
509         public static function countMutuals(int $cid, array $condition = [])
510         {
511                 $condition = DBA::mergeConditions($condition,
512                         ['`id` IN (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ? AND `follows`) 
513                         AND `id` IN (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` = ? AND `follows`)',
514                         $cid, $cid]
515                 );
516
517                 return DI::dba()->count('contact', $condition);
518         }
519
520         /**
521          * Returns a paginated list of contacts that are known mutuals with the provided public contact.
522          *
523          * @param int   $cid       Public contact id
524          * @param array $condition Additional condition on the contact table
525          * @param int   $count
526          * @param int   $offset
527          * @param bool  $shuffle
528          * @return array
529          * @throws Exception
530          */
531         public static function listMutuals(int $cid, array $condition = [], int $count = 30, int $offset = 0, bool $shuffle = false)
532         {
533                 $condition = DBA::mergeConditions($condition,
534                         ['`id` IN (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ? AND `follows`) 
535                         AND `id` IN (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` = ? AND `follows`)',
536                         $cid, $cid]
537                 );
538
539                 return DI::dba()->selectToArray('contact', [], $condition,
540                         ['limit' => [$offset, $count], 'order' => [$shuffle ? 'RAND()' : 'name']]
541                 );
542         }
543
544
545         /**
546          * Counts the number of contacts with any relationship with the provided public contact.
547          *
548          * @param int   $cid       Public contact id
549          * @param array $condition Additional condition array on the contact table
550          * @return int
551          * @throws Exception
552          */
553         public static function countAll(int $cid, array $condition = [])
554         {
555                 $condition = DBA::mergeConditions($condition,
556                         ['(`id` IN (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ? AND `follows`) 
557                         OR `id` IN (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` = ? AND `follows`))',
558                                 $cid, $cid]
559                 );
560
561                 return DI::dba()->count('contact', $condition);
562         }
563
564         /**
565          * Returns a paginated list of contacts with any relationship with the provided public contact.
566          *
567          * @param int   $cid       Public contact id
568          * @param array $condition Additional condition on the contact table
569          * @param int   $count
570          * @param int   $offset
571          * @param bool  $shuffle
572          * @return array
573          * @throws Exception
574          */
575         public static function listAll(int $cid, array $condition = [], int $count = 30, int $offset = 0, bool $shuffle = false)
576         {
577                 $condition = DBA::mergeConditions($condition,
578                         ['(`id` IN (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ? AND `follows`) 
579                         OR `id` IN (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` = ? AND `follows`))',
580                                 $cid, $cid]
581                 );
582
583                 return DI::dba()->selectToArray('contact', [], $condition,
584                         ['limit' => [$offset, $count], 'order' => [$shuffle ? 'RAND()' : 'name']]
585                 );
586         }
587
588         /**
589          * Counts the number of contacts that both provided public contacts have interacted with at least once.
590          * Interactions include follows and likes and comments on public posts.
591          *
592          * @param int   $sourceId  Public contact id
593          * @param int   $targetId  Public contact id
594          * @param array $condition Additional condition array on the contact table
595          * @return int
596          * @throws Exception
597          */
598         public static function countCommon(int $sourceId, int $targetId, array $condition = [])
599         {
600                 $condition = DBA::mergeConditions($condition,
601                         ['`id` IN (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ?) 
602                         AND `id` IN (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ?)',
603                         $sourceId, $targetId]
604                 );
605
606                 return DI::dba()->count('contact', $condition);
607         }
608
609         /**
610          * Returns a paginated list of contacts that both provided public contacts have interacted with at least once.
611          * Interactions include follows and likes and comments on public posts.
612          *
613          * @param int   $sourceId  Public contact id
614          * @param int   $targetId  Public contact id
615          * @param array $condition Additional condition on the contact table
616          * @param int   $count
617          * @param int   $offset
618          * @param bool  $shuffle
619          * @return array|bool Array on success, false on failure
620          * @throws Exception
621          */
622         public static function listCommon(int $sourceId, int $targetId, array $condition = [], int $count = 30, int $offset = 0, bool $shuffle = false)
623         {
624                 $condition = DBA::mergeConditions($condition,
625                         ["`id` IN (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ?) 
626                         AND `id` IN (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ?)",
627                         $sourceId, $targetId]
628                 );
629
630                 return DI::dba()->selectToArray('contact', [], $condition,
631                         ['limit' => [$offset, $count], 'order' => [$shuffle ? 'RAND()' : 'name']]
632                 );
633         }
634
635         /**
636          * Counts the number of contacts that are followed by both provided public contacts.
637          *
638          * @param int   $sourceId  Public contact id
639          * @param int   $targetId  Public contact id
640          * @param array $condition Additional condition array on the contact table
641          * @return int
642          * @throws Exception
643          */
644         public static function countCommonFollows(int $sourceId, int $targetId, array $condition = []): int
645         {
646                 $condition = DBA::mergeConditions($condition,
647                         ['`id` IN (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ? AND `follows`) 
648                         AND `id` IN (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ? AND `follows`)',
649                         $sourceId, $targetId]
650                 );
651
652                 return DI::dba()->count('contact', $condition);
653         }
654
655         /**
656          * Returns a paginated list of contacts that are followed by both provided public contacts.
657          *
658          * @param int   $sourceId  Public contact id
659          * @param int   $targetId  Public contact id
660          * @param array $condition Additional condition array on the contact table
661          * @param int   $count
662          * @param int   $offset
663          * @param bool  $shuffle
664          * @return array|bool Array on success, false on failure
665          * @throws Exception
666          */
667         public static function listCommonFollows(int $sourceId, int $targetId, array $condition = [], int $count = 30, int $offset = 0, bool $shuffle = false)
668         {
669                 $condition = DBA::mergeConditions($condition,
670                         ["`id` IN (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ? AND `follows`) 
671                         AND `id` IN (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ? AND `follows`)",
672                         $sourceId, $targetId]
673                 );
674
675                 return DI::dba()->selectToArray('contact', [], $condition,
676                         ['limit' => [$offset, $count], 'order' => [$shuffle ? 'RAND()' : 'name']]
677                 );
678         }
679
680         /**
681          * Counts the number of contacts that follow both provided public contacts.
682          *
683          * @param int   $sourceId  Public contact id
684          * @param int   $targetId  Public contact id
685          * @param array $condition Additional condition on the contact table
686          * @return int
687          * @throws Exception
688          */
689         public static function countCommonFollowers(int $sourceId, int $targetId, array $condition = []): int
690         {
691                 $condition = DBA::mergeConditions($condition,
692                         ["`id` IN (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` = ? AND `follows`) 
693                         AND `id` IN (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` = ? AND `follows`)",
694                         $sourceId, $targetId]
695                 );
696
697                 return DI::dba()->count('contact', $condition);
698         }
699
700         /**
701          * Returns a paginated list of contacts that follow both provided public contacts.
702          *
703          * @param int   $sourceId  Public contact id
704          * @param int   $targetId  Public contact id
705          * @param array $condition Additional condition on the contact table
706          * @param int   $count
707          * @param int   $offset
708          * @param bool  $shuffle
709          * @return array|bool Array on success, false on failure
710          * @throws Exception
711          */
712         public static function listCommonFollowers(int $sourceId, int $targetId, array $condition = [], int $count = 30, int $offset = 0, bool $shuffle = false)
713         {
714                 $condition = DBA::mergeConditions($condition,
715                         ["`id` IN (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` = ? AND `follows`) 
716                         AND `id` IN (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` = ? AND `follows`)",
717                         $sourceId, $targetId]
718                 );
719
720                 return DI::dba()->selectToArray('contact', [], $condition,
721                         ['limit' => [$offset, $count],  'order' => [$shuffle ? 'RAND()' : 'name']]
722                 );
723         }
724 }