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