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