]> git.mxchange.org Git - friendica.git/blob - src/Model/Contact.php
Merge pull request #8952 from annando/contact-template
[friendica.git] / src / Model / Contact.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2020, Friendica
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;
23
24 use Friendica\App\BaseURL;
25 use Friendica\Content\Pager;
26 use Friendica\Core\Hook;
27 use Friendica\Core\Logger;
28 use Friendica\Core\Protocol;
29 use Friendica\Core\Session;
30 use Friendica\Core\System;
31 use Friendica\Core\Worker;
32 use Friendica\Database\DBA;
33 use Friendica\DI;
34 use Friendica\Model\Notify\Type;
35 use Friendica\Network\HTTPException;
36 use Friendica\Network\Probe;
37 use Friendica\Protocol\Activity;
38 use Friendica\Protocol\ActivityPub;
39 use Friendica\Protocol\DFRN;
40 use Friendica\Protocol\Diaspora;
41 use Friendica\Protocol\OStatus;
42 use Friendica\Protocol\Salmon;
43 use Friendica\Util\DateTimeFormat;
44 use Friendica\Util\Images;
45 use Friendica\Util\Network;
46 use Friendica\Util\Proxy;
47 use Friendica\Util\Strings;
48
49 /**
50  * functions for interacting with a contact
51  */
52 class Contact
53 {
54         /**
55          * @deprecated since version 2019.03
56          * @see User::PAGE_FLAGS_NORMAL
57          */
58         const PAGE_NORMAL    = User::PAGE_FLAGS_NORMAL;
59         /**
60          * @deprecated since version 2019.03
61          * @see User::PAGE_FLAGS_SOAPBOX
62          */
63         const PAGE_SOAPBOX   = User::PAGE_FLAGS_SOAPBOX;
64         /**
65          * @deprecated since version 2019.03
66          * @see User::PAGE_FLAGS_COMMUNITY
67          */
68         const PAGE_COMMUNITY = User::PAGE_FLAGS_COMMUNITY;
69         /**
70          * @deprecated since version 2019.03
71          * @see User::PAGE_FLAGS_FREELOVE
72          */
73         const PAGE_FREELOVE  = User::PAGE_FLAGS_FREELOVE;
74         /**
75          * @deprecated since version 2019.03
76          * @see User::PAGE_FLAGS_BLOG
77          */
78         const PAGE_BLOG      = User::PAGE_FLAGS_BLOG;
79         /**
80          * @deprecated since version 2019.03
81          * @see User::PAGE_FLAGS_PRVGROUP
82          */
83         const PAGE_PRVGROUP  = User::PAGE_FLAGS_PRVGROUP;
84         /**
85          * @}
86          */
87
88         /**
89          * Account types
90          *
91          * TYPE_UNKNOWN - the account has been imported from gcontact where this is the default type value
92          *
93          * TYPE_PERSON - the account belongs to a person
94          *      Associated page types: PAGE_NORMAL, PAGE_SOAPBOX, PAGE_FREELOVE
95          *
96          * TYPE_ORGANISATION - the account belongs to an organisation
97          *      Associated page type: PAGE_SOAPBOX
98          *
99          * TYPE_NEWS - the account is a news reflector
100          *      Associated page type: PAGE_SOAPBOX
101          *
102          * TYPE_COMMUNITY - the account is community forum
103          *      Associated page types: PAGE_COMMUNITY, PAGE_PRVGROUP
104          *
105          * TYPE_RELAY - the account is a relay
106          *      This will only be assigned to contacts, not to user accounts
107          * @{
108          */
109         const TYPE_UNKNOWN =     -1;
110         const TYPE_PERSON =       User::ACCOUNT_TYPE_PERSON;
111         const TYPE_ORGANISATION = User::ACCOUNT_TYPE_ORGANISATION;
112         const TYPE_NEWS =         User::ACCOUNT_TYPE_NEWS;
113         const TYPE_COMMUNITY =    User::ACCOUNT_TYPE_COMMUNITY;
114         const TYPE_RELAY =        User::ACCOUNT_TYPE_RELAY;
115         /**
116          * @}
117          */
118
119         /**
120          * Contact_is
121          *
122          * Relationship types
123          * @{
124          */
125         const FOLLOWER = 1;
126         const SHARING  = 2;
127         const FRIEND   = 3;
128         /**
129          * @}
130          */
131
132         /**
133          * @param array $fields    Array of selected fields, empty for all
134          * @param array $condition Array of fields for condition
135          * @param array $params    Array of several parameters
136          * @return array
137          * @throws \Exception
138          */
139         public static function selectToArray(array $fields = [], array $condition = [], array $params = [])
140         {
141                 return DBA::selectToArray('contact', $fields, $condition, $params);
142         }
143
144         /**
145          * @param array $fields    Array of selected fields, empty for all
146          * @param array $condition Array of fields for condition
147          * @param array $params    Array of several parameters
148          * @return array
149          * @throws \Exception
150          */
151         public static function selectFirst(array $fields = [], array $condition = [], array $params = [])
152         {
153                 $contact = DBA::selectFirst('contact', $fields, $condition, $params);
154
155                 return $contact;
156         }
157
158         /**
159          * Insert a row into the contact table
160          * Important: You can't use DBA::lastInsertId() after this call since it will be set to 0.
161          *
162          * @param array        $fields              field array
163          * @param bool         $on_duplicate_update Do an update on a duplicate entry
164          *
165          * @return boolean was the insert successful?
166          * @throws \Exception
167          */
168         public static function insert(array $fields, bool $on_duplicate_update = false)
169         {
170                 $ret = DBA::insert('contact', $fields, $on_duplicate_update);
171                 $contact = DBA::selectFirst('contact', ['nurl', 'uid'], ['id' => DBA::lastInsertId()]);
172                 if (!DBA::isResult($contact)) {
173                         // Shouldn't happen
174                         return $ret;
175                 }
176
177                 // Search for duplicated contacts and get rid of them
178                 self::removeDuplicates($contact['nurl'], $contact['uid']);
179
180                 return $ret;
181         }
182
183         /**
184          * @param integer $id     Contact ID
185          * @param array   $fields Array of selected fields, empty for all
186          * @return array|boolean Contact record if it exists, false otherwise
187          * @throws \Exception
188          */
189         public static function getById($id, $fields = [])
190         {
191                 return DBA::selectFirst('contact', $fields, ['id' => $id]);
192         }
193
194         /**
195          * Fetches a contact by a given url
196          *
197          * @param string  $url    profile url
198          * @param boolean $update true = always update, false = never update, null = update when not found or outdated
199          * @param array   $fields Field list
200          * @param integer $uid    User ID of the contact
201          * @return array contact array
202          */
203         public static function getByURL(string $url, $update = null, array $fields = [], int $uid = 0)
204         {
205                 if ($update || is_null($update)) {
206                         $cid = self::getIdForURL($url, $uid, $update);
207                         if (empty($cid)) {
208                                 return [];
209                         }
210
211                         $contact = self::getById($cid, $fields);
212                         if (empty($contact)) {
213                                 return [];
214                         }
215                         return $contact;
216                 }
217
218                 // Add internal fields
219                 $removal = [];
220                 if (!empty($fields)) {
221                         foreach (['id', 'updated', 'network'] as $internal) {
222                                 if (!in_array($internal, $fields)) {
223                                         $fields[] = $internal;
224                                         $removal[] = $internal;
225                                 }
226                         }
227                 }
228
229                 // We first try the nurl (http://server.tld/nick), most common case
230                 $options = ['order' => ['id']];
231                 $contact = DBA::selectFirst('contact', $fields, ['nurl' => Strings::normaliseLink($url), 'uid' => $uid, 'deleted' => false], $options);
232
233                 // Then the addr (nick@server.tld)
234                 if (!DBA::isResult($contact)) {
235                         $contact = DBA::selectFirst('contact', $fields, ['addr' => str_replace('acct:', '', $url), 'uid' => $uid, 'deleted' => false], $options);
236                 }
237
238                 // Then the alias (which could be anything)
239                 if (!DBA::isResult($contact)) {
240                         // The link could be provided as http although we stored it as https
241                         $ssl_url = str_replace('http://', 'https://', $url);
242                         $condition = ['`alias` IN (?, ?, ?) AND `uid` = ? AND NOT `deleted`', $url, Strings::normaliseLink($url), $ssl_url, $uid];
243                         $contact = DBA::selectFirst('contact', $fields, $condition, $options);
244                 }
245                 
246                 if (!DBA::isResult($contact)) {
247                         return [];
248                 }
249
250                 // Update the contact in the background if needed
251                 if ((($contact['updated'] < DateTimeFormat::utc('now -7 days')) || empty($contact['avatar'])) &&
252                         in_array($contact['network'], Protocol::FEDERATED)) {
253                         Worker::add(PRIORITY_LOW, "UpdateContact", $contact['id'], ($uid == 0 ? 'force' : ''));
254                 }
255
256                 // Remove the internal fields
257                 foreach ($removal as $internal) {
258                         unset($contact[$internal]);
259                 }
260
261                 return $contact;
262         }
263
264         /**
265          * Fetches a contact for a given user by a given url.
266          * In difference to "getByURL" the function will fetch a public contact when no user contact had been found.
267          *
268          * @param string  $url    profile url
269          * @param integer $uid    User ID of the contact
270          * @param boolean $update true = always update, false = never update, null = update when not found or outdated
271          * @param array   $fields Field list
272          * @return array contact array
273          */
274         public static function getByURLForUser(string $url, int $uid = 0, $update = false, array $fields = [])
275         {
276                 if ($uid != 0) {
277                         $contact = self::getByURL($url, $update, $fields, $uid);
278                         if (!empty($contact)) {
279                                 if (!empty($contact['id'])) {
280                                         $contact['cid'] = $contact['id'];
281                                         $contact['zid'] = 0;
282                                 }
283                                 return $contact;
284                         }
285                 }
286
287                 $contact = self::getByURL($url, $update, $fields);
288                 if (!empty($contact['id'])) {           
289                         $contact['cid'] = 0;
290                         $contact['zid'] = $contact['id'];
291                 }
292                 return $contact;
293         }
294
295         /**
296          * Tests if the given contact is a follower
297          *
298          * @param int $cid Either public contact id or user's contact id
299          * @param int $uid User ID
300          *
301          * @return boolean is the contact id a follower?
302          * @throws HTTPException\InternalServerErrorException
303          * @throws \ImagickException
304          */
305         public static function isFollower($cid, $uid)
306         {
307                 if (self::isBlockedByUser($cid, $uid)) {
308                         return false;
309                 }
310
311                 $cdata = self::getPublicAndUserContacID($cid, $uid);
312                 if (empty($cdata['user'])) {
313                         return false;
314                 }
315
316                 $condition = ['id' => $cdata['user'], 'rel' => [self::FOLLOWER, self::FRIEND]];
317                 return DBA::exists('contact', $condition);
318         }
319
320         /**
321          * Tests if the given contact url is a follower
322          *
323          * @param string $url Contact URL
324          * @param int    $uid User ID
325          *
326          * @return boolean is the contact id a follower?
327          * @throws HTTPException\InternalServerErrorException
328          * @throws \ImagickException
329          */
330         public static function isFollowerByURL($url, $uid)
331         {
332                 $cid = self::getIdForURL($url, $uid, false);
333
334                 if (empty($cid)) {
335                         return false;
336                 }
337
338                 return self::isFollower($cid, $uid);
339         }
340
341         /**
342          * Tests if the given user follow the given contact
343          *
344          * @param int $cid Either public contact id or user's contact id
345          * @param int $uid User ID
346          *
347          * @return boolean is the contact url being followed?
348          * @throws HTTPException\InternalServerErrorException
349          * @throws \ImagickException
350          */
351         public static function isSharing($cid, $uid)
352         {
353                 if (self::isBlockedByUser($cid, $uid)) {
354                         return false;
355                 }
356
357                 $cdata = self::getPublicAndUserContacID($cid, $uid);
358                 if (empty($cdata['user'])) {
359                         return false;
360                 }
361
362                 $condition = ['id' => $cdata['user'], 'rel' => [self::SHARING, self::FRIEND]];
363                 return DBA::exists('contact', $condition);
364         }
365
366         /**
367          * Tests if the given user follow the given contact url
368          *
369          * @param string $url Contact URL
370          * @param int    $uid User ID
371          *
372          * @return boolean is the contact url being followed?
373          * @throws HTTPException\InternalServerErrorException
374          * @throws \ImagickException
375          */
376         public static function isSharingByURL($url, $uid)
377         {
378                 $cid = self::getIdForURL($url, $uid, false);
379
380                 if (empty($cid)) {
381                         return false;
382                 }
383
384                 return self::isSharing($cid, $uid);
385         }
386
387         /**
388          * Get the basepath for a given contact link
389          *
390          * @param string $url The contact link
391          * @param boolean $dont_update Don't update the contact
392          *
393          * @return string basepath
394          * @throws HTTPException\InternalServerErrorException
395          * @throws \ImagickException
396          */
397         public static function getBasepath($url, $dont_update = false)
398         {
399                 $contact = DBA::selectFirst('contact', ['id', 'baseurl'], ['uid' => 0, 'nurl' => Strings::normaliseLink($url)]);
400                 if (!DBA::isResult($contact)) {
401                         return '';
402                 }
403
404                 if (!empty($contact['baseurl'])) {
405                         return $contact['baseurl'];
406                 } elseif ($dont_update) {
407                         return '';
408                 }
409
410                 // Update the existing contact
411                 self::updateFromProbe($contact['id'], '', true);
412
413                 // And fetch the result
414                 $contact = DBA::selectFirst('contact', ['baseurl'], ['id' => $contact['id']]);
415                 if (empty($contact['baseurl'])) {
416                         Logger::info('No baseurl for contact', ['url' => $url]);
417                         return '';
418                 }
419
420                 Logger::info('Found baseurl for contact', ['url' => $url, 'baseurl' => $contact['baseurl']]);
421                 return $contact['baseurl'];
422         }
423
424         /**
425          * Check if the given contact url is on the same server
426          *
427          * @param string $url The contact link
428          *
429          * @return boolean Is it the same server?
430          */
431         public static function isLocal($url)
432         {
433                 return Strings::compareLink(self::getBasepath($url, true), DI::baseUrl());
434         }
435
436         /**
437          * Check if the given contact ID is on the same server
438          *
439          * @param string $url The contact link
440          *
441          * @return boolean Is it the same server?
442          */
443         public static function isLocalById(int $cid)
444         {
445                 $contact = DBA::selectFirst('contact', ['url', 'baseurl'], ['id' => $cid]);
446                 if (!DBA::isResult($contact)) {
447                         return false;
448                 }
449
450                 if (empty($contact['baseurl'])) {
451                         $baseurl = self::getBasepath($contact['url'], true);
452                 } else {
453                         $baseurl = $contact['baseurl'];
454                 }
455
456                 return Strings::compareLink($baseurl, DI::baseUrl());
457         }
458
459         /**
460          * Returns the public contact id of the given user id
461          *
462          * @param  integer $uid User ID
463          *
464          * @return integer|boolean Public contact id for given user id
465          * @throws \Exception
466          */
467         public static function getPublicIdByUserId($uid)
468         {
469                 $self = DBA::selectFirst('contact', ['url'], ['self' => true, 'uid' => $uid]);
470                 if (!DBA::isResult($self)) {
471                         return false;
472                 }
473                 return self::getIdForURL($self['url'], 0, false);
474         }
475
476         /**
477          * Returns the contact id for the user and the public contact id for a given contact id
478          *
479          * @param int $cid Either public contact id or user's contact id
480          * @param int $uid User ID
481          *
482          * @return array with public and user's contact id
483          * @throws HTTPException\InternalServerErrorException
484          * @throws \ImagickException
485          */
486         public static function getPublicAndUserContacID($cid, $uid)
487         {
488                 if (empty($uid) || empty($cid)) {
489                         return [];
490                 }
491
492                 $contact = DBA::selectFirst('contact', ['id', 'uid', 'url'], ['id' => $cid]);
493                 if (!DBA::isResult($contact)) {
494                         return [];
495                 }
496
497                 // We quit when the user id don't match the user id of the provided contact
498                 if (($contact['uid'] != $uid) && ($contact['uid'] != 0)) {
499                         return [];
500                 }
501
502                 if ($contact['uid'] != 0) {
503                         $pcid = Contact::getIdForURL($contact['url'], 0, false, ['url' => $contact['url']]);
504                         if (empty($pcid)) {
505                                 return [];
506                         }
507                         $ucid = $contact['id'];
508                 } else {
509                         $pcid = $contact['id'];
510                         $ucid = Contact::getIdForURL($contact['url'], $uid, false);
511                 }
512
513                 return ['public' => $pcid, 'user' => $ucid];
514         }
515
516         /**
517          * Returns contact details for a given contact id in combination with a user id
518          *
519          * @param int $cid A contact ID
520          * @param int $uid The User ID
521          * @param array $fields The selected fields for the contact
522          *
523          * @return array The contact details
524          *
525          * @throws \Exception
526          */
527         public static function getContactForUser($cid, $uid, array $fields = [])
528         {
529                 $contact = DBA::selectFirst('contact', $fields, ['id' => $cid, 'uid' => $uid]);
530
531                 if (!DBA::isResult($contact)) {
532                         return [];
533                 } else {
534                         return $contact;
535                 }
536         }
537
538         /**
539          * Block contact id for user id
540          *
541          * @param int     $cid     Either public contact id or user's contact id
542          * @param int     $uid     User ID
543          * @param boolean $blocked Is the contact blocked or unblocked?
544          * @throws \Exception
545          */
546         public static function setBlockedForUser($cid, $uid, $blocked)
547         {
548                 $cdata = self::getPublicAndUserContacID($cid, $uid);
549                 if (empty($cdata)) {
550                         return;
551                 }
552
553                 if ($cdata['user'] != 0) {
554                         DBA::update('contact', ['blocked' => $blocked], ['id' => $cdata['user'], 'pending' => false]);
555                 }
556
557                 DBA::update('user-contact', ['blocked' => $blocked], ['cid' => $cdata['public'], 'uid' => $uid], true);
558         }
559
560         /**
561          * Returns "block" state for contact id and user id
562          *
563          * @param int $cid Either public contact id or user's contact id
564          * @param int $uid User ID
565          *
566          * @return boolean is the contact id blocked for the given user?
567          * @throws \Exception
568          */
569         public static function isBlockedByUser($cid, $uid)
570         {
571                 $cdata = self::getPublicAndUserContacID($cid, $uid);
572                 if (empty($cdata)) {
573                         return;
574                 }
575
576                 $public_blocked = false;
577
578                 if (!empty($cdata['public'])) {
579                         $public_contact = DBA::selectFirst('user-contact', ['blocked'], ['cid' => $cdata['public'], 'uid' => $uid]);
580                         if (DBA::isResult($public_contact)) {
581                                 $public_blocked = $public_contact['blocked'];
582                         }
583                 }
584
585                 $user_blocked = $public_blocked;
586
587                 if (!empty($cdata['user'])) {
588                         $user_contact = DBA::selectFirst('contact', ['blocked'], ['id' => $cdata['user'], 'pending' => false]);
589                         if (DBA::isResult($user_contact)) {
590                                 $user_blocked = $user_contact['blocked'];
591                         }
592                 }
593
594                 if ($user_blocked != $public_blocked) {
595                         DBA::update('user-contact', ['blocked' => $user_blocked], ['cid' => $cdata['public'], 'uid' => $uid], true);
596                 }
597
598                 return $user_blocked;
599         }
600
601         /**
602          * Ignore contact id for user id
603          *
604          * @param int     $cid     Either public contact id or user's contact id
605          * @param int     $uid     User ID
606          * @param boolean $ignored Is the contact ignored or unignored?
607          * @throws \Exception
608          */
609         public static function setIgnoredForUser($cid, $uid, $ignored)
610         {
611                 $cdata = self::getPublicAndUserContacID($cid, $uid);
612                 if (empty($cdata)) {
613                         return;
614                 }
615
616                 if ($cdata['user'] != 0) {
617                         DBA::update('contact', ['readonly' => $ignored], ['id' => $cdata['user'], 'pending' => false]);
618                 }
619
620                 DBA::update('user-contact', ['ignored' => $ignored], ['cid' => $cdata['public'], 'uid' => $uid], true);
621         }
622
623         /**
624          * Returns "ignore" state for contact id and user id
625          *
626          * @param int $cid Either public contact id or user's contact id
627          * @param int $uid User ID
628          *
629          * @return boolean is the contact id ignored for the given user?
630          * @throws \Exception
631          */
632         public static function isIgnoredByUser($cid, $uid)
633         {
634                 $cdata = self::getPublicAndUserContacID($cid, $uid);
635                 if (empty($cdata)) {
636                         return;
637                 }
638
639                 $public_ignored = false;
640
641                 if (!empty($cdata['public'])) {
642                         $public_contact = DBA::selectFirst('user-contact', ['ignored'], ['cid' => $cdata['public'], 'uid' => $uid]);
643                         if (DBA::isResult($public_contact)) {
644                                 $public_ignored = $public_contact['ignored'];
645                         }
646                 }
647
648                 $user_ignored = $public_ignored;
649
650                 if (!empty($cdata['user'])) {
651                         $user_contact = DBA::selectFirst('contact', ['readonly'], ['id' => $cdata['user'], 'pending' => false]);
652                         if (DBA::isResult($user_contact)) {
653                                 $user_ignored = $user_contact['readonly'];
654                         }
655                 }
656
657                 if ($user_ignored != $public_ignored) {
658                         DBA::update('user-contact', ['ignored' => $user_ignored], ['cid' => $cdata['public'], 'uid' => $uid], true);
659                 }
660
661                 return $user_ignored;
662         }
663
664         /**
665          * Set "collapsed" for contact id and user id
666          *
667          * @param int     $cid       Either public contact id or user's contact id
668          * @param int     $uid       User ID
669          * @param boolean $collapsed are the contact's posts collapsed or uncollapsed?
670          * @throws \Exception
671          */
672         public static function setCollapsedForUser($cid, $uid, $collapsed)
673         {
674                 $cdata = self::getPublicAndUserContacID($cid, $uid);
675                 if (empty($cdata)) {
676                         return;
677                 }
678
679                 DBA::update('user-contact', ['collapsed' => $collapsed], ['cid' => $cdata['public'], 'uid' => $uid], true);
680         }
681
682         /**
683          * Returns "collapsed" state for contact id and user id
684          *
685          * @param int $cid Either public contact id or user's contact id
686          * @param int $uid User ID
687          *
688          * @return boolean is the contact id blocked for the given user?
689          * @throws HTTPException\InternalServerErrorException
690          * @throws \ImagickException
691          */
692         public static function isCollapsedByUser($cid, $uid)
693         {
694                 $cdata = self::getPublicAndUserContacID($cid, $uid);
695                 if (empty($cdata)) {
696                         return;
697                 }
698
699                 $collapsed = false;
700
701                 if (!empty($cdata['public'])) {
702                         $public_contact = DBA::selectFirst('user-contact', ['collapsed'], ['cid' => $cdata['public'], 'uid' => $uid]);
703                         if (DBA::isResult($public_contact)) {
704                                 $collapsed = $public_contact['collapsed'];
705                         }
706                 }
707
708                 return $collapsed;
709         }
710
711         /**
712          * Returns a list of contacts belonging in a group
713          *
714          * @param int $gid
715          * @return array
716          * @throws \Exception
717          */
718         public static function getByGroupId($gid)
719         {
720                 $return = [];
721
722                 if (intval($gid)) {
723                         $stmt = DBA::p('SELECT `group_member`.`contact-id`, `contact`.*
724                                 FROM `contact`
725                                 INNER JOIN `group_member`
726                                         ON `contact`.`id` = `group_member`.`contact-id`
727                                 WHERE `gid` = ?
728                                 AND `contact`.`uid` = ?
729                                 AND NOT `contact`.`self`
730                                 AND NOT `contact`.`deleted`
731                                 AND NOT `contact`.`blocked`
732                                 AND NOT `contact`.`pending`
733                                 ORDER BY `contact`.`name` ASC',
734                                 $gid,
735                                 local_user()
736                         );
737
738                         if (DBA::isResult($stmt)) {
739                                 $return = DBA::toArray($stmt);
740                         }
741                 }
742
743                 return $return;
744         }
745
746         /**
747          * Creates the self-contact for the provided user id
748          *
749          * @param int $uid
750          * @return bool Operation success
751          * @throws HTTPException\InternalServerErrorException
752          */
753         public static function createSelfFromUserId($uid)
754         {
755                 // Only create the entry if it doesn't exist yet
756                 if (DBA::exists('contact', ['uid' => $uid, 'self' => true])) {
757                         return true;
758                 }
759
760                 $user = DBA::selectFirst('user', ['uid', 'username', 'nickname'], ['uid' => $uid]);
761                 if (!DBA::isResult($user)) {
762                         return false;
763                 }
764
765                 $return = DBA::insert('contact', [
766                         'uid'         => $user['uid'],
767                         'created'     => DateTimeFormat::utcNow(),
768                         'self'        => 1,
769                         'name'        => $user['username'],
770                         'nick'        => $user['nickname'],
771                         'photo'       => DI::baseUrl() . '/photo/profile/' . $user['uid'] . '.jpg',
772                         'thumb'       => DI::baseUrl() . '/photo/avatar/'  . $user['uid'] . '.jpg',
773                         'micro'       => DI::baseUrl() . '/photo/micro/'   . $user['uid'] . '.jpg',
774                         'blocked'     => 0,
775                         'pending'     => 0,
776                         'url'         => DI::baseUrl() . '/profile/' . $user['nickname'],
777                         'nurl'        => Strings::normaliseLink(DI::baseUrl() . '/profile/' . $user['nickname']),
778                         'addr'        => $user['nickname'] . '@' . substr(DI::baseUrl(), strpos(DI::baseUrl(), '://') + 3),
779                         'request'     => DI::baseUrl() . '/dfrn_request/' . $user['nickname'],
780                         'notify'      => DI::baseUrl() . '/dfrn_notify/'  . $user['nickname'],
781                         'poll'        => DI::baseUrl() . '/dfrn_poll/'    . $user['nickname'],
782                         'confirm'     => DI::baseUrl() . '/dfrn_confirm/' . $user['nickname'],
783                         'poco'        => DI::baseUrl() . '/poco/'         . $user['nickname'],
784                         'name-date'   => DateTimeFormat::utcNow(),
785                         'uri-date'    => DateTimeFormat::utcNow(),
786                         'avatar-date' => DateTimeFormat::utcNow(),
787                         'closeness'   => 0
788                 ]);
789
790                 return $return;
791         }
792
793         /**
794          * Updates the self-contact for the provided user id
795          *
796          * @param int     $uid
797          * @param boolean $update_avatar Force the avatar update
798          * @throws HTTPException\InternalServerErrorException
799          */
800         public static function updateSelfFromUserID($uid, $update_avatar = false)
801         {
802                 $fields = ['id', 'name', 'nick', 'location', 'about', 'keywords', 'avatar',
803                         'xmpp', 'contact-type', 'forum', 'prv', 'avatar-date', 'url', 'nurl', 'unsearchable',
804                         'photo', 'thumb', 'micro', 'addr', 'request', 'notify', 'poll', 'confirm', 'poco'];
805                 $self = DBA::selectFirst('contact', $fields, ['uid' => $uid, 'self' => true]);
806                 if (!DBA::isResult($self)) {
807                         return;
808                 }
809
810                 $fields = ['nickname', 'page-flags', 'account-type'];
811                 $user = DBA::selectFirst('user', $fields, ['uid' => $uid]);
812                 if (!DBA::isResult($user)) {
813                         return;
814                 }
815
816                 $fields = ['name', 'photo', 'thumb', 'about', 'address', 'locality', 'region',
817                         'country-name', 'pub_keywords', 'xmpp', 'net-publish'];
818                 $profile = DBA::selectFirst('profile', $fields, ['uid' => $uid]);
819                 if (!DBA::isResult($profile)) {
820                         return;
821                 }
822
823                 $file_suffix = 'jpg';
824
825                 $fields = ['name' => $profile['name'], 'nick' => $user['nickname'],
826                         'avatar-date' => $self['avatar-date'], 'location' => Profile::formatLocation($profile),
827                         'about' => $profile['about'], 'keywords' => $profile['pub_keywords'],
828                         'contact-type' => $user['account-type'],
829                         'xmpp' => $profile['xmpp']];
830
831                 $avatar = Photo::selectFirst(['resource-id', 'type'], ['uid' => $uid, 'profile' => true]);
832                 if (DBA::isResult($avatar)) {
833                         if ($update_avatar) {
834                                 $fields['avatar-date'] = DateTimeFormat::utcNow();
835                         }
836
837                         // Creating the path to the avatar, beginning with the file suffix
838                         $types = Images::supportedTypes();
839                         if (isset($types[$avatar['type']])) {
840                                 $file_suffix = $types[$avatar['type']];
841                         }
842
843                         // We are adding a timestamp value so that other systems won't use cached content
844                         $timestamp = strtotime($fields['avatar-date']);
845
846                         $prefix = DI::baseUrl() . '/photo/' .$avatar['resource-id'] . '-';
847                         $suffix = '.' . $file_suffix . '?ts=' . $timestamp;
848
849                         $fields['photo'] = $prefix . '4' . $suffix;
850                         $fields['thumb'] = $prefix . '5' . $suffix;
851                         $fields['micro'] = $prefix . '6' . $suffix;
852                 } else {
853                         // We hadn't found a photo entry, so we use the default avatar
854                         $fields['photo'] = DI::baseUrl() . '/images/person-300.jpg';
855                         $fields['thumb'] = DI::baseUrl() . '/images/person-80.jpg';
856                         $fields['micro'] = DI::baseUrl() . '/images/person-48.jpg';
857                 }
858
859                 $fields['avatar'] = DI::baseUrl() . '/photo/profile/' .$uid . '.' . $file_suffix;
860                 $fields['forum'] = $user['page-flags'] == User::PAGE_FLAGS_COMMUNITY;
861                 $fields['prv'] = $user['page-flags'] == User::PAGE_FLAGS_PRVGROUP;
862                 $fields['unsearchable'] = !$profile['net-publish'];
863
864                 // it seems as if ported accounts can have wrong values, so we make sure that now everything is fine.
865                 $fields['url'] = DI::baseUrl() . '/profile/' . $user['nickname'];
866                 $fields['nurl'] = Strings::normaliseLink($fields['url']);
867                 $fields['addr'] = $user['nickname'] . '@' . substr(DI::baseUrl(), strpos(DI::baseUrl(), '://') + 3);
868                 $fields['request'] = DI::baseUrl() . '/dfrn_request/' . $user['nickname'];
869                 $fields['notify'] = DI::baseUrl() . '/dfrn_notify/' . $user['nickname'];
870                 $fields['poll'] = DI::baseUrl() . '/dfrn_poll/'. $user['nickname'];
871                 $fields['confirm'] = DI::baseUrl() . '/dfrn_confirm/' . $user['nickname'];
872                 $fields['poco'] = DI::baseUrl() . '/poco/' . $user['nickname'];
873
874                 $update = false;
875
876                 foreach ($fields as $field => $content) {
877                         if ($self[$field] != $content) {
878                                 $update = true;
879                         }
880                 }
881
882                 if ($update) {
883                         if ($fields['name'] != $self['name']) {
884                                 $fields['name-date'] = DateTimeFormat::utcNow();
885                         }
886                         $fields['updated'] = DateTimeFormat::utcNow();
887                         DBA::update('contact', $fields, ['id' => $self['id']]);
888
889                         // Update the public contact as well
890                         DBA::update('contact', $fields, ['uid' => 0, 'nurl' => $self['nurl']]);
891
892                         // Update the profile
893                         $fields = ['photo' => DI::baseUrl() . '/photo/profile/' .$uid . '.' . $file_suffix,
894                                 'thumb' => DI::baseUrl() . '/photo/avatar/' . $uid .'.' . $file_suffix];
895                         DBA::update('profile', $fields, ['uid' => $uid]);
896                 }
897         }
898
899         /**
900          * Marks a contact for removal
901          *
902          * @param int $id contact id
903          * @return null
904          * @throws HTTPException\InternalServerErrorException
905          */
906         public static function remove($id)
907         {
908                 // We want just to make sure that we don't delete our "self" contact
909                 $contact = DBA::selectFirst('contact', ['uid'], ['id' => $id, 'self' => false]);
910                 if (!DBA::isResult($contact) || !intval($contact['uid'])) {
911                         return;
912                 }
913
914                 // Archive the contact
915                 DBA::update('contact', ['archive' => true, 'network' => Protocol::PHANTOM, 'deleted' => true], ['id' => $id]);
916
917                 // Delete it in the background
918                 Worker::add(PRIORITY_MEDIUM, 'RemoveContact', $id);
919         }
920
921         /**
922          * Sends an unfriend message. Does not remove the contact
923          *
924          * @param array   $user     User unfriending
925          * @param array   $contact  Contact unfriended
926          * @param boolean $dissolve Remove the contact on the remote side
927          * @return void
928          * @throws HTTPException\InternalServerErrorException
929          * @throws \ImagickException
930          */
931         public static function terminateFriendship(array $user, array $contact, $dissolve = false)
932         {
933                 if (empty($contact['network'])) {
934                         return;
935                 }
936
937                 $protocol = $contact['network'];
938                 if (($protocol == Protocol::DFRN) && !self::isLegacyDFRNContact($contact)) {
939                         $protocol = Protocol::ACTIVITYPUB;
940                 }
941
942                 if (($protocol == Protocol::DFRN) && $dissolve) {
943                         DFRN::deliver($user, $contact, 'placeholder', true);
944                 } elseif (in_array($protocol, [Protocol::OSTATUS, Protocol::DFRN])) {
945                         // create an unfollow slap
946                         $item = [];
947                         $item['verb'] = Activity::O_UNFOLLOW;
948                         $item['gravity'] = GRAVITY_ACTIVITY;
949                         $item['follow'] = $contact["url"];
950                         $item['body'] = '';
951                         $item['title'] = '';
952                         $item['guid'] = '';
953                         $item['uri-id'] = 0;
954                         $item['attach'] = '';
955                         $slap = OStatus::salmon($item, $user);
956
957                         if (!empty($contact['notify'])) {
958                                 Salmon::slapper($user, $contact['notify'], $slap);
959                         }
960                 } elseif ($protocol == Protocol::DIASPORA) {
961                         Diaspora::sendUnshare($user, $contact);
962                 } elseif ($protocol == Protocol::ACTIVITYPUB) {
963                         ActivityPub\Transmitter::sendContactUndo($contact['url'], $contact['id'], $user['uid']);
964
965                         if ($dissolve) {
966                                 ActivityPub\Transmitter::sendContactReject($contact['url'], $contact['hub-verify'], $user['uid']);
967                         }
968                 }
969         }
970
971         /**
972          * Marks a contact for archival after a communication issue delay
973          *
974          * Contact has refused to recognise us as a friend. We will start a countdown.
975          * If they still don't recognise us in 32 days, the relationship is over,
976          * and we won't waste any more time trying to communicate with them.
977          * This provides for the possibility that their database is temporarily messed
978          * up or some other transient event and that there's a possibility we could recover from it.
979          *
980          * @param array $contact contact to mark for archival
981          * @return null
982          * @throws HTTPException\InternalServerErrorException
983          */
984         public static function markForArchival(array $contact)
985         {
986                 if (!isset($contact['url']) && !empty($contact['id'])) {
987                         $fields = ['id', 'url', 'archive', 'self', 'term-date'];
988                         $contact = DBA::selectFirst('contact', $fields, ['id' => $contact['id']]);
989                         if (!DBA::isResult($contact)) {
990                                 return;
991                         }
992                 } elseif (!isset($contact['url'])) {
993                         Logger::info('Empty contact', ['contact' => $contact, 'callstack' => System::callstack(20)]);
994                 }
995
996                 Logger::info('Contact is marked for archival', ['id' => $contact['id']]);
997
998                 // Contact already archived or "self" contact? => nothing to do
999                 if ($contact['archive'] || $contact['self']) {
1000                         return;
1001                 }
1002
1003                 if ($contact['term-date'] <= DBA::NULL_DATETIME) {
1004                         DBA::update('contact', ['term-date' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
1005                         DBA::update('contact', ['term-date' => DateTimeFormat::utcNow()], ['`nurl` = ? AND `term-date` <= ? AND NOT `self`', Strings::normaliseLink($contact['url']), DBA::NULL_DATETIME]);
1006                 } else {
1007                         /* @todo
1008                          * We really should send a notification to the owner after 2-3 weeks
1009                          * so they won't be surprised when the contact vanishes and can take
1010                          * remedial action if this was a serious mistake or glitch
1011                          */
1012
1013                         /// @todo Check for contact vitality via probing
1014                         $archival_days = DI::config()->get('system', 'archival_days', 32);
1015
1016                         $expiry = $contact['term-date'] . ' + ' . $archival_days . ' days ';
1017                         if (DateTimeFormat::utcNow() > DateTimeFormat::utc($expiry)) {
1018                                 /* Relationship is really truly dead. archive them rather than
1019                                  * delete, though if the owner tries to unarchive them we'll start
1020                                  * the whole process over again.
1021                                  */
1022                                 DBA::update('contact', ['archive' => true], ['id' => $contact['id']]);
1023                                 DBA::update('contact', ['archive' => true], ['nurl' => Strings::normaliseLink($contact['url']), 'self' => false]);
1024                                 GContact::updateFromPublicContactURL($contact['url']);
1025                         }
1026                 }
1027         }
1028
1029         /**
1030          * Cancels the archival countdown
1031          *
1032          * @see   Contact::markForArchival()
1033          *
1034          * @param array $contact contact to be unmarked for archival
1035          * @return null
1036          * @throws \Exception
1037          */
1038         public static function unmarkForArchival(array $contact)
1039         {
1040                 // Always unarchive the relay contact entry
1041                 if (!empty($contact['batch']) && !empty($contact['term-date']) && ($contact['term-date'] > DBA::NULL_DATETIME)) {
1042                         $fields = ['failed' => false, 'term-date' => DBA::NULL_DATETIME, 'archive' => false];
1043                         $condition = ['uid' => 0, 'network' => Protocol::FEDERATED, 'batch' => $contact['batch'], 'contact-type' => self::TYPE_RELAY];
1044                         DBA::update('contact', $fields, $condition);
1045                 }
1046
1047                 $condition = ['`id` = ? AND (`term-date` > ? OR `archive`)', $contact['id'], DBA::NULL_DATETIME];
1048                 $exists = DBA::exists('contact', $condition);
1049
1050                 // We don't need to update, we never marked this contact for archival
1051                 if (!$exists) {
1052                         return;
1053                 }
1054
1055                 Logger::info('Contact is marked as vital again', ['id' => $contact['id']]);
1056
1057                 if (!isset($contact['url']) && !empty($contact['id'])) {
1058                         $fields = ['id', 'url', 'batch'];
1059                         $contact = DBA::selectFirst('contact', $fields, ['id' => $contact['id']]);
1060                         if (!DBA::isResult($contact)) {
1061                                 return;
1062                         }
1063                 }
1064
1065                 // It's a miracle. Our dead contact has inexplicably come back to life.
1066                 $fields = ['failed' => false, 'term-date' => DBA::NULL_DATETIME, 'archive' => false];
1067                 DBA::update('contact', $fields, ['id' => $contact['id']]);
1068                 DBA::update('contact', $fields, ['nurl' => Strings::normaliseLink($contact['url']), 'self' => false]);
1069                 GContact::updateFromPublicContactURL($contact['url']);
1070         }
1071
1072         /**
1073          * Returns the data array for the photo menu of a given contact
1074          *
1075          * @param array $contact contact
1076          * @param int   $uid     optional, default 0
1077          * @return array
1078          * @throws HTTPException\InternalServerErrorException
1079          * @throws \ImagickException
1080          */
1081         public static function photoMenu(array $contact, $uid = 0)
1082         {
1083                 $pm_url = '';
1084                 $status_link = '';
1085                 $photos_link = '';
1086                 $contact_drop_link = '';
1087                 $poke_link = '';
1088
1089                 if ($uid == 0) {
1090                         $uid = local_user();
1091                 }
1092
1093                 if (empty($contact['uid']) || ($contact['uid'] != $uid)) {
1094                         if ($uid == 0) {
1095                                 $profile_link = self::magicLink($contact['url']);
1096                                 $menu = ['profile' => [DI::l10n()->t('View Profile'), $profile_link, true]];
1097
1098                                 return $menu;
1099                         }
1100
1101                         // Look for our own contact if the uid doesn't match and isn't public
1102                         $contact_own = DBA::selectFirst('contact', [], ['nurl' => $contact['nurl'], 'network' => $contact['network'], 'uid' => $uid]);
1103                         if (DBA::isResult($contact_own)) {
1104                                 return self::photoMenu($contact_own, $uid);
1105                         }
1106                 }
1107
1108                 $sparkle = false;
1109                 if (($contact['network'] === Protocol::DFRN) && !$contact['self'] && empty($contact['pending'])) {
1110                         $sparkle = true;
1111                         $profile_link = DI::baseUrl() . '/redir/' . $contact['id'];
1112                 } else {
1113                         $profile_link = $contact['url'];
1114                 }
1115
1116                 if ($profile_link === 'mailbox') {
1117                         $profile_link = '';
1118                 }
1119
1120                 if ($sparkle) {
1121                         $status_link = $profile_link . '/status';
1122                         $photos_link = str_replace('/profile/', '/photos/', $profile_link);
1123                         $profile_link = $profile_link . '/profile';
1124                 }
1125
1126                 if (self::canReceivePrivateMessages($contact) && empty($contact['pending'])) {
1127                         $pm_url = DI::baseUrl() . '/message/new/' . $contact['id'];
1128                 }
1129
1130                 if (($contact['network'] == Protocol::DFRN) && !$contact['self'] && empty($contact['pending'])) {
1131                         $poke_link = 'contact/' . $contact['id'] . '/poke';
1132                 }
1133
1134                 $contact_url = DI::baseUrl() . '/contact/' . $contact['id'];
1135
1136                 $posts_link = DI::baseUrl() . '/contact/' . $contact['id'] . '/conversations';
1137
1138                 if (!$contact['self']) {
1139                         $contact_drop_link = DI::baseUrl() . '/contact/' . $contact['id'] . '/drop?confirm=1';
1140                 }
1141
1142                 $follow_link = '';
1143                 $unfollow_link = '';
1144                 if (!$contact['self'] && in_array($contact['network'], Protocol::NATIVE_SUPPORT)) {
1145                         if ($contact['uid'] && in_array($contact['rel'], [self::SHARING, self::FRIEND])) {
1146                                 $unfollow_link = 'unfollow?url=' . urlencode($contact['url']);
1147                         } elseif(!$contact['pending']) {
1148                                 $follow_link = 'follow?url=' . urlencode($contact['url']);
1149                         }
1150                 }
1151
1152                 if (!empty($follow_link) || !empty($unfollow_link)) {
1153                         $contact_drop_link = '';
1154                 }
1155
1156                 /**
1157                  * Menu array:
1158                  * "name" => [ "Label", "link", (bool)Should the link opened in a new tab? ]
1159                  */
1160                 if (empty($contact['uid'])) {
1161                         $menu = [
1162                                 'profile' => [DI::l10n()->t('View Profile')  , $profile_link , true],
1163                                 'network' => [DI::l10n()->t('Network Posts') , $posts_link   , false],
1164                                 'edit'    => [DI::l10n()->t('View Contact')  , $contact_url  , false],
1165                                 'follow'  => [DI::l10n()->t('Connect/Follow'), $follow_link  , true],
1166                                 'unfollow'=> [DI::l10n()->t('UnFollow')      , $unfollow_link, true],
1167                         ];
1168                 } else {
1169                         $menu = [
1170                                 'status'  => [DI::l10n()->t('View Status')   , $status_link      , true],
1171                                 'profile' => [DI::l10n()->t('View Profile')  , $profile_link     , true],
1172                                 'photos'  => [DI::l10n()->t('View Photos')   , $photos_link      , true],
1173                                 'network' => [DI::l10n()->t('Network Posts') , $posts_link       , false],
1174                                 'edit'    => [DI::l10n()->t('View Contact')  , $contact_url      , false],
1175                                 'drop'    => [DI::l10n()->t('Drop Contact')  , $contact_drop_link, false],
1176                                 'pm'      => [DI::l10n()->t('Send PM')       , $pm_url           , false],
1177                                 'poke'    => [DI::l10n()->t('Poke')          , $poke_link        , false],
1178                                 'follow'  => [DI::l10n()->t('Connect/Follow'), $follow_link      , true],
1179                                 'unfollow'=> [DI::l10n()->t('UnFollow')      , $unfollow_link    , true],
1180                         ];
1181
1182                         if (!empty($contact['pending'])) {
1183                                 $intro = DBA::selectFirst('intro', ['id'], ['contact-id' => $contact['id']]);
1184                                 if (DBA::isResult($intro)) {
1185                                         $menu['follow'] = [DI::l10n()->t('Approve'), 'notifications/intros/' . $intro['id'], true];
1186                                 }
1187                         }
1188                 }
1189
1190                 $args = ['contact' => $contact, 'menu' => &$menu];
1191
1192                 Hook::callAll('contact_photo_menu', $args);
1193
1194                 $menucondensed = [];
1195
1196                 foreach ($menu as $menuname => $menuitem) {
1197                         if ($menuitem[1] != '') {
1198                                 $menucondensed[$menuname] = $menuitem;
1199                         }
1200                 }
1201
1202                 return $menucondensed;
1203         }
1204
1205         /**
1206          * Returns ungrouped contact count or list for user
1207          *
1208          * Returns either the total number of ungrouped contacts for the given user
1209          * id or a paginated list of ungrouped contacts.
1210          *
1211          * @param int $uid uid
1212          * @return array
1213          * @throws \Exception
1214          */
1215         public static function getUngroupedList($uid)
1216         {
1217                 return q("SELECT *
1218                            FROM `contact`
1219                            WHERE `uid` = %d
1220                            AND NOT `self`
1221                            AND NOT `deleted`
1222                            AND NOT `blocked`
1223                            AND NOT `pending`
1224                            AND `id` NOT IN (
1225                                 SELECT DISTINCT(`contact-id`)
1226                                 FROM `group_member`
1227                                 INNER JOIN `group` ON `group`.`id` = `group_member`.`gid`
1228                                 WHERE `group`.`uid` = %d
1229                            )", intval($uid), intval($uid));
1230         }
1231
1232         /**
1233          * Have a look at all contact tables for a given profile url.
1234          * This function works as a replacement for probing the contact.
1235          *
1236          * @param string  $url Contact URL
1237          * @param integer $cid Contact ID
1238          *
1239          * @return array Contact array in the "probe" structure
1240         */
1241         private static function getProbeDataFromDatabase($url, $cid = null)
1242         {
1243                 // The link could be provided as http although we stored it as https
1244                 $ssl_url = str_replace('http://', 'https://', $url);
1245
1246                 $fields = ['id', 'uid', 'url', 'addr', 'alias', 'notify', 'poll', 'name', 'nick',
1247                         'photo', 'keywords', 'location', 'about', 'network',
1248                         'priority', 'batch', 'request', 'confirm', 'poco'];
1249
1250                 if (!empty($cid)) {
1251                         $data = DBA::selectFirst('contact', $fields, ['id' => $cid]);
1252                         if (DBA::isResult($data)) {
1253                                 return $data;
1254                         }
1255                 }
1256
1257                 $data = DBA::selectFirst('contact', $fields, ['nurl' => Strings::normaliseLink($url)]);
1258
1259                 if (!DBA::isResult($data)) {
1260                         $condition = ['alias' => [$url, Strings::normaliseLink($url), $ssl_url]];
1261                         $data = DBA::selectFirst('contact', $fields, $condition);
1262                 }
1263
1264                 if (DBA::isResult($data)) {
1265                         // For security reasons we don't fetch key data from our users
1266                         $data["pubkey"] = '';
1267                         return $data;
1268                 }
1269
1270                 $fields = ['url', 'addr', 'alias', 'notify', 'name', 'nick',
1271                         'photo', 'keywords', 'location', 'about', 'network'];
1272                 $data = DBA::selectFirst('gcontact', $fields, ['nurl' => Strings::normaliseLink($url)]);
1273
1274                 if (!DBA::isResult($data)) {
1275                         $condition = ['alias' => [$url, Strings::normaliseLink($url), $ssl_url]];
1276                         $data = DBA::selectFirst('contact', $fields, $condition);
1277                 }
1278
1279                 if (DBA::isResult($data)) {
1280                         $data["pubkey"] = '';
1281                         $data["poll"] = '';
1282                         $data["priority"] = 0;
1283                         $data["batch"] = '';
1284                         $data["request"] = '';
1285                         $data["confirm"] = '';
1286                         $data["poco"] = '';
1287                         return $data;
1288                 }
1289
1290                 $data = ActivityPub::probeProfile($url, false);
1291                 if (!empty($data)) {
1292                         return $data;
1293                 }
1294
1295                 $fields = ['url', 'addr', 'alias', 'notify', 'poll', 'name', 'nick',
1296                         'photo', 'network', 'priority', 'batch', 'request', 'confirm'];
1297                 $data = DBA::selectFirst('fcontact', $fields, ['url' => $url]);
1298
1299                 if (!DBA::isResult($data)) {
1300                         $condition = ['alias' => [$url, Strings::normaliseLink($url), $ssl_url]];
1301                         $data = DBA::selectFirst('contact', $fields, $condition);
1302                 }
1303
1304                 if (DBA::isResult($data)) {
1305                         $data["pubkey"] = '';
1306                         $data["keywords"] = '';
1307                         $data["location"] = '';
1308                         $data["about"] = '';
1309                         $data["poco"] = '';
1310                         return $data;
1311                 }
1312
1313                 return [];
1314         }
1315
1316         /**
1317          * Fetch the contact id for a given URL and user
1318          *
1319          * First lookup in the contact table to find a record matching either `url`, `nurl`,
1320          * `addr` or `alias`.
1321          *
1322          * If there's no record and we aren't looking for a public contact, we quit.
1323          * If there's one, we check that it isn't time to update the picture else we
1324          * directly return the found contact id.
1325          *
1326          * Second, we probe the provided $url whether it's http://server.tld/profile or
1327          * nick@server.tld. We quit if we can't get any info back.
1328          *
1329          * Third, we create the contact record if it doesn't exist
1330          *
1331          * Fourth, we update the existing record with the new data (avatar, alias, nick)
1332          * if there's any updates
1333          *
1334          * @param string  $url       Contact URL
1335          * @param integer $uid       The user id for the contact (0 = public contact)
1336          * @param boolean $update    true = always update, false = never update, null = update when not found or outdated
1337          * @param array   $default   Default value for creating the contact when every else fails
1338          * @param boolean $in_loop   Internally used variable to prevent an endless loop
1339          *
1340          * @return integer Contact ID
1341          * @throws HTTPException\InternalServerErrorException
1342          * @throws \ImagickException
1343          */
1344         public static function getIdForURL($url, $uid = 0, $update = null, $default = [], $in_loop = false)
1345         {
1346                 Logger::info('Get contact data', ['url' => $url, 'user' => $uid]);
1347
1348                 $contact_id = 0;
1349
1350                 if ($url == '') {
1351                         return 0;
1352                 }
1353
1354                 $contact = self::getByURL($url, false, ['id', 'avatar', 'updated', 'network'], $uid);
1355
1356                 if (!empty($contact)) {
1357                         $contact_id = $contact["id"];
1358
1359                         if (empty($default) && in_array($contact['network'], [Protocol::MAIL, Protocol::PHANTOM]) && ($uid == 0)) {
1360                                 // Update public mail accounts via their user's accounts
1361                                 $fields = ['network', 'addr', 'name', 'nick', 'avatar', 'photo', 'thumb', 'micro'];
1362                                 $mailcontact = DBA::selectFirst('contact', $fields, ["`addr` = ? AND `network` = ? AND `uid` != 0", $url, Protocol::MAIL]);
1363                                 if (!DBA::isResult($mailcontact)) {
1364                                         $mailcontact = DBA::selectFirst('contact', $fields, ["`nurl` = ? AND `network` = ? AND `uid` != 0", $url, Protocol::MAIL]);
1365                                 }
1366
1367                                 if (DBA::isResult($mailcontact)) {
1368                                         DBA::update('contact', $mailcontact, ['id' => $contact_id]);
1369                                 }
1370                         }
1371
1372                         if (empty($update)) {
1373                                 return $contact_id;
1374                         }
1375                 } elseif ($uid != 0) {
1376                         // Non-existing user-specific contact, exiting
1377                         return 0;
1378                 }
1379
1380                 if (!$update && empty($default)) {
1381                         // When we don't want to update, we look if we know this contact in any way
1382                         $data = self::getProbeDataFromDatabase($url, $contact_id);
1383                         $background_update = true;
1384                 } elseif (!$update && !empty($default['network'])) {
1385                         // If there are default values, take these
1386                         $data = $default;
1387                         $background_update = false;
1388                 } else {
1389                         $data = [];
1390                         $background_update = false;
1391                 }
1392
1393                 if ((empty($data) && is_null($update)) || $update) {
1394                         $data = Probe::uri($url, "", $uid);
1395                 }
1396
1397                 // Take the default values when probing failed
1398                 if (!empty($default) && !in_array($data["network"], array_merge(Protocol::NATIVE_SUPPORT, [Protocol::PUMPIO]))) {
1399                         $data = array_merge($data, $default);
1400                 }
1401
1402                 if (empty($data) || ($data['network'] == Protocol::PHANTOM)) {
1403                         Logger::info('No valid network found', ['url' => $url, 'data' => $data, 'callstack' => System::callstack(20)]);
1404                         return 0;
1405                 }
1406
1407                 if (!empty($data['baseurl'])) {
1408                         $data['baseurl'] = GServer::cleanURL($data['baseurl']);
1409                 }
1410
1411                 if (!empty($data['baseurl']) && empty($data['gsid'])) {
1412                         $data['gsid'] = GServer::getID($data['baseurl']);
1413                 }
1414
1415                 if (!$contact_id && !empty($data['alias']) && ($data['alias'] != $data['url']) && !$in_loop) {
1416                         $contact_id = self::getIdForURL($data["alias"], $uid, false, $default, true);
1417                 }
1418
1419                 if (!$contact_id) {
1420                         $fields = [
1421                                 'uid'       => $uid,
1422                                 'created'   => DateTimeFormat::utcNow(),
1423                                 'url'       => $data['url'],
1424                                 'nurl'      => Strings::normaliseLink($data['url']),
1425                                 'addr'      => $data['addr'] ?? '',
1426                                 'alias'     => $data['alias'] ?? '',
1427                                 'notify'    => $data['notify'] ?? '',
1428                                 'poll'      => $data['poll'] ?? '',
1429                                 'name'      => $data['name'] ?? '',
1430                                 'nick'      => $data['nick'] ?? '',
1431                                 'keywords'  => $data['keywords'] ?? '',
1432                                 'location'  => $data['location'] ?? '',
1433                                 'about'     => $data['about'] ?? '',
1434                                 'network'   => $data['network'],
1435                                 'pubkey'    => $data['pubkey'] ?? '',
1436                                 'rel'       => self::SHARING,
1437                                 'priority'  => $data['priority'] ?? 0,
1438                                 'batch'     => $data['batch'] ?? '',
1439                                 'request'   => $data['request'] ?? '',
1440                                 'confirm'   => $data['confirm'] ?? '',
1441                                 'poco'      => $data['poco'] ?? '',
1442                                 'baseurl'   => $data['baseurl'] ?? '',
1443                                 'gsid'      => $data['gsid'] ?? null,
1444                                 'name-date' => DateTimeFormat::utcNow(),
1445                                 'uri-date'  => DateTimeFormat::utcNow(),
1446                                 'avatar-date' => DateTimeFormat::utcNow(),
1447                                 'writable'  => 1,
1448                                 'blocked'   => 0,
1449                                 'readonly'  => 0,
1450                                 'pending'   => 0];
1451
1452                         $condition = ['nurl' => Strings::normaliseLink($data["url"]), 'uid' => $uid, 'deleted' => false];
1453
1454                         // Before inserting we do check if the entry does exist now.
1455                         $contact = DBA::selectFirst('contact', ['id'], $condition, ['order' => ['id']]);
1456                         if (!DBA::isResult($contact)) {
1457                                 Logger::info('Create new contact', $fields);
1458
1459                                 self::insert($fields);
1460
1461                                 // We intentionally aren't using lastInsertId here. There is a chance for duplicates.
1462                                 $contact = DBA::selectFirst('contact', ['id'], $condition, ['order' => ['id']]);
1463                                 if (!DBA::isResult($contact)) {
1464                                         Logger::info('Contact creation failed', $fields);
1465                                         // Shouldn't happen
1466                                         return 0;
1467                                 }
1468                         } else {
1469                                 Logger::info('Contact had been created before', ['id' => $contact["id"], 'url' => $url, 'contact' => $fields]);
1470                         }
1471
1472                         $contact_id = $contact["id"];
1473                 }
1474
1475                 if (!empty($data['photo']) && ($data['network'] != Protocol::FEED)) {
1476                         self::updateAvatar($contact_id, $data['photo']);
1477                 }
1478
1479                 if (in_array($data["network"], array_merge(Protocol::NATIVE_SUPPORT, [Protocol::PUMPIO]))) {
1480                         if ($background_update) {
1481                                 // Update in the background when we fetched the data solely from the database
1482                                 Worker::add(PRIORITY_MEDIUM, "UpdateContact", $contact_id, ($uid == 0 ? 'force' : ''));
1483                         } else {
1484                                 // Else do a direct update
1485                                 self::updateFromProbe($contact_id, '', false);
1486                         }
1487                 } else {
1488                         $fields = ['url', 'nurl', 'addr', 'alias', 'name', 'nick', 'keywords', 'location', 'about', 'avatar-date', 'baseurl', 'gsid'];
1489                         $contact = DBA::selectFirst('contact', $fields, ['id' => $contact_id]);
1490
1491                         // This condition should always be true
1492                         if (!DBA::isResult($contact)) {
1493                                 return $contact_id;
1494                         }
1495
1496                         $updated = [
1497                                 'url' => $data['url'],
1498                                 'nurl' => Strings::normaliseLink($data['url']),
1499                                 'updated' => DateTimeFormat::utcNow(),
1500                                 'failed' => false
1501                         ];
1502
1503                         $fields = ['addr', 'alias', 'name', 'nick', 'keywords', 'location', 'about', 'baseurl', 'gsid'];
1504
1505                         foreach ($fields as $field) {
1506                                 $updated[$field] = ($data[$field] ?? '') ?: $contact[$field];
1507                         }
1508
1509                         if (($updated['addr'] != $contact['addr']) || (!empty($data['alias']) && ($data['alias'] != $contact['alias']))) {
1510                                 $updated['uri-date'] = DateTimeFormat::utcNow();
1511                         }
1512
1513                         if (($data['name'] != $contact['name']) || ($data['nick'] != $contact['nick'])) {
1514                                 $updated['name-date'] = DateTimeFormat::utcNow();
1515                         }
1516
1517                         DBA::update('contact', $updated, ['id' => $contact_id], $contact);
1518                 }
1519
1520                 return $contact_id;
1521         }
1522
1523         /**
1524          * Checks if the contact is archived
1525          *
1526          * @param int $cid contact id
1527          *
1528          * @return boolean Is the contact archived?
1529          * @throws HTTPException\InternalServerErrorException
1530          */
1531         public static function isArchived(int $cid)
1532         {
1533                 if ($cid == 0) {
1534                         return false;
1535                 }
1536
1537                 $contact = DBA::selectFirst('contact', ['archive', 'url', 'batch'], ['id' => $cid]);
1538                 if (!DBA::isResult($contact)) {
1539                         return false;
1540                 }
1541
1542                 if ($contact['archive']) {
1543                         return true;
1544                 }
1545
1546                 // Check status of ActivityPub endpoints
1547                 $apcontact = APContact::getByURL($contact['url'], false);
1548                 if (!empty($apcontact)) {
1549                         if (!empty($apcontact['inbox']) && DBA::exists('inbox-status', ['archive' => true, 'url' => $apcontact['inbox']])) {
1550                                 return true;
1551                         }
1552
1553                         if (!empty($apcontact['sharedinbox']) && DBA::exists('inbox-status', ['archive' => true, 'url' => $apcontact['sharedinbox']])) {
1554                                 return true;
1555                         }
1556                 }
1557
1558                 // Check status of Diaspora endpoints
1559                 if (!empty($contact['batch'])) {
1560                         $condition = ['archive' => true, 'uid' => 0, 'network' => Protocol::FEDERATED, 'batch' => $contact['batch'], 'contact-type' => self::TYPE_RELAY];
1561                         return DBA::exists('contact', $condition);
1562                 }
1563
1564                 return false;
1565         }
1566
1567         /**
1568          * Checks if the contact is blocked
1569          *
1570          * @param int $cid contact id
1571          *
1572          * @return boolean Is the contact blocked?
1573          * @throws HTTPException\InternalServerErrorException
1574          */
1575         public static function isBlocked($cid)
1576         {
1577                 if ($cid == 0) {
1578                         return false;
1579                 }
1580
1581                 $blocked = DBA::selectFirst('contact', ['blocked', 'url'], ['id' => $cid]);
1582                 if (!DBA::isResult($blocked)) {
1583                         return false;
1584                 }
1585
1586                 if (Network::isUrlBlocked($blocked['url'])) {
1587                         return true;
1588                 }
1589
1590                 return (bool) $blocked['blocked'];
1591         }
1592
1593         /**
1594          * Checks if the contact is hidden
1595          *
1596          * @param int $cid contact id
1597          *
1598          * @return boolean Is the contact hidden?
1599          * @throws \Exception
1600          */
1601         public static function isHidden($cid)
1602         {
1603                 if ($cid == 0) {
1604                         return false;
1605                 }
1606
1607                 $hidden = DBA::selectFirst('contact', ['hidden'], ['id' => $cid]);
1608                 if (!DBA::isResult($hidden)) {
1609                         return false;
1610                 }
1611                 return (bool) $hidden['hidden'];
1612         }
1613
1614         /**
1615          * Returns posts from a given contact url
1616          *
1617          * @param string $contact_url Contact URL
1618          * @param bool   $thread_mode
1619          * @param int    $update
1620          * @return string posts in HTML
1621          * @throws \Exception
1622          */
1623         public static function getPostsFromUrl($contact_url, $thread_mode = false, $update = 0)
1624         {
1625                 return self::getPostsFromId(self::getIdForURL($contact_url), $thread_mode, $update);
1626         }
1627
1628         /**
1629          * Returns posts from a given contact id
1630          *
1631          * @param integer $cid
1632          * @param bool    $thread_mode
1633          * @param integer $update
1634          * @return string posts in HTML
1635          * @throws \Exception
1636          */
1637         public static function getPostsFromId($cid, $thread_mode = false, $update = 0)
1638         {
1639                 $a = DI::app();
1640
1641                 $contact = DBA::selectFirst('contact', ['contact-type', 'network'], ['id' => $cid]);
1642                 if (!DBA::isResult($contact)) {
1643                         return '';
1644                 }
1645
1646                 if (empty($contact["network"]) || in_array($contact["network"], Protocol::FEDERATED)) {
1647                         $sql = "(`item`.`uid` = 0 OR (`item`.`uid` = ? AND NOT `item`.`global`))";
1648                 } else {
1649                         $sql = "`item`.`uid` = ?";
1650                 }
1651
1652                 $contact_field = ((($contact["contact-type"] == self::TYPE_COMMUNITY) || ($contact['network'] == Protocol::MAIL)) ? 'owner-id' : 'author-id');
1653
1654                 if ($thread_mode) {
1655                         $condition = ["`$contact_field` = ? AND `gravity` = ? AND " . $sql,
1656                                 $cid, GRAVITY_PARENT, local_user()];
1657                 } else {
1658                         $condition = ["`$contact_field` = ? AND `gravity` IN (?, ?) AND " . $sql,
1659                                 $cid, GRAVITY_PARENT, GRAVITY_COMMENT, local_user()];
1660                 }
1661
1662                 if (DI::mode()->isMobile()) {
1663                         $itemsPerPage = DI::pConfig()->get(local_user(), 'system', 'itemspage_mobile_network',
1664                                 DI::config()->get('system', 'itemspage_network_mobile'));
1665                 } else {
1666                         $itemsPerPage = DI::pConfig()->get(local_user(), 'system', 'itemspage_network',
1667                                 DI::config()->get('system', 'itemspage_network'));
1668                 }
1669
1670                 $pager = new Pager(DI::l10n(), DI::args()->getQueryString(), $itemsPerPage);
1671
1672                 $params = ['order' => ['received' => true],
1673                         'limit' => [$pager->getStart(), $pager->getItemsPerPage()]];
1674
1675                 if ($thread_mode) {
1676                         $r = Item::selectThreadForUser(local_user(), ['uri'], $condition, $params);
1677
1678                         $items = Item::inArray($r);
1679
1680                         $o = conversation($a, $items, 'contacts', $update, false, 'commented', local_user());
1681                 } else {
1682                         $r = Item::selectForUser(local_user(), [], $condition, $params);
1683
1684                         $items = Item::inArray($r);
1685
1686                         $o = conversation($a, $items, 'contact-posts', false);
1687                 }
1688
1689                 if (!$update) {
1690                         $o .= $pager->renderMinimal(count($items));
1691                 }
1692
1693                 return $o;
1694         }
1695
1696         /**
1697          * Returns the account type name
1698          *
1699          * The function can be called with either the user or the contact array
1700          *
1701          * @param array $contact contact or user array
1702          * @return string
1703          */
1704         public static function getAccountType(array $contact)
1705         {
1706                 // There are several fields that indicate that the contact or user is a forum
1707                 // "page-flags" is a field in the user table,
1708                 // "forum" and "prv" are used in the contact table. They stand for User::PAGE_FLAGS_COMMUNITY and User::PAGE_FLAGS_PRVGROUP.
1709                 // "community" is used in the gcontact table and is true if the contact is User::PAGE_FLAGS_COMMUNITY or User::PAGE_FLAGS_PRVGROUP.
1710                 if ((isset($contact['page-flags']) && (intval($contact['page-flags']) == User::PAGE_FLAGS_COMMUNITY))
1711                         || (isset($contact['page-flags']) && (intval($contact['page-flags']) == User::PAGE_FLAGS_PRVGROUP))
1712                         || (isset($contact['forum']) && intval($contact['forum']))
1713                         || (isset($contact['prv']) && intval($contact['prv']))
1714                         || (isset($contact['community']) && intval($contact['community']))
1715                 ) {
1716                         $type = self::TYPE_COMMUNITY;
1717                 } else {
1718                         $type = self::TYPE_PERSON;
1719                 }
1720
1721                 // The "contact-type" (contact table) and "account-type" (user table) are more general then the chaos from above.
1722                 if (isset($contact["contact-type"])) {
1723                         $type = $contact["contact-type"];
1724                 }
1725
1726                 if (isset($contact["account-type"])) {
1727                         $type = $contact["account-type"];
1728                 }
1729
1730                 switch ($type) {
1731                         case self::TYPE_ORGANISATION:
1732                                 $account_type = DI::l10n()->t("Organisation");
1733                                 break;
1734
1735                         case self::TYPE_NEWS:
1736                                 $account_type = DI::l10n()->t('News');
1737                                 break;
1738
1739                         case self::TYPE_COMMUNITY:
1740                                 $account_type = DI::l10n()->t("Forum");
1741                                 break;
1742
1743                         default:
1744                                 $account_type = "";
1745                                 break;
1746                 }
1747
1748                 return $account_type;
1749         }
1750
1751         /**
1752          * Blocks a contact
1753          *
1754          * @param int $cid
1755          * @return bool
1756          * @throws \Exception
1757          */
1758         public static function block($cid, $reason = null)
1759         {
1760                 $return = DBA::update('contact', ['blocked' => true, 'block_reason' => $reason], ['id' => $cid]);
1761
1762                 return $return;
1763         }
1764
1765         /**
1766          * Unblocks a contact
1767          *
1768          * @param int $cid
1769          * @return bool
1770          * @throws \Exception
1771          */
1772         public static function unblock($cid)
1773         {
1774                 $return = DBA::update('contact', ['blocked' => false, 'block_reason' => null], ['id' => $cid]);
1775
1776                 return $return;
1777         }
1778
1779         /**
1780          * Ensure that cached avatar exist
1781          *
1782          * @param integer $cid
1783          */
1784         public static function checkAvatarCache(int $cid)
1785         {
1786                 $contact = DBA::selectFirst('contact', ['url', 'avatar', 'photo', 'thumb', 'micro'], ['id' => $cid, 'uid' => 0, 'self' => false]);
1787                 if (!DBA::isResult($contact)) {
1788                         return;
1789                 }
1790
1791                 if (empty($contact['avatar']) || (!empty($contact['photo']) && !empty($contact['thumb']) && !empty($contact['micro']))) {
1792                         return;
1793                 }
1794
1795                 Logger::info('Adding avatar cache', ['id' => $cid, 'contact' => $contact]);
1796
1797                 self::updateAvatar($cid, $contact['avatar'], true);
1798         }
1799
1800         /**
1801          * Return the photo path for a given contact array in the given size
1802          *
1803          * @param array $contact  contact array
1804          * @param string $field   Fieldname of the photo in the contact array
1805          * @param string $default Default path when no picture had been found
1806          * @param string $size    Size of the avatar picture
1807          * @param string $avatar  Avatar path that is displayed when no photo had been found
1808          * @return string photo path
1809          */
1810         private static function getAvatarPath(array $contact, string $field, string $default, string $size, string $avatar)
1811         {
1812                 if (!empty($contact)) {
1813                         $contact = self::checkAvatarCacheByArray($contact);
1814                         if (!empty($contact[$field])) {
1815                                 $avatar = $contact[$field];
1816                         }
1817                 }
1818
1819                 if (empty($avatar)) {
1820                         return $default;
1821                 }
1822
1823                 if (Proxy::isLocalImage($avatar)) {
1824                         return $avatar;
1825                 } else {
1826                         return Proxy::proxifyUrl($avatar, false, $size);
1827                 }
1828         }
1829
1830         /**
1831          * Return the photo path for a given contact array
1832          *
1833          * @param array $contact Contact array
1834          * @param string $avatar  Avatar path that is displayed when no photo had been found
1835          * @return string photo path
1836          */
1837         public static function getPhoto(array $contact, string $avatar = '')
1838         {
1839                 return self::getAvatarPath($contact, 'photo', DI::baseUrl() . '/images/person-300.jpg', Proxy::SIZE_SMALL, $avatar);
1840         }
1841
1842         /**
1843          * Return the photo path (thumb size) for a given contact array
1844          *
1845          * @param array $contact Contact array
1846          * @param string $avatar  Avatar path that is displayed when no photo had been found
1847          * @return string photo path
1848          */
1849         public static function getThumb(array $contact, string $avatar = '')
1850         {
1851                 return self::getAvatarPath($contact, 'thumb', DI::baseUrl() . '/images/person-80.jpg', Proxy::SIZE_THUMB, $avatar);
1852         }
1853
1854         /**
1855          * Return the photo path (micro size) for a given contact array
1856          *
1857          * @param array $contact Contact array
1858          * @param string $avatar  Avatar path that is displayed when no photo had been found
1859          * @return string photo path
1860          */
1861         public static function getMicro(array $contact, string $avatar = '')
1862         {
1863                 return self::getAvatarPath($contact, 'micro', DI::baseUrl() . '/images/person-48.jpg', Proxy::SIZE_MICRO, $avatar);
1864         }
1865
1866         /**
1867          * Check the given contact array for avatar cache fields
1868          *
1869          * @param array $contact
1870          * @return array contact array with avatar cache fields
1871          */
1872         private static function checkAvatarCacheByArray(array $contact)
1873         {
1874                 $update = false;
1875                 $contact_fields = [];
1876                 $fields = ['photo', 'thumb', 'micro'];
1877                 foreach ($fields as $field) {
1878                         if (isset($contact[$field])) {
1879                                 $contact_fields[] = $field;
1880                         }
1881                         if (isset($contact[$field]) && empty($contact[$field])) {
1882                                 $update = true;
1883                         }
1884                 }
1885
1886                 if (!$update) {
1887                         return $contact;
1888                 }
1889
1890                 if (!empty($contact['id']) && !empty($contact['avatar'])) {
1891                         self::updateAvatar($contact['id'], $contact['avatar'], true);
1892
1893                         $new_contact = self::getById($contact['id'], $contact_fields);
1894                         if (DBA::isResult($new_contact)) {
1895                                 // We only update the cache fields
1896                                 $contact = array_merge($contact, $new_contact);
1897                         }
1898                 }
1899
1900                 /// add the default avatars if the fields aren't filled
1901                 if (isset($contact['photo']) && empty($contact['photo'])) {
1902                         $contact['photo'] = DI::baseUrl() . '/images/person-300.jpg';
1903                 }
1904                 if (isset($contact['thumb']) && empty($contact['thumb'])) {
1905                         $contact['thumb'] = DI::baseUrl() . '/images/person-80.jpg';
1906                 }
1907                 if (isset($contact['micro']) && empty($contact['micro'])) {
1908                         $contact['micro'] = DI::baseUrl() . '/images/person-48.jpg';
1909                 }
1910
1911                 return $contact;
1912         }
1913
1914         /**
1915          * Updates the avatar links in a contact only if needed
1916          *
1917          * @param int    $cid    Contact id
1918          * @param string $avatar Link to avatar picture
1919          * @param bool   $force  force picture update
1920          *
1921          * @return void
1922          * @throws HTTPException\InternalServerErrorException
1923          * @throws HTTPException\NotFoundException
1924          * @throws \ImagickException
1925          */
1926         public static function updateAvatar(int $cid, string $avatar, bool $force = false)
1927         {
1928                 $contact = DBA::selectFirst('contact', ['uid', 'avatar', 'photo', 'thumb', 'micro', 'nurl'], ['id' => $cid, 'self' => false]);
1929                 if (!DBA::isResult($contact)) {
1930                         return;
1931                 }
1932
1933                 $uid = $contact['uid'];
1934
1935                 // Only update the cached photo links of public contacts when they already are cached
1936                 if (($uid == 0) && !$force && empty($contact['thumb']) && empty($contact['micro'])) {
1937                         if ($contact['avatar'] != $avatar) {
1938                                 DBA::update('contact', ['avatar' => $avatar], ['id' => $cid]);
1939                                 Logger::info('Only update the avatar', ['id' => $cid, 'avatar' => $avatar, 'contact' => $contact]);
1940                         }
1941                         return;
1942                 }
1943
1944                 $data = [
1945                         $contact['photo'] ?? '',
1946                         $contact['thumb'] ?? '',
1947                         $contact['micro'] ?? '',
1948                 ];
1949
1950                 $update = ($contact['avatar'] != $avatar) || $force;
1951
1952                 if (!$update) {
1953                         foreach ($data as $image_uri) {
1954                                 $image_rid = Photo::ridFromURI($image_uri);
1955                                 if ($image_rid && !Photo::exists(['resource-id' => $image_rid, 'uid' => $uid])) {
1956                                         Logger::info('Regenerating avatar', ['contact uid' => $uid, 'cid' => $cid, 'missing photo' => $image_rid, 'avatar' => $contact['avatar']]);
1957                                         $update = true;
1958                                 }
1959                         }
1960                 }
1961
1962                 if ($update) {
1963                         $photos = Photo::importProfilePhoto($avatar, $uid, $cid, true);
1964                         if ($photos) {
1965                                 $fields = ['avatar' => $avatar, 'photo' => $photos[0], 'thumb' => $photos[1], 'micro' => $photos[2], 'avatar-date' => DateTimeFormat::utcNow()];
1966                                 DBA::update('contact', $fields, ['id' => $cid]);
1967                         } elseif (empty($contact['avatar'])) {
1968                                 // Ensure that the avatar field is set
1969                                 DBA::update('contact', ['avatar' => $avatar], ['id' => $cid]);                          
1970                                 Logger::info('Failed profile import', ['id' => $cid, 'force' => $force, 'avatar' => $avatar, 'contact' => $contact]);
1971                         }
1972                 }
1973         }
1974
1975         /**
1976          * Helper function for "updateFromProbe". Updates personal and public contact
1977          *
1978          * @param integer $id      contact id
1979          * @param integer $uid     user id
1980          * @param string  $url     The profile URL of the contact
1981          * @param array   $fields  The fields that are updated
1982          *
1983          * @throws \Exception
1984          */
1985         private static function updateContact($id, $uid, $url, array $fields)
1986         {
1987                 if (!DBA::update('contact', $fields, ['id' => $id])) {
1988                         Logger::info('Couldn\'t update contact.', ['id' => $id, 'fields' => $fields]);
1989                         return;
1990                 }
1991
1992                 // Search for duplicated contacts and get rid of them
1993                 if (self::removeDuplicates(Strings::normaliseLink($url), $uid) || ($uid != 0)) {
1994                         return;
1995                 }
1996
1997                 // Update the corresponding gcontact entry
1998                 GContact::updateFromPublicContactID($id);
1999
2000                 // Archive or unarchive the contact. We only need to do this for the public contact.
2001                 // The archive/unarchive function will update the personal contacts by themselves.
2002                 $contact = DBA::selectFirst('contact', [], ['id' => $id]);
2003                 if (!DBA::isResult($contact)) {
2004                         Logger::info('Couldn\'t select contact for archival.', ['id' => $id]);
2005                         return;
2006                 }
2007
2008                 if (!empty($fields['success_update'])) {
2009                         self::unmarkForArchival($contact);
2010                 } elseif (!empty($fields['failure_update'])) {
2011                         self::markForArchival($contact);
2012                 }
2013
2014                 $condition = ['self' => false, 'nurl' => Strings::normaliseLink($url), 'network' => Protocol::FEDERATED];
2015
2016                 // These contacts are sharing with us, we don't poll them.
2017                 // This means that we don't set the update fields in "OnePoll.php".
2018                 $condition['rel'] = self::SHARING;
2019                 DBA::update('contact', $fields, $condition);
2020
2021                 unset($fields['last-update']);
2022                 unset($fields['success_update']);
2023                 unset($fields['failure_update']);
2024
2025                 if (empty($fields)) {
2026                         return;
2027                 }
2028
2029                 // We are polling these contacts, so we mustn't set the update fields here.
2030                 $condition['rel'] = [self::FOLLOWER, self::FRIEND];
2031                 DBA::update('contact', $fields, $condition);
2032         }
2033
2034         /**
2035          * Remove duplicated contacts
2036          *
2037          * @param string  $nurl  Normalised contact url
2038          * @param integer $uid   User id
2039          * @return boolean
2040          * @throws \Exception
2041          */
2042         public static function removeDuplicates(string $nurl, int $uid)
2043         {
2044                 $condition = ['nurl' => $nurl, 'uid' => $uid, 'deleted' => false, 'network' => Protocol::FEDERATED];
2045                 $count = DBA::count('contact', $condition);
2046                 if ($count <= 1) {
2047                         return false;
2048                 }
2049
2050                 $first_contact = DBA::selectFirst('contact', ['id', 'network'], $condition, ['order' => ['id']]);
2051                 if (!DBA::isResult($first_contact)) {
2052                         // Shouldn't happen - so we handle it
2053                         return false;
2054                 }
2055
2056                 $first = $first_contact['id'];
2057                 Logger::info('Found duplicates', ['count' => $count, 'first' => $first, 'uid' => $uid, 'nurl' => $nurl]);
2058                 if (($uid != 0 && ($first_contact['network'] == Protocol::DFRN))) {
2059                         // Don't handle non public DFRN duplicates by now (legacy DFRN is very special because of the key handling)
2060                         Logger::info('Not handling non public DFRN duplicate', ['uid' => $uid, 'nurl' => $nurl]);
2061                         return false;
2062                 }
2063
2064                 // Find all duplicates
2065                 $condition = ["`nurl` = ? AND `uid` = ? AND `id` != ? AND NOT `self` AND NOT `deleted`", $nurl, $uid, $first];
2066                 $duplicates = DBA::select('contact', ['id', 'network'], $condition);
2067                 while ($duplicate = DBA::fetch($duplicates)) {
2068                         if (!in_array($duplicate['network'], Protocol::FEDERATED)) {
2069                                 continue;
2070                         }
2071
2072                         Worker::add(PRIORITY_HIGH, 'MergeContact', $first, $duplicate['id'], $uid);
2073                 }
2074                 DBA::close($duplicates);
2075                 Logger::info('Duplicates handled', ['uid' => $uid, 'nurl' => $nurl]);
2076                 return true;
2077         }
2078
2079         /**
2080          * @param integer $id      contact id
2081          * @param string  $network Optional network we are probing for
2082          * @param boolean $force   Optional forcing of network probing (otherwise we use the cached data)
2083          * @return boolean
2084          * @throws HTTPException\InternalServerErrorException
2085          * @throws \ImagickException
2086          */
2087         public static function updateFromProbe(int $id, string $network = '', bool $force = false)
2088         {
2089                 /*
2090                   Warning: Never ever fetch the public key via Probe::uri and write it into the contacts.
2091                   This will reliably kill your communication with old Friendica contacts.
2092                  */
2093
2094                 // These fields aren't updated by this routine:
2095                 // 'xmpp', 'sensitive'
2096
2097                 $fields = ['uid', 'avatar', 'name', 'nick', 'location', 'keywords', 'about', 'subscribe',
2098                         'unsearchable', 'url', 'addr', 'batch', 'notify', 'poll', 'request', 'confirm', 'poco',
2099                         'network', 'alias', 'baseurl', 'gsid', 'forum', 'prv', 'contact-type', 'pubkey'];
2100                 $contact = DBA::selectFirst('contact', $fields, ['id' => $id]);
2101                 if (!DBA::isResult($contact)) {
2102                         return false;
2103                 }
2104
2105                 $uid = $contact['uid'];
2106                 unset($contact['uid']);
2107
2108                 $pubkey = $contact['pubkey'];
2109                 unset($contact['pubkey']);
2110
2111                 $contact['photo'] = $contact['avatar'];
2112                 unset($contact['avatar']);
2113
2114                 $ret = Probe::uri($contact['url'], $network, $uid, !$force);
2115
2116                 $updated = DateTimeFormat::utcNow();
2117
2118                 // We must not try to update relay contacts via probe. They are no real contacts.
2119                 // We check after the probing to be able to correct falsely detected contact types.
2120                 if (($contact['contact-type'] == self::TYPE_RELAY) &&
2121                         (!Strings::compareLink($ret['url'], $contact['url']) || in_array($ret['network'], [Protocol::FEED, Protocol::PHANTOM]))) {
2122                         self::updateContact($id, $uid, $contact['url'], ['failed' => false, 'last-update' => $updated, 'success_update' => $updated]);
2123                         Logger::info('Not updating relais', ['id' => $id, 'url' => $contact['url']]);
2124                         return true;
2125                 }
2126
2127                 // If Probe::uri fails the network code will be different ("feed" or "unkn")
2128                 if (in_array($ret['network'], [Protocol::FEED, Protocol::PHANTOM]) && ($ret['network'] != $contact['network'])) {
2129                         if ($force && ($uid == 0)) {
2130                                 self::updateContact($id, $uid, $ret['url'], ['failed' => true, 'last-update' => $updated, 'failure_update' => $updated]);
2131                         }
2132                         return false;
2133                 }
2134
2135                 if (ContactRelation::isDiscoverable($ret['url'])) {
2136                         Worker::add(PRIORITY_LOW, 'ContactDiscovery', $ret['url']);
2137                 }
2138
2139                 if (isset($ret['hide']) && is_bool($ret['hide'])) {
2140                         $ret['unsearchable'] = $ret['hide'];
2141                 }
2142
2143                 if (isset($ret['account-type']) && is_int($ret['account-type'])) {
2144                         $ret['forum'] = false;
2145                         $ret['prv'] = false;
2146                         $ret['contact-type'] = $ret['account-type'];
2147                         if ($ret['contact-type'] == User::ACCOUNT_TYPE_COMMUNITY) {
2148                                 $apcontact = APContact::getByURL($ret['url'], false);
2149                                 if (isset($apcontact['manually-approve'])) {
2150                                         $ret['forum'] = (bool)!$apcontact['manually-approve'];
2151                                         $ret['prv'] = (bool)!$ret['forum'];
2152                                 }
2153                         }
2154                 }
2155
2156                 $new_pubkey = $ret['pubkey'];
2157
2158                 // Update the gcontact entry
2159                 if ($uid == 0) {
2160                         GContact::updateFromPublicContactID($id);
2161                 }
2162
2163                 $update = false;
2164
2165                 // make sure to not overwrite existing values with blank entries except some technical fields
2166                 $keep = ['batch', 'notify', 'poll', 'request', 'confirm', 'poco', 'baseurl'];
2167                 foreach ($ret as $key => $val) {
2168                         if (!array_key_exists($key, $contact)) {
2169                                 unset($ret[$key]);
2170                         } elseif (($contact[$key] != '') && ($val === '') && !is_bool($ret[$key]) && !in_array($key, $keep)) {
2171                                 $ret[$key] = $contact[$key];
2172                         } elseif ($ret[$key] != $contact[$key]) {
2173                                 $update = true;
2174                         }
2175                 }
2176
2177                 if (!empty($ret['photo']) && ($ret['network'] != Protocol::FEED)) {
2178                         self::updateAvatar($id, $ret['photo'], $update || $force);
2179                 }
2180
2181                 if (!$update) {
2182                         if ($force) {
2183                                 self::updateContact($id, $uid, $ret['url'], ['failed' => false, 'last-update' => $updated, 'success_update' => $updated]);
2184                         }
2185
2186                         // Update the public contact
2187                         if ($uid != 0) {
2188                                 self::updateFromProbeByURL($ret['url']);
2189                         }
2190
2191                         return true;
2192                 }
2193
2194                 $ret['nurl'] = Strings::normaliseLink($ret['url']);
2195                 $ret['updated'] = $updated;
2196
2197                 // Only fill the pubkey if it had been empty before. We have to prevent identity theft.
2198                 if (empty($pubkey) && !empty($new_pubkey)) {
2199                         $ret['pubkey'] = $new_pubkey;
2200                 }
2201
2202                 if (($ret['addr'] != $contact['addr']) || (!empty($ret['alias']) && ($ret['alias'] != $contact['alias']))) {
2203                         $ret['uri-date'] = DateTimeFormat::utcNow();
2204                 }
2205
2206                 if (($ret['name'] != $contact['name']) || ($ret['nick'] != $contact['nick'])) {
2207                         $ret['name-date'] = $updated;
2208                 }
2209
2210                 if ($force && ($uid == 0)) {
2211                         $ret['last-update'] = $updated;
2212                         $ret['success_update'] = $updated;
2213                         $ret['failed'] = false;
2214                 }
2215
2216                 unset($ret['photo']);
2217
2218                 self::updateContact($id, $uid, $ret['url'], $ret);
2219
2220                 return true;
2221         }
2222
2223         public static function updateFromProbeByURL($url, $force = false)
2224         {
2225                 $id = self::getIdForURL($url);
2226
2227                 if (empty($id)) {
2228                         return $id;
2229                 }
2230
2231                 self::updateFromProbe($id, '', $force);
2232
2233                 return $id;
2234         }
2235
2236         /**
2237          * Detects if a given contact array belongs to a legacy DFRN connection
2238          *
2239          * @param array $contact
2240          * @return boolean
2241          */
2242         public static function isLegacyDFRNContact($contact)
2243         {
2244                 // Newer Friendica contacts are connected via AP, then these fields aren't set
2245                 return !empty($contact['dfrn-id']) || !empty($contact['issued-id']);
2246         }
2247
2248         /**
2249          * Detects the communication protocol for a given contact url.
2250          * This is used to detect Friendica contacts that we can communicate via AP.
2251          *
2252          * @param string $url contact url
2253          * @param string $network Network of that contact
2254          * @return string with protocol
2255          */
2256         public static function getProtocol($url, $network)
2257         {
2258                 if ($network != Protocol::DFRN) {
2259                         return $network;
2260                 }
2261
2262                 $apcontact = APContact::getByURL($url);
2263                 if (!empty($apcontact) && !empty($apcontact['generator'])) {
2264                         return Protocol::ACTIVITYPUB;
2265                 } else {
2266                         return $network;
2267                 }
2268         }
2269
2270         /**
2271          * Takes a $uid and a url/handle and adds a new contact
2272          *
2273          * Currently if the contact is DFRN, interactive needs to be true, to redirect to the
2274          * dfrn_request page.
2275          *
2276          * Otherwise this can be used to bulk add StatusNet contacts, Twitter contacts, etc.
2277          *
2278          * Returns an array
2279          * $return['success'] boolean true if successful
2280          * $return['message'] error text if success is false.
2281          *
2282          * Takes a $uid and a url/handle and adds a new contact
2283          *
2284          * @param array  $user        The user the contact should be created for
2285          * @param string $url         The profile URL of the contact
2286          * @param bool   $interactive
2287          * @param string $network
2288          * @return array
2289          * @throws HTTPException\InternalServerErrorException
2290          * @throws HTTPException\NotFoundException
2291          * @throws \ImagickException
2292          */
2293         public static function createFromProbe(array $user, $url, $interactive = false, $network = '')
2294         {
2295                 $result = ['cid' => -1, 'success' => false, 'message' => ''];
2296
2297                 // remove ajax junk, e.g. Twitter
2298                 $url = str_replace('/#!/', '/', $url);
2299
2300                 if (!Network::isUrlAllowed($url)) {
2301                         $result['message'] = DI::l10n()->t('Disallowed profile URL.');
2302                         return $result;
2303                 }
2304
2305                 if (Network::isUrlBlocked($url)) {
2306                         $result['message'] = DI::l10n()->t('Blocked domain');
2307                         return $result;
2308                 }
2309
2310                 if (!$url) {
2311                         $result['message'] = DI::l10n()->t('Connect URL missing.');
2312                         return $result;
2313                 }
2314
2315                 $arr = ['url' => $url, 'contact' => []];
2316
2317                 Hook::callAll('follow', $arr);
2318
2319                 if (empty($arr)) {
2320                         $result['message'] = DI::l10n()->t('The contact could not be added. Please check the relevant network credentials in your Settings -> Social Networks page.');
2321                         return $result;
2322                 }
2323
2324                 if (!empty($arr['contact']['name'])) {
2325                         $ret = $arr['contact'];
2326                 } else {
2327                         $ret = Probe::uri($url, $network, $user['uid'], false);
2328                 }
2329
2330                 if (($network != '') && ($ret['network'] != $network)) {
2331                         Logger::log('Expected network ' . $network . ' does not match actual network ' . $ret['network']);
2332                         return $result;
2333                 }
2334
2335                 // check if we already have a contact
2336                 // the poll url is more reliable than the profile url, as we may have
2337                 // indirect links or webfinger links
2338
2339                 $condition = ['uid' => $user['uid'], 'poll' => [$ret['poll'], Strings::normaliseLink($ret['poll'])], 'network' => $ret['network'], 'pending' => false];
2340                 $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
2341                 if (!DBA::isResult($contact)) {
2342                         $condition = ['uid' => $user['uid'], 'nurl' => Strings::normaliseLink($ret['url']), 'network' => $ret['network'], 'pending' => false];
2343                         $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
2344                 }
2345
2346                 $protocol = self::getProtocol($ret['url'], $ret['network']);
2347
2348                 if (($protocol === Protocol::DFRN) && !DBA::isResult($contact)) {
2349                         if ($interactive) {
2350                                 if (strlen(DI::baseUrl()->getUrlPath())) {
2351                                         $myaddr = bin2hex(DI::baseUrl() . '/profile/' . $user['nickname']);
2352                                 } else {
2353                                         $myaddr = bin2hex($user['nickname'] . '@' . DI::baseUrl()->getHostname());
2354                                 }
2355
2356                                 DI::baseUrl()->redirect($ret['request'] . "&addr=$myaddr");
2357
2358                                 // NOTREACHED
2359                         }
2360                 } elseif (DI::config()->get('system', 'dfrn_only') && ($ret['network'] != Protocol::DFRN)) {
2361                         $result['message'] = DI::l10n()->t('This site is not configured to allow communications with other networks.') . EOL;
2362                         $result['message'] .= DI::l10n()->t('No compatible communication protocols or feeds were discovered.') . EOL;
2363                         return $result;
2364                 }
2365
2366                 // This extra param just confuses things, remove it
2367                 if ($protocol === Protocol::DIASPORA) {
2368                         $ret['url'] = str_replace('?absolute=true', '', $ret['url']);
2369                 }
2370
2371                 // do we have enough information?
2372                 if (empty($ret['name']) || empty($ret['poll']) || (empty($ret['url']) && empty($ret['addr']))) {
2373                         $result['message'] .= DI::l10n()->t('The profile address specified does not provide adequate information.') . EOL;
2374                         if (empty($ret['poll'])) {
2375                                 $result['message'] .= DI::l10n()->t('No compatible communication protocols or feeds were discovered.') . EOL;
2376                         }
2377                         if (empty($ret['name'])) {
2378                                 $result['message'] .= DI::l10n()->t('An author or name was not found.') . EOL;
2379                         }
2380                         if (empty($ret['url'])) {
2381                                 $result['message'] .= DI::l10n()->t('No browser URL could be matched to this address.') . EOL;
2382                         }
2383                         if (strpos($ret['url'], '@') !== false) {
2384                                 $result['message'] .= DI::l10n()->t('Unable to match @-style Identity Address with a known protocol or email contact.') . EOL;
2385                                 $result['message'] .= DI::l10n()->t('Use mailto: in front of address to force email check.') . EOL;
2386                         }
2387                         return $result;
2388                 }
2389
2390                 if ($protocol === Protocol::OSTATUS && DI::config()->get('system', 'ostatus_disabled')) {
2391                         $result['message'] .= DI::l10n()->t('The profile address specified belongs to a network which has been disabled on this site.') . EOL;
2392                         $ret['notify'] = '';
2393                 }
2394
2395                 if (!$ret['notify']) {
2396                         $result['message'] .= DI::l10n()->t('Limited profile. This person will be unable to receive direct/personal notifications from you.') . EOL;
2397                 }
2398
2399                 $writeable = ((($protocol === Protocol::OSTATUS) && ($ret['notify'])) ? 1 : 0);
2400
2401                 $subhub = (($protocol === Protocol::OSTATUS) ? true : false);
2402
2403                 $hidden = (($protocol === Protocol::MAIL) ? 1 : 0);
2404
2405                 $pending = false;
2406                 if ($protocol == Protocol::ACTIVITYPUB) {
2407                         $apcontact = APContact::getByURL($ret['url'], false);
2408                         if (isset($apcontact['manually-approve'])) {
2409                                 $pending = (bool)$apcontact['manually-approve'];
2410                         }
2411                 }
2412
2413                 if (in_array($protocol, [Protocol::MAIL, Protocol::DIASPORA, Protocol::ACTIVITYPUB])) {
2414                         $writeable = 1;
2415                 }
2416
2417                 if (DBA::isResult($contact)) {
2418                         // update contact
2419                         $new_relation = (($contact['rel'] == self::FOLLOWER) ? self::FRIEND : self::SHARING);
2420
2421                         $fields = ['rel' => $new_relation, 'subhub' => $subhub, 'readonly' => false];
2422                         DBA::update('contact', $fields, ['id' => $contact['id']]);
2423                 } else {
2424                         $new_relation = (in_array($protocol, [Protocol::MAIL]) ? self::FRIEND : self::SHARING);
2425
2426                         // create contact record
2427                         self::insert([
2428                                 'uid'     => $user['uid'],
2429                                 'created' => DateTimeFormat::utcNow(),
2430                                 'url'     => $ret['url'],
2431                                 'nurl'    => Strings::normaliseLink($ret['url']),
2432                                 'addr'    => $ret['addr'],
2433                                 'alias'   => $ret['alias'],
2434                                 'batch'   => $ret['batch'],
2435                                 'notify'  => $ret['notify'],
2436                                 'poll'    => $ret['poll'],
2437                                 'poco'    => $ret['poco'],
2438                                 'name'    => $ret['name'],
2439                                 'nick'    => $ret['nick'],
2440                                 'network' => $ret['network'],
2441                                 'baseurl' => $ret['baseurl'],
2442                                 'gsid'    => $ret['gsid'] ?? null,
2443                                 'protocol' => $protocol,
2444                                 'pubkey'  => $ret['pubkey'],
2445                                 'rel'     => $new_relation,
2446                                 'priority'=> $ret['priority'],
2447                                 'writable'=> $writeable,
2448                                 'hidden'  => $hidden,
2449                                 'blocked' => 0,
2450                                 'readonly'=> 0,
2451                                 'pending' => $pending,
2452                                 'subhub'  => $subhub
2453                         ]);
2454                 }
2455
2456                 $contact = DBA::selectFirst('contact', [], ['url' => $ret['url'], 'network' => $ret['network'], 'uid' => $user['uid']]);
2457                 if (!DBA::isResult($contact)) {
2458                         $result['message'] .= DI::l10n()->t('Unable to retrieve contact information.') . EOL;
2459                         return $result;
2460                 }
2461
2462                 $contact_id = $contact['id'];
2463                 $result['cid'] = $contact_id;
2464
2465                 Group::addMember(User::getDefaultGroup($user['uid'], $contact["network"]), $contact_id);
2466
2467                 // Update the avatar
2468                 self::updateAvatar($contact_id, $ret['photo']);
2469
2470                 // pull feed and consume it, which should subscribe to the hub.
2471
2472                 Worker::add(PRIORITY_HIGH, "OnePoll", $contact_id, "force");
2473
2474                 $owner = User::getOwnerDataById($user['uid']);
2475
2476                 if (DBA::isResult($owner)) {
2477                         if (in_array($protocol, [Protocol::OSTATUS, Protocol::DFRN])) {
2478                                 // create a follow slap
2479                                 $item = [];
2480                                 $item['verb'] = Activity::FOLLOW;
2481                                 $item['gravity'] = GRAVITY_ACTIVITY;
2482                                 $item['follow'] = $contact["url"];
2483                                 $item['body'] = '';
2484                                 $item['title'] = '';
2485                                 $item['guid'] = '';
2486                                 $item['uri-id'] = 0;
2487                                 $item['attach'] = '';
2488
2489                                 $slap = OStatus::salmon($item, $owner);
2490
2491                                 if (!empty($contact['notify'])) {
2492                                         Salmon::slapper($owner, $contact['notify'], $slap);
2493                                 }
2494                         } elseif ($protocol == Protocol::DIASPORA) {
2495                                 $ret = Diaspora::sendShare($owner, $contact);
2496                                 Logger::log('share returns: ' . $ret);
2497                         } elseif ($protocol == Protocol::ACTIVITYPUB) {
2498                                 $activity_id = ActivityPub\Transmitter::activityIDFromContact($contact_id);
2499                                 if (empty($activity_id)) {
2500                                         // This really should never happen
2501                                         return false;
2502                                 }
2503
2504                                 $ret = ActivityPub\Transmitter::sendActivity('Follow', $contact['url'], $user['uid'], $activity_id);
2505                                 Logger::log('Follow returns: ' . $ret);
2506                         }
2507                 }
2508
2509                 $result['success'] = true;
2510                 return $result;
2511         }
2512
2513         /**
2514          * Updated contact's SSL policy
2515          *
2516          * @param array  $contact    Contact array
2517          * @param string $new_policy New policy, valid: self,full
2518          *
2519          * @return array Contact array with updated values
2520          * @throws \Exception
2521          */
2522         public static function updateSslPolicy(array $contact, $new_policy)
2523         {
2524                 $ssl_changed = false;
2525                 if ((intval($new_policy) == BaseURL::SSL_POLICY_SELFSIGN || $new_policy === 'self') && strstr($contact['url'], 'https:')) {
2526                         $ssl_changed = true;
2527                         $contact['url']     =   str_replace('https:', 'http:', $contact['url']);
2528                         $contact['request'] =   str_replace('https:', 'http:', $contact['request']);
2529                         $contact['notify']  =   str_replace('https:', 'http:', $contact['notify']);
2530                         $contact['poll']    =   str_replace('https:', 'http:', $contact['poll']);
2531                         $contact['confirm'] =   str_replace('https:', 'http:', $contact['confirm']);
2532                         $contact['poco']    =   str_replace('https:', 'http:', $contact['poco']);
2533                 }
2534
2535                 if ((intval($new_policy) == BaseURL::SSL_POLICY_FULL || $new_policy === 'full') && strstr($contact['url'], 'http:')) {
2536                         $ssl_changed = true;
2537                         $contact['url']     =   str_replace('http:', 'https:', $contact['url']);
2538                         $contact['request'] =   str_replace('http:', 'https:', $contact['request']);
2539                         $contact['notify']  =   str_replace('http:', 'https:', $contact['notify']);
2540                         $contact['poll']    =   str_replace('http:', 'https:', $contact['poll']);
2541                         $contact['confirm'] =   str_replace('http:', 'https:', $contact['confirm']);
2542                         $contact['poco']    =   str_replace('http:', 'https:', $contact['poco']);
2543                 }
2544
2545                 if ($ssl_changed) {
2546                         $fields = ['url' => $contact['url'], 'request' => $contact['request'],
2547                                         'notify' => $contact['notify'], 'poll' => $contact['poll'],
2548                                         'confirm' => $contact['confirm'], 'poco' => $contact['poco']];
2549                         DBA::update('contact', $fields, ['id' => $contact['id']]);
2550                 }
2551
2552                 return $contact;
2553         }
2554
2555         /**
2556          * @param array  $importer Owner (local user) data
2557          * @param array  $contact  Existing owner-specific contact data we want to expand the relationship with. Optional.
2558          * @param array  $datarray An item-like array with at least the 'author-id' and 'author-url' keys for the contact. Mandatory.
2559          * @param bool   $sharing  True: Contact is now sharing with Owner; False: Contact is now following Owner (default)
2560          * @param string $note     Introduction additional message
2561          * @return bool|null True: follow request is accepted; False: relationship is rejected; Null: relationship is pending
2562          * @throws HTTPException\InternalServerErrorException
2563          * @throws \ImagickException
2564          */
2565         public static function addRelationship(array $importer, array $contact, array $datarray, $sharing = false, $note = '')
2566         {
2567                 // Should always be set
2568                 if (empty($datarray['author-id'])) {
2569                         return false;
2570                 }
2571
2572                 $fields = ['url', 'name', 'nick', 'avatar', 'photo', 'network', 'blocked'];
2573                 $pub_contact = DBA::selectFirst('contact', $fields, ['id' => $datarray['author-id']]);
2574                 if (!DBA::isResult($pub_contact)) {
2575                         // Should never happen
2576                         return false;
2577                 }
2578
2579                 // Contact is blocked at node-level
2580                 if (self::isBlocked($datarray['author-id'])) {
2581                         return false;
2582                 }
2583
2584                 $url = ($datarray['author-link'] ?? '') ?: $pub_contact['url'];
2585                 $name = $pub_contact['name'];
2586                 $photo = ($pub_contact['avatar'] ?? '') ?: $pub_contact["photo"];
2587                 $nick = $pub_contact['nick'];
2588                 $network = $pub_contact['network'];
2589
2590                 // Ensure that we don't create a new contact when there already is one
2591                 $cid = self::getIdForURL($url, $importer['uid']);
2592                 if (!empty($cid)) {
2593                         $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
2594                 }
2595
2596                 if (!empty($contact)) {
2597                         if (!empty($contact['pending'])) {
2598                                 Logger::info('Pending contact request already exists.', ['url' => $url, 'uid' => $importer['uid']]);
2599                                 return null;
2600                         }
2601
2602                         // Contact is blocked at user-level
2603                         if (!empty($contact['id']) && !empty($importer['id']) &&
2604                                 self::isBlockedByUser($contact['id'], $importer['id'])) {
2605                                 return false;
2606                         }
2607
2608                         // Make sure that the existing contact isn't archived
2609                         self::unmarkForArchival($contact);
2610
2611                         if (($contact['rel'] == self::SHARING)
2612                                 || ($sharing && $contact['rel'] == self::FOLLOWER)) {
2613                                 DBA::update('contact', ['rel' => self::FRIEND, 'writable' => true, 'pending' => false],
2614                                                 ['id' => $contact['id'], 'uid' => $importer['uid']]);
2615                         }
2616
2617                         // Ensure to always have the correct network type, independent from the connection request method
2618                         self::updateFromProbe($contact['id'], '', true);
2619
2620                         return true;
2621                 } else {
2622                         // send email notification to owner?
2623                         if (DBA::exists('contact', ['nurl' => Strings::normaliseLink($url), 'uid' => $importer['uid'], 'pending' => true])) {
2624                                 Logger::log('ignoring duplicated connection request from pending contact ' . $url);
2625                                 return null;
2626                         }
2627
2628                         // create contact record
2629                         DBA::insert('contact', [
2630                                 'uid'      => $importer['uid'],
2631                                 'created'  => DateTimeFormat::utcNow(),
2632                                 'url'      => $url,
2633                                 'nurl'     => Strings::normaliseLink($url),
2634                                 'name'     => $name,
2635                                 'nick'     => $nick,
2636                                 'network'  => $network,
2637                                 'rel'      => self::FOLLOWER,
2638                                 'blocked'  => 0,
2639                                 'readonly' => 0,
2640                                 'pending'  => 1,
2641                                 'writable' => 1,
2642                         ]);
2643
2644                         $contact_id = DBA::lastInsertId();
2645
2646                         // Ensure to always have the correct network type, independent from the connection request method
2647                         self::updateFromProbe($contact_id, '', true);
2648
2649                         self::updateAvatar($contact_id, $photo, true);
2650
2651                         $contact_record = DBA::selectFirst('contact', ['id', 'network', 'name', 'url', 'photo'], ['id' => $contact_id]);
2652
2653                         /// @TODO Encapsulate this into a function/method
2654                         $fields = ['uid', 'username', 'email', 'page-flags', 'notify-flags', 'language'];
2655                         $user = DBA::selectFirst('user', $fields, ['uid' => $importer['uid']]);
2656                         if (DBA::isResult($user) && !in_array($user['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_FREELOVE, User::PAGE_FLAGS_COMMUNITY])) {
2657                                 // create notification
2658                                 $hash = Strings::getRandomHex();
2659
2660                                 if (is_array($contact_record)) {
2661                                         DBA::insert('intro', ['uid' => $importer['uid'], 'contact-id' => $contact_record['id'],
2662                                                                 'blocked' => false, 'knowyou' => false, 'note' => $note,
2663                                                                 'hash' => $hash, 'datetime' => DateTimeFormat::utcNow()]);
2664                                 }
2665
2666                                 Group::addMember(User::getDefaultGroup($importer['uid'], $contact_record["network"]), $contact_record['id']);
2667
2668                                 if (($user['notify-flags'] & Type::INTRO) &&
2669                                         in_array($user['page-flags'], [User::PAGE_FLAGS_NORMAL])) {
2670
2671                                         notification([
2672                                                 'type'         => Type::INTRO,
2673                                                 'notify_flags' => $user['notify-flags'],
2674                                                 'language'     => $user['language'],
2675                                                 'to_name'      => $user['username'],
2676                                                 'to_email'     => $user['email'],
2677                                                 'uid'          => $user['uid'],
2678                                                 'link'         => DI::baseUrl() . '/notifications/intros',
2679                                                 'source_name'  => ((strlen(stripslashes($contact_record['name']))) ? stripslashes($contact_record['name']) : DI::l10n()->t('[Name Withheld]')),
2680                                                 'source_link'  => $contact_record['url'],
2681                                                 'source_photo' => $contact_record['photo'],
2682                                                 'verb'         => ($sharing ? Activity::FRIEND : Activity::FOLLOW),
2683                                                 'otype'        => 'intro'
2684                                         ]);
2685                                 }
2686                         } elseif (DBA::isResult($user) && in_array($user['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_FREELOVE, User::PAGE_FLAGS_COMMUNITY])) {
2687                                 if (($user['page-flags'] == User::PAGE_FLAGS_FREELOVE) && ($network != Protocol::DIASPORA)) {
2688                                         self::createFromProbe($importer, $url, false, $network);
2689                                 }
2690
2691                                 $condition = ['uid' => $importer['uid'], 'url' => $url, 'pending' => true];
2692                                 $fields = ['pending' => false];
2693                                 if ($user['page-flags'] == User::PAGE_FLAGS_FREELOVE) {
2694                                         $fields['rel'] = Contact::FRIEND;
2695                                 }
2696
2697                                 DBA::update('contact', $fields, $condition);
2698
2699                                 return true;
2700                         }
2701                 }
2702
2703                 return null;
2704         }
2705
2706         public static function removeFollower($importer, $contact, array $datarray = [], $item = "")
2707         {
2708                 if (($contact['rel'] == self::FRIEND) || ($contact['rel'] == self::SHARING)) {
2709                         DBA::update('contact', ['rel' => self::SHARING], ['id' => $contact['id']]);
2710                 } else {
2711                         Contact::remove($contact['id']);
2712                 }
2713         }
2714
2715         public static function removeSharer($importer, $contact, array $datarray = [], $item = "")
2716         {
2717                 if (($contact['rel'] == self::FRIEND) || ($contact['rel'] == self::FOLLOWER)) {
2718                         DBA::update('contact', ['rel' => self::FOLLOWER], ['id' => $contact['id']]);
2719                 } else {
2720                         Contact::remove($contact['id']);
2721                 }
2722         }
2723
2724         /**
2725          * Create a birthday event.
2726          *
2727          * Update the year and the birthday.
2728          */
2729         public static function updateBirthdays()
2730         {
2731                 $condition = [
2732                         '`bd` != ""
2733                         AND `bd` > "0001-01-01"
2734                         AND SUBSTRING(`bd`, 1, 4) != `bdyear`
2735                         AND (`contact`.`rel` = ? OR `contact`.`rel` = ?)
2736                         AND NOT `contact`.`pending`
2737                         AND NOT `contact`.`hidden`
2738                         AND NOT `contact`.`blocked`
2739                         AND NOT `contact`.`archive`
2740                         AND NOT `contact`.`deleted`',
2741                         Contact::SHARING,
2742                         Contact::FRIEND
2743                 ];
2744
2745                 $contacts = DBA::select('contact', ['id', 'uid', 'name', 'url', 'bd'], $condition);
2746
2747                 while ($contact = DBA::fetch($contacts)) {
2748                         Logger::log('update_contact_birthday: ' . $contact['bd']);
2749
2750                         $nextbd = DateTimeFormat::utcNow('Y') . substr($contact['bd'], 4);
2751
2752                         if (Event::createBirthday($contact, $nextbd)) {
2753                                 // update bdyear
2754                                 DBA::update(
2755                                         'contact',
2756                                         ['bdyear' => substr($nextbd, 0, 4), 'bd' => $nextbd],
2757                                         ['id' => $contact['id']]
2758                                 );
2759                         }
2760                 }
2761                 DBA::close($contacts);
2762         }
2763
2764         /**
2765          * Remove the unavailable contact ids from the provided list
2766          *
2767          * @param array $contact_ids Contact id list
2768          * @return array
2769          * @throws \Exception
2770          */
2771         public static function pruneUnavailable(array $contact_ids)
2772         {
2773                 if (empty($contact_ids)) {
2774                         return [];
2775                 }
2776
2777                 $contacts = Contact::selectToArray(['id'], [
2778                         'id'      => $contact_ids,
2779                         'blocked' => false,
2780                         'pending' => false,
2781                         'archive' => false,
2782                 ]);
2783
2784                 return array_column($contacts, 'id');
2785         }
2786
2787         /**
2788          * Returns a magic link to authenticate remote visitors
2789          *
2790          * @todo  check if the return is either a fully qualified URL or a relative path to Friendica basedir
2791          *
2792          * @param string $contact_url The address of the target contact profile
2793          * @param string $url         An url that we will be redirected to after the authentication
2794          *
2795          * @return string with "redir" link
2796          * @throws HTTPException\InternalServerErrorException
2797          * @throws \ImagickException
2798          */
2799         public static function magicLink($contact_url, $url = '')
2800         {
2801                 if (!Session::isAuthenticated()) {
2802                         return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
2803                 }
2804
2805                 $data = self::getProbeDataFromDatabase($contact_url);
2806                 if (empty($data)) {
2807                         return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
2808                 }
2809
2810                 // Prevents endless loop in case only a non-public contact exists for the contact URL
2811                 unset($data['uid']);
2812
2813                 return self::magicLinkByContact($data, $url ?: $contact_url);
2814         }
2815
2816         /**
2817          * Returns a magic link to authenticate remote visitors
2818          *
2819          * @param integer $cid The contact id of the target contact profile
2820          * @param string  $url An url that we will be redirected to after the authentication
2821          *
2822          * @return string with "redir" link
2823          * @throws HTTPException\InternalServerErrorException
2824          * @throws \ImagickException
2825          */
2826         public static function magicLinkbyId($cid, $url = '')
2827         {
2828                 $contact = DBA::selectFirst('contact', ['id', 'network', 'url', 'uid'], ['id' => $cid]);
2829
2830                 return self::magicLinkByContact($contact, $url);
2831         }
2832
2833         /**
2834          * Returns a magic link to authenticate remote visitors
2835          *
2836          * @param array  $contact The contact array with "uid", "network" and "url"
2837          * @param string $url     An url that we will be redirected to after the authentication
2838          *
2839          * @return string with "redir" link
2840          * @throws HTTPException\InternalServerErrorException
2841          * @throws \ImagickException
2842          */
2843         public static function magicLinkByContact($contact, $url = '')
2844         {
2845                 $destination = $url ?: $contact['url']; // Equivalent to ($url != '') ? $url : $contact['url'];
2846
2847                 if (!Session::isAuthenticated() || ($contact['network'] != Protocol::DFRN)) {
2848                         return $destination;
2849                 }
2850
2851                 // Only redirections to the same host do make sense
2852                 if (($url != '') && (parse_url($url, PHP_URL_HOST) != parse_url($contact['url'], PHP_URL_HOST))) {
2853                         return $url;
2854                 }
2855
2856                 if (!empty($contact['uid'])) {
2857                         return self::magicLink($contact['url'], $url);
2858                 }
2859
2860                 if (empty($contact['id'])) {
2861                         return $destination;
2862                 }
2863
2864                 $redirect = 'redir/' . $contact['id'];
2865
2866                 if (($url != '') && !Strings::compareLink($contact['url'], $url)) {
2867                         $redirect .= '?url=' . $url;
2868                 }
2869
2870                 return $redirect;
2871         }
2872
2873         /**
2874          * Remove a contact from all groups
2875          *
2876          * @param integer $contact_id
2877          *
2878          * @return boolean Success
2879          */
2880         public static function removeFromGroups($contact_id)
2881         {
2882                 return DBA::delete('group_member', ['contact-id' => $contact_id]);
2883         }
2884
2885         /**
2886          * Is the contact a forum?
2887          *
2888          * @param integer $contactid ID of the contact
2889          *
2890          * @return boolean "true" if it is a forum
2891          */
2892         public static function isForum($contactid)
2893         {
2894                 $fields = ['forum', 'prv'];
2895                 $condition = ['id' => $contactid];
2896                 $contact = DBA::selectFirst('contact', $fields, $condition);
2897                 if (!DBA::isResult($contact)) {
2898                         return false;
2899                 }
2900
2901                 // Is it a forum?
2902                 return ($contact['forum'] || $contact['prv']);
2903         }
2904
2905         /**
2906          * Can the remote contact receive private messages?
2907          *
2908          * @param array $contact
2909          * @return bool
2910          */
2911         public static function canReceivePrivateMessages(array $contact)
2912         {
2913                 $protocol = $contact['network'] ?? $contact['protocol'] ?? Protocol::PHANTOM;
2914                 $self = $contact['self'] ?? false;
2915
2916                 return in_array($protocol, [Protocol::DFRN, Protocol::DIASPORA, Protocol::ACTIVITYPUB]) && !$self;
2917         }
2918
2919         /**
2920          * Search contact table by nick or name
2921          *
2922          * @param string $search Name or nick
2923          * @param string $mode   Search mode (e.g. "community")
2924          *
2925          * @return array with search results
2926          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2927          */
2928         public static function searchByName($search, $mode = '')
2929         {
2930                 if (empty($search)) {
2931                         return [];
2932                 }
2933
2934                 // check supported networks
2935                 if (DI::config()->get('system', 'diaspora_enabled')) {
2936                         $diaspora = Protocol::DIASPORA;
2937                 } else {
2938                         $diaspora = Protocol::DFRN;
2939                 }
2940
2941                 if (!DI::config()->get('system', 'ostatus_disabled')) {
2942                         $ostatus = Protocol::OSTATUS;
2943                 } else {
2944                         $ostatus = Protocol::DFRN;
2945                 }
2946
2947                 // check if we search only communities or every contact
2948                 if ($mode === 'community') {
2949                         $extra_sql = sprintf(' AND `contact-type` = %d', Contact::TYPE_COMMUNITY);
2950                 } else {
2951                         $extra_sql = '';
2952                 }
2953
2954                 $search .= '%';
2955
2956                 $results = DBA::p("SELECT * FROM `contact`
2957                         WHERE NOT `unsearchable` AND `network` IN (?, ?, ?, ?) AND
2958                                 NOT `failed` AND `uid` = ? AND
2959                                 (`addr` LIKE ? OR `name` LIKE ? OR `nick` LIKE ?) $extra_sql
2960                                 ORDER BY `nurl` DESC LIMIT 1000",
2961                         Protocol::DFRN, Protocol::ACTIVITYPUB, $ostatus, $diaspora, 0, $search, $search, $search
2962                 );
2963
2964                 $contacts = DBA::toArray($results);
2965                 return $contacts;
2966         }
2967
2968         /**
2969          * @param int $uid   user
2970          * @param int $start optional, default 0
2971          * @param int $limit optional, default 80
2972          * @return array
2973          */
2974         static public function getSuggestions(int $uid, int $start = 0, int $limit = 80)
2975         {
2976                 $cid = self::getPublicIdByUserId($uid);
2977                 $totallimit = $start + $limit;
2978                 $contacts = [];
2979
2980                 Logger::info('Collecting suggestions', ['uid' => $uid, 'cid' => $cid, 'start' => $start, 'limit' => $limit]);
2981
2982                 $diaspora = DI::config()->get('system', 'diaspora_enabled') ? Protocol::DIASPORA : Protocol::ACTIVITYPUB;
2983                 $ostatus = !DI::config()->get('system', 'ostatus_disabled') ? Protocol::OSTATUS : Protocol::ACTIVITYPUB;
2984
2985                 // The query returns contacts where contacts interacted with whom the given user follows.
2986                 // Contacts who already are in the user's contact table are ignored.
2987                 $results = DBA::select('contact', [],
2988                         ["`id` IN (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` IN
2989                                 (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` = ?)
2990                                         AND NOT `cid` IN (SELECT `id` FROM `contact` WHERE `uid` = ? AND `nurl` IN
2991                                                 (SELECT `nurl` FROM `contact` WHERE `uid` = ? AND `rel` IN (?, ?))))
2992                         AND NOT `hidden` AND `network` IN (?, ?, ?, ?)",
2993                         $cid, 0, $uid, Contact::FRIEND, Contact::SHARING,
2994                         Protocol::ACTIVITYPUB, Protocol::DFRN, $diaspora, $ostatus],
2995                         ['order' => ['last-item' => true], 'limit' => $totallimit]
2996                 );
2997
2998                 while ($contact = DBA::fetch($results)) {
2999                         $contacts[$contact['id']] = $contact;
3000                 }
3001                 DBA::close($results);
3002
3003                 Logger::info('Contacts of contacts who are followed by the given user', ['uid' => $uid, 'cid' => $cid, 'count' => count($contacts)]);
3004
3005                 if (count($contacts) >= $totallimit) {
3006                         return array_slice($contacts, $start, $limit);
3007                 }
3008
3009                 // The query returns contacts where contacts interacted with whom also interacted with the given user.
3010                 // Contacts who already are in the user's contact table are ignored.
3011                 $results = DBA::select('contact', [],
3012                         ["`id` IN (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` IN
3013                                 (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ?)
3014                                         AND NOT `cid` IN (SELECT `id` FROM `contact` WHERE `uid` = ? AND `nurl` IN
3015                                                 (SELECT `nurl` FROM `contact` WHERE `uid` = ? AND `rel` IN (?, ?))))
3016                         AND NOT `hidden` AND `network` IN (?, ?, ?, ?)",
3017                         $cid, 0, $uid, Contact::FRIEND, Contact::SHARING,
3018                         Protocol::ACTIVITYPUB, Protocol::DFRN, $diaspora, $ostatus],
3019                         ['order' => ['last-item' => true], 'limit' => $totallimit]
3020                 );
3021
3022                 while ($contact = DBA::fetch($results)) {
3023                         $contacts[$contact['id']] = $contact;
3024                 }
3025                 DBA::close($results);
3026
3027                 Logger::info('Contacts of contacts who are following the given user', ['uid' => $uid, 'cid' => $cid, 'count' => count($contacts)]);
3028
3029                 if (count($contacts) >= $totallimit) {
3030                         return array_slice($contacts, $start, $limit);
3031                 }
3032
3033                 // The query returns contacts that follow the given user but aren't followed by that user.
3034                 $results = DBA::select('contact', [],
3035                         ["`nurl` IN (SELECT `nurl` FROM `contact` WHERE `uid` = ? AND `rel` = ?)
3036                         AND NOT `hidden` AND `uid` = ? AND `network` IN (?, ?, ?, ?)",
3037                         $uid, Contact::FOLLOWER, 0, 
3038                         Protocol::ACTIVITYPUB, Protocol::DFRN, $diaspora, $ostatus],
3039                         ['order' => ['last-item' => true], 'limit' => $totallimit]
3040                 );
3041
3042                 while ($contact = DBA::fetch($results)) {
3043                         $contacts[$contact['id']] = $contact;
3044                 }
3045                 DBA::close($results);
3046
3047                 Logger::info('Followers that are not followed by the given user', ['uid' => $uid, 'cid' => $cid, 'count' => count($contacts)]);
3048
3049                 if (count($contacts) >= $totallimit) {
3050                         return array_slice($contacts, $start, $limit);
3051                 }
3052
3053                 // The query returns any contact that isn't followed by that user.
3054                 $results = DBA::select('contact', [],
3055                         ["NOT `nurl` IN (SELECT `nurl` FROM `contact` WHERE `uid` = ? AND `rel` IN (?, ?))
3056                         AND NOT `hidden` AND `uid` = ? AND `network` IN (?, ?, ?, ?)",
3057                         $uid, Contact::FRIEND, Contact::SHARING, 0, 
3058                         Protocol::ACTIVITYPUB, Protocol::DFRN, $diaspora, $ostatus],
3059                         ['order' => ['last-item' => true], 'limit' => $totallimit]
3060                 );
3061
3062                 while ($contact = DBA::fetch($results)) {
3063                         $contacts[$contact['id']] = $contact;
3064                 }
3065                 DBA::close($results);
3066
3067                 Logger::info('Any contact', ['uid' => $uid, 'cid' => $cid, 'count' => count($contacts)]);
3068
3069                 return array_slice($contacts, $start, $limit);
3070         }
3071 }