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