]> git.mxchange.org Git - friendica.git/blob - src/Model/Contact.php
Repair missing contact photos
[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                 foreach ($data as $image_uri) {
1900                         $image_rid = Photo::ridFromURI($image_uri);
1901                         if ($image_rid && !Photo::exists(['resource-id' => $image_rid, 'uid' => $uid])) {
1902                                 Logger::info('Regenerating avatar for contact uid ' . $uid . ' cid ' . $cid . ' missing photo ' . $image_rid . ' avatar ' . $contact['avatar']);
1903                                 $force = true;
1904                         }
1905                 }
1906
1907                 if (($contact["avatar"] != $avatar) || $force) {
1908                         $photos = Photo::importProfilePhoto($avatar, $uid, $cid, true);
1909
1910                         if ($photos) {
1911                                 $fields = ['avatar' => $avatar, 'photo' => $photos[0], 'thumb' => $photos[1], 'micro' => $photos[2], 'avatar-date' => DateTimeFormat::utcNow()];
1912                                 DBA::update('contact', $fields, ['id' => $cid]);
1913
1914                                 // Update the public contact (contact id = 0)
1915                                 if ($uid != 0) {
1916                                         $pcontact = DBA::selectFirst('contact', ['id'], ['nurl' => $contact['nurl'], 'uid' => 0]);
1917                                         if (DBA::isResult($pcontact)) {
1918                                                 DBA::update('contact', $fields, ['id' => $pcontact['id']]);
1919                                         }
1920                                 }
1921
1922                                 return $photos;
1923                         }
1924                 }
1925
1926                 return $data;
1927         }
1928
1929         /**
1930          * @brief Helper function for "updateFromProbe". Updates personal and public contact
1931          *
1932          * @param integer $id      contact id
1933          * @param integer $uid     user id
1934          * @param string  $url     The profile URL of the contact
1935          * @param array   $fields  The fields that are updated
1936          *
1937          * @throws \Exception
1938          */
1939         private static function updateContact($id, $uid, $url, array $fields)
1940         {
1941                 if (!DBA::update('contact', $fields, ['id' => $id])) {
1942                         Logger::info('Couldn\'t update contact.', ['id' => $id, 'fields' => $fields]);
1943                         return;
1944                 }
1945
1946                 // Search for duplicated contacts and get rid of them
1947                 if (self::removeDuplicates(Strings::normaliseLink($url), $uid) || ($uid != 0)) {
1948                         return;
1949                 }
1950
1951                 // Update the corresponding gcontact entry
1952                 GContact::updateFromPublicContactID($id);
1953
1954                 // Archive or unarchive the contact. We only need to do this for the public contact.
1955                 // The archive/unarchive function will update the personal contacts by themselves.
1956                 $contact = DBA::selectFirst('contact', [], ['id' => $id]);
1957                 if (!DBA::isResult($contact)) {
1958                         Logger::info('Couldn\'t select contact for archival.', ['id' => $id]);
1959                         return;
1960                 }
1961
1962                 if (!empty($fields['success_update'])) {
1963                         self::unmarkForArchival($contact);
1964                 } elseif (!empty($fields['failure_update'])) {
1965                         self::markForArchival($contact);
1966                 }
1967
1968                 $condition = ['self' => false, 'nurl' => Strings::normaliseLink($url), 'network' => Protocol::FEDERATED];
1969
1970                 // These contacts are sharing with us, we don't poll them.
1971                 // This means that we don't set the update fields in "OnePoll.php".
1972                 $condition['rel'] = self::SHARING;
1973                 DBA::update('contact', $fields, $condition);
1974
1975                 unset($fields['last-update']);
1976                 unset($fields['success_update']);
1977                 unset($fields['failure_update']);
1978
1979                 if (empty($fields)) {
1980                         return;
1981                 }
1982
1983                 // We are polling these contacts, so we mustn't set the update fields here.
1984                 $condition['rel'] = [self::FOLLOWER, self::FRIEND];
1985                 DBA::update('contact', $fields, $condition);
1986         }
1987
1988         /**
1989          * @brief Remove duplicated contacts
1990          *
1991          * @param string  $nurl  Normalised contact url
1992          * @param integer $uid   User id
1993          * @return boolean
1994          * @throws \Exception
1995          */
1996         public static function removeDuplicates(string $nurl, int $uid)
1997         {
1998                 $condition = ['nurl' => $nurl, 'uid' => $uid, 'deleted' => false, 'network' => Protocol::FEDERATED];
1999                 $count = DBA::count('contact', $condition);
2000                 if ($count <= 1) {
2001                         return false;
2002                 }
2003
2004                 $first_contact = DBA::selectFirst('contact', ['id', 'network'], $condition, ['order' => ['id']]);
2005                 if (!DBA::isResult($first_contact)) {
2006                         // Shouldn't happen - so we handle it
2007                         return false;
2008                 }
2009
2010                 $first = $first_contact['id'];
2011                 Logger::info('Found duplicates', ['count' => $count, 'first' => $first, 'uid' => $uid, 'nurl' => $nurl]);
2012                 if (($uid != 0 && ($first_contact['network'] == Protocol::DFRN))) {
2013                         // Don't handle non public DFRN duplicates by now (legacy DFRN is very special because of the key handling)
2014                         Logger::info('Not handling non public DFRN duplicate', ['uid' => $uid, 'nurl' => $nurl]);
2015                         return false;
2016                 }
2017
2018                 // Find all duplicates
2019                 $condition = ["`nurl` = ? AND `uid` = ? AND `id` != ? AND NOT `self` AND NOT `deleted`", $nurl, $uid, $first];
2020                 $duplicates = DBA::select('contact', ['id', 'network'], $condition);
2021                 while ($duplicate = DBA::fetch($duplicates)) {
2022                         if (!in_array($duplicate['network'], Protocol::FEDERATED)) {
2023                                 continue;
2024                         }
2025
2026                         Worker::add(PRIORITY_HIGH, 'MergeContact', $first, $duplicate['id'], $uid);
2027                 }
2028                 Logger::info('Duplicates handled', ['uid' => $uid, 'nurl' => $nurl]);
2029                 return true;
2030         }
2031
2032         /**
2033          * @param integer $id      contact id
2034          * @param string  $network Optional network we are probing for
2035          * @param boolean $force   Optional forcing of network probing (otherwise we use the cached data)
2036          * @return boolean
2037          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2038          * @throws \ImagickException
2039          */
2040         public static function updateFromProbe($id, $network = '', $force = false)
2041         {
2042                 /*
2043                   Warning: Never ever fetch the public key via Probe::uri and write it into the contacts.
2044                   This will reliably kill your communication with old Friendica contacts.
2045                  */
2046
2047                 // These fields aren't updated by this routine:
2048                 // 'xmpp', 'sensitive'
2049
2050                 $fields = ['uid', 'avatar', 'name', 'nick', 'location', 'keywords', 'about', 'gender',
2051                         'unsearchable', 'url', 'addr', 'batch', 'notify', 'poll', 'request', 'confirm', 'poco',
2052                         'network', 'alias', 'baseurl', 'forum', 'prv', 'contact-type', 'pubkey'];
2053                 $contact = DBA::selectFirst('contact', $fields, ['id' => $id]);
2054                 if (!DBA::isResult($contact)) {
2055                         return false;
2056                 }
2057
2058                 $uid = $contact['uid'];
2059                 unset($contact['uid']);
2060
2061                 $pubkey = $contact['pubkey'];
2062                 unset($contact['pubkey']);
2063
2064                 $contact['photo'] = $contact['avatar'];
2065                 unset($contact['avatar']);
2066
2067                 $ret = Probe::uri($contact['url'], $network, $uid, !$force);
2068
2069                 $updated = DateTimeFormat::utcNow();
2070
2071                 // We must not try to update relay contacts via probe. They are no real contacts.
2072                 // We check after the probing to be able to correct falsely detected contact types.
2073                 if (($contact['contact-type'] == self::TYPE_RELAY) &&
2074                         (!Strings::compareLink($ret['url'], $contact['url']) || in_array($ret['network'], [Protocol::FEED, Protocol::PHANTOM]))) {
2075                         self::updateContact($id, $uid, $contact['url'], ['last-update' => $updated, 'success_update' => $updated]);
2076                         Logger::info('Not updating relais', ['id' => $id, 'url' => $contact['url']]);
2077                         return true;
2078                 }
2079
2080                 // If Probe::uri fails the network code will be different ("feed" or "unkn")
2081                 if (in_array($ret['network'], [Protocol::FEED, Protocol::PHANTOM]) && ($ret['network'] != $contact['network'])) {
2082                         if ($force && ($uid == 0)) {
2083                                 self::updateContact($id, $uid, $ret['url'], ['last-update' => $updated, 'failure_update' => $updated]);
2084                         }
2085                         return false;
2086                 }
2087
2088                 if (isset($ret['hide']) && is_bool($ret['hide'])) {
2089                         $ret['unsearchable'] = $ret['hide'];
2090                 }
2091
2092                 if (isset($ret['account-type']) && is_int($ret['account-type'])) {
2093                         $ret['forum'] = false;
2094                         $ret['prv'] = false;
2095                         $ret['contact-type'] = $ret['account-type'];
2096                         if ($ret['contact-type'] == User::ACCOUNT_TYPE_COMMUNITY) {
2097                                 $apcontact = APContact::getByURL($ret['url'], false);
2098                                 if (isset($apcontact['manually-approve'])) {
2099                                         $ret['forum'] = (bool)!$apcontact['manually-approve'];
2100                                         $ret['prv'] = (bool)!$ret['forum'];
2101                                 }
2102                         }
2103                 }
2104
2105                 $new_pubkey = $ret['pubkey'];
2106
2107                 $update = false;
2108
2109                 // make sure to not overwrite existing values with blank entries except some technical fields
2110                 $keep = ['batch', 'notify', 'poll', 'request', 'confirm', 'poco', 'baseurl'];
2111                 foreach ($ret as $key => $val) {
2112                         if (!array_key_exists($key, $contact)) {
2113                                 unset($ret[$key]);
2114                         } elseif (($contact[$key] != '') && ($val === '') && !is_bool($ret[$key]) && !in_array($key, $keep)) {
2115                                 $ret[$key] = $contact[$key];
2116                         } elseif ($ret[$key] != $contact[$key]) {
2117                                 $update = true;
2118                         }
2119                 }
2120
2121                 if (!empty($ret['photo']) && ($ret['network'] != Protocol::FEED)) {
2122                         self::updateAvatar($ret['photo'], $uid, $id, $update || $force);
2123                 }
2124
2125                 if (!$update) {
2126                         if ($force) {
2127                                 self::updateContact($id, $uid, $ret['url'], ['last-update' => $updated, 'success_update' => $updated]);
2128                         }
2129                         return true;
2130                 }
2131
2132                 $ret['nurl'] = Strings::normaliseLink($ret['url']);
2133                 $ret['updated'] = $updated;
2134
2135                 // Only fill the pubkey if it had been empty before. We have to prevent identity theft.
2136                 if (empty($pubkey) && !empty($new_pubkey)) {
2137                         $ret['pubkey'] = $new_pubkey;
2138                 }
2139
2140                 if (($ret['addr'] != $contact['addr']) || (!empty($ret['alias']) && ($ret['alias'] != $contact['alias']))) {
2141                         $ret['uri-date'] = DateTimeFormat::utcNow();
2142                 }
2143
2144                 if (($ret['name'] != $contact['name']) || ($ret['nick'] != $contact['nick'])) {
2145                         $ret['name-date'] = $updated;
2146                 }
2147
2148                 if ($force && ($uid == 0)) {
2149                         $ret['last-update'] = $updated;
2150                         $ret['success_update'] = $updated;
2151                 }
2152
2153                 unset($ret['photo']);
2154
2155                 self::updateContact($id, $uid, $ret['url'], $ret);
2156
2157                 return true;
2158         }
2159
2160         public static function updateFromProbeByURL($url, $force = false)
2161         {
2162                 $id = self::getIdForURL($url);
2163
2164                 if (empty($id)) {
2165                         return $id;
2166                 }
2167
2168                 self::updateFromProbe($id, '', $force);
2169
2170                 return $id;
2171         }
2172
2173         /**
2174          * Detects if a given contact array belongs to a legacy DFRN connection
2175          *
2176          * @param array $contact
2177          * @return boolean
2178          */
2179         public static function isLegacyDFRNContact($contact)
2180         {
2181                 // Newer Friendica contacts are connected via AP, then these fields aren't set
2182                 return !empty($contact['dfrn-id']) || !empty($contact['issued-id']);
2183         }
2184
2185         /**
2186          * Detects the communication protocol for a given contact url.
2187          * This is used to detect Friendica contacts that we can communicate via AP.
2188          *
2189          * @param string $url contact url
2190          * @param string $network Network of that contact
2191          * @return string with protocol
2192          */
2193         public static function getProtocol($url, $network)
2194         {
2195                 if ($network != Protocol::DFRN) {
2196                         return $network;
2197                 }
2198
2199                 $apcontact = APContact::getByURL($url);
2200                 if (!empty($apcontact) && !empty($apcontact['generator'])) {
2201                         return Protocol::ACTIVITYPUB;
2202                 } else {
2203                         return $network;
2204                 }
2205         }
2206
2207         /**
2208          * Takes a $uid and a url/handle and adds a new contact
2209          * Currently if the contact is DFRN, interactive needs to be true, to redirect to the
2210          * dfrn_request page.
2211          *
2212          * Otherwise this can be used to bulk add StatusNet contacts, Twitter contacts, etc.
2213          *
2214          * Returns an array
2215          * $return['success'] boolean true if successful
2216          * $return['message'] error text if success is false.
2217          *
2218          * @brief Takes a $uid and a url/handle and adds a new contact
2219          * @param int    $uid
2220          * @param string $url
2221          * @param bool   $interactive
2222          * @param string $network
2223          * @return array
2224          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2225          * @throws \ImagickException
2226          */
2227         public static function createFromProbe($uid, $url, $interactive = false, $network = '')
2228         {
2229                 $result = ['cid' => -1, 'success' => false, 'message' => ''];
2230
2231                 $a = DI::app();
2232
2233                 // remove ajax junk, e.g. Twitter
2234                 $url = str_replace('/#!/', '/', $url);
2235
2236                 if (!Network::isUrlAllowed($url)) {
2237                         $result['message'] = L10n::t('Disallowed profile URL.');
2238                         return $result;
2239                 }
2240
2241                 if (Network::isUrlBlocked($url)) {
2242                         $result['message'] = L10n::t('Blocked domain');
2243                         return $result;
2244                 }
2245
2246                 if (!$url) {
2247                         $result['message'] = L10n::t('Connect URL missing.');
2248                         return $result;
2249                 }
2250
2251                 $arr = ['url' => $url, 'contact' => []];
2252
2253                 Hook::callAll('follow', $arr);
2254
2255                 if (empty($arr)) {
2256                         $result['message'] = L10n::t('The contact could not be added. Please check the relevant network credentials in your Settings -> Social Networks page.');
2257                         return $result;
2258                 }
2259
2260                 if (!empty($arr['contact']['name'])) {
2261                         $ret = $arr['contact'];
2262                 } else {
2263                         $ret = Probe::uri($url, $network, $uid, false);
2264                 }
2265
2266                 if (($network != '') && ($ret['network'] != $network)) {
2267                         Logger::log('Expected network ' . $network . ' does not match actual network ' . $ret['network']);
2268                         return $result;
2269                 }
2270
2271                 // check if we already have a contact
2272                 // the poll url is more reliable than the profile url, as we may have
2273                 // indirect links or webfinger links
2274
2275                 $condition = ['uid' => $uid, 'poll' => [$ret['poll'], Strings::normaliseLink($ret['poll'])], 'network' => $ret['network'], 'pending' => false];
2276                 $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
2277                 if (!DBA::isResult($contact)) {
2278                         $condition = ['uid' => $uid, 'nurl' => Strings::normaliseLink($url), 'network' => $ret['network'], 'pending' => false];
2279                         $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
2280                 }
2281
2282                 $protocol = self::getProtocol($url, $ret['network']);
2283
2284                 if (($protocol === Protocol::DFRN) && !DBA::isResult($contact)) {
2285                         if ($interactive) {
2286                                 if (strlen(DI::baseUrl()->getUrlPath())) {
2287                                         $myaddr = bin2hex(DI::baseUrl() . '/profile/' . $a->user['nickname']);
2288                                 } else {
2289                                         $myaddr = bin2hex($a->user['nickname'] . '@' . DI::baseUrl()->getHostname());
2290                                 }
2291
2292                                 DI::baseUrl()->redirect($ret['request'] . "&addr=$myaddr");
2293
2294                                 // NOTREACHED
2295                         }
2296                 } elseif (Config::get('system', 'dfrn_only') && ($ret['network'] != Protocol::DFRN)) {
2297                         $result['message'] = L10n::t('This site is not configured to allow communications with other networks.') . EOL;
2298                         $result['message'] .= L10n::t('No compatible communication protocols or feeds were discovered.') . EOL;
2299                         return $result;
2300                 }
2301
2302                 // This extra param just confuses things, remove it
2303                 if ($protocol === Protocol::DIASPORA) {
2304                         $ret['url'] = str_replace('?absolute=true', '', $ret['url']);
2305                 }
2306
2307                 // do we have enough information?
2308                 if (empty($ret['name']) || empty($ret['poll']) || (empty($ret['url']) && empty($ret['addr']))) {
2309                         $result['message'] .= L10n::t('The profile address specified does not provide adequate information.') . EOL;
2310                         if (empty($ret['poll'])) {
2311                                 $result['message'] .= L10n::t('No compatible communication protocols or feeds were discovered.') . EOL;
2312                         }
2313                         if (empty($ret['name'])) {
2314                                 $result['message'] .= L10n::t('An author or name was not found.') . EOL;
2315                         }
2316                         if (empty($ret['url'])) {
2317                                 $result['message'] .= L10n::t('No browser URL could be matched to this address.') . EOL;
2318                         }
2319                         if (strpos($url, '@') !== false) {
2320                                 $result['message'] .= L10n::t('Unable to match @-style Identity Address with a known protocol or email contact.') . EOL;
2321                                 $result['message'] .= L10n::t('Use mailto: in front of address to force email check.') . EOL;
2322                         }
2323                         return $result;
2324                 }
2325
2326                 if ($protocol === Protocol::OSTATUS && Config::get('system', 'ostatus_disabled')) {
2327                         $result['message'] .= L10n::t('The profile address specified belongs to a network which has been disabled on this site.') . EOL;
2328                         $ret['notify'] = '';
2329                 }
2330
2331                 if (!$ret['notify']) {
2332                         $result['message'] .= L10n::t('Limited profile. This person will be unable to receive direct/personal notifications from you.') . EOL;
2333                 }
2334
2335                 $writeable = ((($protocol === Protocol::OSTATUS) && ($ret['notify'])) ? 1 : 0);
2336
2337                 $subhub = (($protocol === Protocol::OSTATUS) ? true : false);
2338
2339                 $hidden = (($protocol === Protocol::MAIL) ? 1 : 0);
2340
2341                 $pending = false;
2342                 if ($protocol == Protocol::ACTIVITYPUB) {
2343                         $apcontact = APContact::getByURL($url, false);
2344                         if (isset($apcontact['manually-approve'])) {
2345                                 $pending = (bool)$apcontact['manually-approve'];
2346                         }
2347                 }
2348
2349                 if (in_array($protocol, [Protocol::MAIL, Protocol::DIASPORA, Protocol::ACTIVITYPUB])) {
2350                         $writeable = 1;
2351                 }
2352
2353                 if (DBA::isResult($contact)) {
2354                         // update contact
2355                         $new_relation = (($contact['rel'] == self::FOLLOWER) ? self::FRIEND : self::SHARING);
2356
2357                         $fields = ['rel' => $new_relation, 'subhub' => $subhub, 'readonly' => false];
2358                         DBA::update('contact', $fields, ['id' => $contact['id']]);
2359                 } else {
2360                         $new_relation = (in_array($protocol, [Protocol::MAIL]) ? self::FRIEND : self::SHARING);
2361
2362                         // create contact record
2363                         self::insert([
2364                                 'uid'     => $uid,
2365                                 'created' => DateTimeFormat::utcNow(),
2366                                 'url'     => $ret['url'],
2367                                 'nurl'    => Strings::normaliseLink($ret['url']),
2368                                 'addr'    => $ret['addr'],
2369                                 'alias'   => $ret['alias'],
2370                                 'batch'   => $ret['batch'],
2371                                 'notify'  => $ret['notify'],
2372                                 'poll'    => $ret['poll'],
2373                                 'poco'    => $ret['poco'],
2374                                 'name'    => $ret['name'],
2375                                 'nick'    => $ret['nick'],
2376                                 'network' => $ret['network'],
2377                                 'baseurl' => $ret['baseurl'],
2378                                 'protocol' => $protocol,
2379                                 'pubkey'  => $ret['pubkey'],
2380                                 'rel'     => $new_relation,
2381                                 'priority'=> $ret['priority'],
2382                                 'writable'=> $writeable,
2383                                 'hidden'  => $hidden,
2384                                 'blocked' => 0,
2385                                 'readonly'=> 0,
2386                                 'pending' => $pending,
2387                                 'subhub'  => $subhub
2388                         ]);
2389                 }
2390
2391                 $contact = DBA::selectFirst('contact', [], ['url' => $ret['url'], 'network' => $ret['network'], 'uid' => $uid]);
2392                 if (!DBA::isResult($contact)) {
2393                         $result['message'] .= L10n::t('Unable to retrieve contact information.') . EOL;
2394                         return $result;
2395                 }
2396
2397                 $contact_id = $contact['id'];
2398                 $result['cid'] = $contact_id;
2399
2400                 Group::addMember(User::getDefaultGroup($uid, $contact["network"]), $contact_id);
2401
2402                 // Update the avatar
2403                 self::updateAvatar($ret['photo'], $uid, $contact_id);
2404
2405                 // pull feed and consume it, which should subscribe to the hub.
2406
2407                 Worker::add(PRIORITY_HIGH, "OnePoll", $contact_id, "force");
2408
2409                 $owner = User::getOwnerDataById($uid);
2410
2411                 if (DBA::isResult($owner)) {
2412                         if (in_array($protocol, [Protocol::OSTATUS, Protocol::DFRN])) {
2413                                 // create a follow slap
2414                                 $item = [];
2415                                 $item['verb'] = Activity::FOLLOW;
2416                                 $item['follow'] = $contact["url"];
2417                                 $item['body'] = '';
2418                                 $item['title'] = '';
2419                                 $item['guid'] = '';
2420                                 $item['tag'] = '';
2421                                 $item['attach'] = '';
2422
2423                                 $slap = OStatus::salmon($item, $owner);
2424
2425                                 if (!empty($contact['notify'])) {
2426                                         Salmon::slapper($owner, $contact['notify'], $slap);
2427                                 }
2428                         } elseif ($protocol == Protocol::DIASPORA) {
2429                                 $ret = Diaspora::sendShare($a->user, $contact);
2430                                 Logger::log('share returns: ' . $ret);
2431                         } elseif ($protocol == Protocol::ACTIVITYPUB) {
2432                                 $activity_id = ActivityPub\Transmitter::activityIDFromContact($contact_id);
2433                                 if (empty($activity_id)) {
2434                                         // This really should never happen
2435                                         return false;
2436                                 }
2437
2438                                 $ret = ActivityPub\Transmitter::sendActivity('Follow', $contact['url'], $uid, $activity_id);
2439                                 Logger::log('Follow returns: ' . $ret);
2440                         }
2441                 }
2442
2443                 $result['success'] = true;
2444                 return $result;
2445         }
2446
2447         /**
2448          * @brief Updated contact's SSL policy
2449          *
2450          * @param array  $contact    Contact array
2451          * @param string $new_policy New policy, valid: self,full
2452          *
2453          * @return array Contact array with updated values
2454          * @throws \Exception
2455          */
2456         public static function updateSslPolicy(array $contact, $new_policy)
2457         {
2458                 $ssl_changed = false;
2459                 if ((intval($new_policy) == BaseURL::SSL_POLICY_SELFSIGN || $new_policy === 'self') && strstr($contact['url'], 'https:')) {
2460                         $ssl_changed = true;
2461                         $contact['url']     =   str_replace('https:', 'http:', $contact['url']);
2462                         $contact['request'] =   str_replace('https:', 'http:', $contact['request']);
2463                         $contact['notify']  =   str_replace('https:', 'http:', $contact['notify']);
2464                         $contact['poll']    =   str_replace('https:', 'http:', $contact['poll']);
2465                         $contact['confirm'] =   str_replace('https:', 'http:', $contact['confirm']);
2466                         $contact['poco']    =   str_replace('https:', 'http:', $contact['poco']);
2467                 }
2468
2469                 if ((intval($new_policy) == BaseURL::SSL_POLICY_FULL || $new_policy === 'full') && strstr($contact['url'], 'http:')) {
2470                         $ssl_changed = true;
2471                         $contact['url']     =   str_replace('http:', 'https:', $contact['url']);
2472                         $contact['request'] =   str_replace('http:', 'https:', $contact['request']);
2473                         $contact['notify']  =   str_replace('http:', 'https:', $contact['notify']);
2474                         $contact['poll']    =   str_replace('http:', 'https:', $contact['poll']);
2475                         $contact['confirm'] =   str_replace('http:', 'https:', $contact['confirm']);
2476                         $contact['poco']    =   str_replace('http:', 'https:', $contact['poco']);
2477                 }
2478
2479                 if ($ssl_changed) {
2480                         $fields = ['url' => $contact['url'], 'request' => $contact['request'],
2481                                         'notify' => $contact['notify'], 'poll' => $contact['poll'],
2482                                         'confirm' => $contact['confirm'], 'poco' => $contact['poco']];
2483                         DBA::update('contact', $fields, ['id' => $contact['id']]);
2484                 }
2485
2486                 return $contact;
2487         }
2488
2489         /**
2490          * @param array  $importer Owner (local user) data
2491          * @param array  $contact  Existing owner-specific contact data we want to expand the relationship with. Optional.
2492          * @param array  $datarray An item-like array with at least the 'author-id' and 'author-url' keys for the contact. Mandatory.
2493          * @param bool   $sharing  True: Contact is now sharing with Owner; False: Contact is now following Owner (default)
2494          * @param string $note     Introduction additional message
2495          * @return bool|null True: follow request is accepted; False: relationship is rejected; Null: relationship is pending
2496          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2497          * @throws \ImagickException
2498          */
2499         public static function addRelationship(array $importer, array $contact, array $datarray, $sharing = false, $note = '')
2500         {
2501                 // Should always be set
2502                 if (empty($datarray['author-id'])) {
2503                         return false;
2504                 }
2505
2506                 $fields = ['url', 'name', 'nick', 'avatar', 'photo', 'network', 'blocked'];
2507                 $pub_contact = DBA::selectFirst('contact', $fields, ['id' => $datarray['author-id']]);
2508                 if (!DBA::isResult($pub_contact)) {
2509                         // Should never happen
2510                         return false;
2511                 }
2512
2513                 // Contact is blocked at node-level
2514                 if (self::isBlocked($datarray['author-id'])) {
2515                         return false;
2516                 }
2517
2518                 $url = ($datarray['author-link'] ?? '') ?: $pub_contact['url'];
2519                 $name = $pub_contact['name'];
2520                 $photo = ($pub_contact['avatar'] ?? '') ?: $pub_contact["photo"];
2521                 $nick = $pub_contact['nick'];
2522                 $network = $pub_contact['network'];
2523
2524                 // Ensure that we don't create a new contact when there already is one
2525                 $cid = self::getIdForURL($url, $importer['uid']);
2526                 if (!empty($cid)) {
2527                         $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
2528                 }
2529
2530                 if (!empty($contact)) {
2531                         if (!empty($contact['pending'])) {
2532                                 Logger::info('Pending contact request already exists.', ['url' => $url, 'uid' => $importer['uid']]);
2533                                 return null;
2534                         }
2535
2536                         // Contact is blocked at user-level
2537                         if (!empty($contact['id']) && !empty($importer['id']) &&
2538                                 self::isBlockedByUser($contact['id'], $importer['id'])) {
2539                                 return false;
2540                         }
2541
2542                         // Make sure that the existing contact isn't archived
2543                         self::unmarkForArchival($contact);
2544
2545                         if (($contact['rel'] == self::SHARING)
2546                                 || ($sharing && $contact['rel'] == self::FOLLOWER)) {
2547                                 DBA::update('contact', ['rel' => self::FRIEND, 'writable' => true, 'pending' => false],
2548                                                 ['id' => $contact['id'], 'uid' => $importer['uid']]);
2549                         }
2550
2551                         // Ensure to always have the correct network type, independent from the connection request method
2552                         self::updateFromProbe($contact['id'], '', true);
2553
2554                         return true;
2555                 } else {
2556                         // send email notification to owner?
2557                         if (DBA::exists('contact', ['nurl' => Strings::normaliseLink($url), 'uid' => $importer['uid'], 'pending' => true])) {
2558                                 Logger::log('ignoring duplicated connection request from pending contact ' . $url);
2559                                 return null;
2560                         }
2561
2562                         // create contact record
2563                         DBA::insert('contact', [
2564                                 'uid'      => $importer['uid'],
2565                                 'created'  => DateTimeFormat::utcNow(),
2566                                 'url'      => $url,
2567                                 'nurl'     => Strings::normaliseLink($url),
2568                                 'name'     => $name,
2569                                 'nick'     => $nick,
2570                                 'photo'    => $photo,
2571                                 'network'  => $network,
2572                                 'rel'      => self::FOLLOWER,
2573                                 'blocked'  => 0,
2574                                 'readonly' => 0,
2575                                 'pending'  => 1,
2576                                 'writable' => 1,
2577                         ]);
2578
2579                         $contact_id = DBA::lastInsertId();
2580
2581                         // Ensure to always have the correct network type, independent from the connection request method
2582                         self::updateFromProbe($contact_id, '', true);
2583
2584                         Contact::updateAvatar($photo, $importer["uid"], $contact_id, true);
2585
2586                         $contact_record = DBA::selectFirst('contact', ['id', 'network', 'name', 'url', 'photo'], ['id' => $contact_id]);
2587
2588                         /// @TODO Encapsulate this into a function/method
2589                         $fields = ['uid', 'username', 'email', 'page-flags', 'notify-flags', 'language'];
2590                         $user = DBA::selectFirst('user', $fields, ['uid' => $importer['uid']]);
2591                         if (DBA::isResult($user) && !in_array($user['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_FREELOVE, User::PAGE_FLAGS_COMMUNITY])) {
2592                                 // create notification
2593                                 $hash = Strings::getRandomHex();
2594
2595                                 if (is_array($contact_record)) {
2596                                         DBA::insert('intro', ['uid' => $importer['uid'], 'contact-id' => $contact_record['id'],
2597                                                                 'blocked' => false, 'knowyou' => false, 'note' => $note,
2598                                                                 'hash' => $hash, 'datetime' => DateTimeFormat::utcNow()]);
2599                                 }
2600
2601                                 Group::addMember(User::getDefaultGroup($importer['uid'], $contact_record["network"]), $contact_record['id']);
2602
2603                                 if (($user['notify-flags'] & NOTIFY_INTRO) &&
2604                                         in_array($user['page-flags'], [User::PAGE_FLAGS_NORMAL])) {
2605
2606                                         notification([
2607                                                 'type'         => NOTIFY_INTRO,
2608                                                 'notify_flags' => $user['notify-flags'],
2609                                                 'language'     => $user['language'],
2610                                                 'to_name'      => $user['username'],
2611                                                 'to_email'     => $user['email'],
2612                                                 'uid'          => $user['uid'],
2613                                                 'link'         => DI::baseUrl() . '/notifications/intro',
2614                                                 'source_name'  => ((strlen(stripslashes($contact_record['name']))) ? stripslashes($contact_record['name']) : L10n::t('[Name Withheld]')),
2615                                                 'source_link'  => $contact_record['url'],
2616                                                 'source_photo' => $contact_record['photo'],
2617                                                 'verb'         => ($sharing ? Activity::FRIEND : Activity::FOLLOW),
2618                                                 'otype'        => 'intro'
2619                                         ]);
2620                                 }
2621                         } elseif (DBA::isResult($user) && in_array($user['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_FREELOVE, User::PAGE_FLAGS_COMMUNITY])) {
2622                                 $condition = ['uid' => $importer['uid'], 'url' => $url, 'pending' => true];
2623                                 DBA::update('contact', ['pending' => false], $condition);
2624
2625                                 return true;
2626                         }
2627                 }
2628
2629                 return null;
2630         }
2631
2632         public static function removeFollower($importer, $contact, array $datarray = [], $item = "")
2633         {
2634                 if (($contact['rel'] == self::FRIEND) || ($contact['rel'] == self::SHARING)) {
2635                         DBA::update('contact', ['rel' => self::SHARING], ['id' => $contact['id']]);
2636                 } else {
2637                         Contact::remove($contact['id']);
2638                 }
2639         }
2640
2641         public static function removeSharer($importer, $contact, array $datarray = [], $item = "")
2642         {
2643                 if (($contact['rel'] == self::FRIEND) || ($contact['rel'] == self::FOLLOWER)) {
2644                         DBA::update('contact', ['rel' => self::FOLLOWER], ['id' => $contact['id']]);
2645                 } else {
2646                         Contact::remove($contact['id']);
2647                 }
2648         }
2649
2650         /**
2651          * @brief Create a birthday event.
2652          *
2653          * Update the year and the birthday.
2654          */
2655         public static function updateBirthdays()
2656         {
2657                 $condition = [
2658                         '`bd` != ""
2659                         AND `bd` > "0001-01-01"
2660                         AND SUBSTRING(`bd`, 1, 4) != `bdyear`
2661                         AND (`contact`.`rel` = ? OR `contact`.`rel` = ?)
2662                         AND NOT `contact`.`pending`
2663                         AND NOT `contact`.`hidden`
2664                         AND NOT `contact`.`blocked`
2665                         AND NOT `contact`.`archive`
2666                         AND NOT `contact`.`deleted`',
2667                         Contact::SHARING,
2668                         Contact::FRIEND
2669                 ];
2670
2671                 $contacts = DBA::select('contact', ['id', 'uid', 'name', 'url', 'bd'], $condition);
2672
2673                 while ($contact = DBA::fetch($contacts)) {
2674                         Logger::log('update_contact_birthday: ' . $contact['bd']);
2675
2676                         $nextbd = DateTimeFormat::utcNow('Y') . substr($contact['bd'], 4);
2677
2678                         if (Event::createBirthday($contact, $nextbd)) {
2679                                 // update bdyear
2680                                 DBA::update(
2681                                         'contact',
2682                                         ['bdyear' => substr($nextbd, 0, 4), 'bd' => $nextbd],
2683                                         ['id' => $contact['id']]
2684                                 );
2685                         }
2686                 }
2687         }
2688
2689         /**
2690          * Remove the unavailable contact ids from the provided list
2691          *
2692          * @param array $contact_ids Contact id list
2693          * @return array
2694          * @throws \Exception
2695          */
2696         public static function pruneUnavailable(array $contact_ids)
2697         {
2698                 if (empty($contact_ids)) {
2699                         return [];
2700                 }
2701
2702                 $contacts = Contact::selectToArray(['id'], [
2703                         'id'      => $contact_ids,
2704                         'blocked' => false,
2705                         'pending' => false,
2706                         'archive' => false,
2707                 ]);
2708
2709                 return array_column($contacts, 'id');
2710         }
2711
2712         /**
2713          * @brief Returns a magic link to authenticate remote visitors
2714          *
2715          * @todo  check if the return is either a fully qualified URL or a relative path to Friendica basedir
2716          *
2717          * @param string $contact_url The address of the target contact profile
2718          * @param string $url         An url that we will be redirected to after the authentication
2719          *
2720          * @return string with "redir" link
2721          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2722          * @throws \ImagickException
2723          */
2724         public static function magicLink($contact_url, $url = '')
2725         {
2726                 if (!Session::isAuthenticated()) {
2727                         return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
2728                 }
2729
2730                 $data = self::getProbeDataFromDatabase($contact_url);
2731                 if (empty($data)) {
2732                         return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
2733                 }
2734
2735                 // Prevents endless loop in case only a non-public contact exists for the contact URL
2736                 unset($data['uid']);
2737
2738                 return self::magicLinkByContact($data, $url ?: $contact_url);
2739         }
2740
2741         /**
2742          * @brief Returns a magic link to authenticate remote visitors
2743          *
2744          * @param integer $cid The contact id of the target contact profile
2745          * @param string  $url An url that we will be redirected to after the authentication
2746          *
2747          * @return string with "redir" link
2748          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2749          * @throws \ImagickException
2750          */
2751         public static function magicLinkbyId($cid, $url = '')
2752         {
2753                 $contact = DBA::selectFirst('contact', ['id', 'network', 'url', 'uid'], ['id' => $cid]);
2754
2755                 return self::magicLinkByContact($contact, $url);
2756         }
2757
2758         /**
2759          * @brief Returns a magic link to authenticate remote visitors
2760          *
2761          * @param array  $contact The contact array with "uid", "network" and "url"
2762          * @param string $url     An url that we will be redirected to after the authentication
2763          *
2764          * @return string with "redir" link
2765          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2766          * @throws \ImagickException
2767          */
2768         public static function magicLinkByContact($contact, $url = '')
2769         {
2770                 $destination = $url ?: $contact['url']; // Equivalent to ($url != '') ? $url : $contact['url'];
2771
2772                 if (!Session::isAuthenticated() || ($contact['network'] != Protocol::DFRN)) {
2773                         return $destination;
2774                 }
2775
2776                 // Only redirections to the same host do make sense
2777                 if (($url != '') && (parse_url($url, PHP_URL_HOST) != parse_url($contact['url'], PHP_URL_HOST))) {
2778                         return $url;
2779                 }
2780
2781                 if (!empty($contact['uid'])) {
2782                         return self::magicLink($contact['url'], $url);
2783                 }
2784
2785                 if (empty($contact['id'])) {
2786                         return $destination;
2787                 }
2788
2789                 $redirect = 'redir/' . $contact['id'];
2790
2791                 if (($url != '') && !Strings::compareLink($contact['url'], $url)) {
2792                         $redirect .= '?url=' . $url;
2793                 }
2794
2795                 return $redirect;
2796         }
2797
2798         /**
2799          * Remove a contact from all groups
2800          *
2801          * @param integer $contact_id
2802          *
2803          * @return boolean Success
2804          */
2805         public static function removeFromGroups($contact_id)
2806         {
2807                 return DBA::delete('group_member', ['contact-id' => $contact_id]);
2808         }
2809
2810         /**
2811          * Is the contact a forum?
2812          *
2813          * @param integer $contactid ID of the contact
2814          *
2815          * @return boolean "true" if it is a forum
2816          */
2817         public static function isForum($contactid)
2818         {
2819                 $fields = ['forum', 'prv'];
2820                 $condition = ['id' => $contactid];
2821                 $contact = DBA::selectFirst('contact', $fields, $condition);
2822                 if (!DBA::isResult($contact)) {
2823                         return false;
2824                 }
2825
2826                 // Is it a forum?
2827                 return ($contact['forum'] || $contact['prv']);
2828         }
2829
2830         /**
2831          * Can the remote contact receive private messages?
2832          *
2833          * @param array $contact
2834          * @return bool
2835          */
2836         public static function canReceivePrivateMessages(array $contact)
2837         {
2838                 $protocol = $contact['network'] ?? $contact['protocol'] ?? Protocol::PHANTOM;
2839                 $self = $contact['self'] ?? false;
2840
2841                 return in_array($protocol, [Protocol::DFRN, Protocol::DIASPORA, Protocol::ACTIVITYPUB]) && !$self;
2842         }
2843 }