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