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