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