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