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