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