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