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