]> git.mxchange.org Git - friendica.git/blob - src/Model/Contact.php
cf08a4cffcd6ec5d422bd55d352ee9782bb08b00
[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                 if (!empty($follow_link) || !empty($unfollow_link)) {
1282                         $contact_drop_link = '';
1283                 }
1284
1285                 /**
1286                  * Menu array:
1287                  * "name" => [ "Label", "link", (bool)Should the link opened in a new tab? ]
1288                  */
1289                 if (empty($contact['uid'])) {
1290                         $menu = [
1291                                 'profile' => [DI::l10n()->t('View Profile')  , $profile_link , true],
1292                                 'network' => [DI::l10n()->t('Network Posts') , $posts_link   , false],
1293                                 'edit'    => [DI::l10n()->t('View Contact')  , $contact_url  , false],
1294                                 'follow'  => [DI::l10n()->t('Connect/Follow'), $follow_link  , true],
1295                                 'unfollow'=> [DI::l10n()->t('UnFollow')      , $unfollow_link, true],
1296                         ];
1297                 } else {
1298                         $menu = [
1299                                 'status'  => [DI::l10n()->t('View Status')   , $status_link      , true],
1300                                 'profile' => [DI::l10n()->t('View Profile')  , $profile_link     , true],
1301                                 'photos'  => [DI::l10n()->t('View Photos')   , $photos_link      , true],
1302                                 'network' => [DI::l10n()->t('Network Posts') , $posts_link       , false],
1303                                 'edit'    => [DI::l10n()->t('View Contact')  , $contact_url      , false],
1304                                 'drop'    => [DI::l10n()->t('Drop Contact')  , $contact_drop_link, false],
1305                                 'pm'      => [DI::l10n()->t('Send PM')       , $pm_url           , false],
1306                                 'poke'    => [DI::l10n()->t('Poke')          , $poke_link        , false],
1307                                 'follow'  => [DI::l10n()->t('Connect/Follow'), $follow_link      , true],
1308                                 'unfollow'=> [DI::l10n()->t('UnFollow')      , $unfollow_link    , true],
1309                         ];
1310
1311                         if (!empty($contact['pending'])) {
1312                                 $intro = DBA::selectFirst('intro', ['id'], ['contact-id' => $contact['id']]);
1313                                 if (DBA::isResult($intro)) {
1314                                         $menu['follow'] = [DI::l10n()->t('Approve'), 'notifications/intros/' . $intro['id'], true];
1315                                 }
1316                         }
1317                 }
1318
1319                 $args = ['contact' => $contact, 'menu' => &$menu];
1320
1321                 Hook::callAll('contact_photo_menu', $args);
1322
1323                 $menucondensed = [];
1324
1325                 foreach ($menu as $menuname => $menuitem) {
1326                         if ($menuitem[1] != '') {
1327                                 $menucondensed[$menuname] = $menuitem;
1328                         }
1329                 }
1330
1331                 return $menucondensed;
1332         }
1333
1334         /**
1335          * Returns ungrouped contact count or list for user
1336          *
1337          * Returns either the total number of ungrouped contacts for the given user
1338          * id or a paginated list of ungrouped contacts.
1339          *
1340          * @param int $uid uid
1341          * @return array
1342          * @throws \Exception
1343          */
1344         public static function getUngroupedList($uid)
1345         {
1346                 return q("SELECT *
1347                            FROM `contact`
1348                            WHERE `uid` = %d
1349                            AND NOT `self`
1350                            AND NOT `deleted`
1351                            AND NOT `blocked`
1352                            AND NOT `pending`
1353                            AND `id` NOT IN (
1354                                 SELECT DISTINCT(`contact-id`)
1355                                 FROM `group_member`
1356                                 INNER JOIN `group` ON `group`.`id` = `group_member`.`gid`
1357                                 WHERE `group`.`uid` = %d
1358                            )", intval($uid), intval($uid));
1359         }
1360
1361         /**
1362          * Have a look at all contact tables for a given profile url.
1363          * This function works as a replacement for probing the contact.
1364          *
1365          * @param string  $url Contact URL
1366          * @param integer $cid Contact ID
1367          *
1368          * @return array Contact array in the "probe" structure
1369         */
1370         private static function getProbeDataFromDatabase($url, $cid = null)
1371         {
1372                 // The link could be provided as http although we stored it as https
1373                 $ssl_url = str_replace('http://', 'https://', $url);
1374
1375                 $fields = ['id', 'uid', 'url', 'addr', 'alias', 'notify', 'poll', 'name', 'nick',
1376                         'photo', 'keywords', 'location', 'about', 'network',
1377                         'priority', 'batch', 'request', 'confirm', 'poco'];
1378
1379                 if (!empty($cid)) {
1380                         $data = DBA::selectFirst('contact', $fields, ['id' => $cid]);
1381                         if (DBA::isResult($data)) {
1382                                 return $data;
1383                         }
1384                 }
1385
1386                 $data = DBA::selectFirst('contact', $fields, ['nurl' => Strings::normaliseLink($url)]);
1387
1388                 if (!DBA::isResult($data)) {
1389                         $condition = ['alias' => [$url, Strings::normaliseLink($url), $ssl_url]];
1390                         $data = DBA::selectFirst('contact', $fields, $condition);
1391                 }
1392
1393                 if (DBA::isResult($data)) {
1394                         // For security reasons we don't fetch key data from our users
1395                         $data["pubkey"] = '';
1396                         return $data;
1397                 }
1398
1399                 $fields = ['url', 'addr', 'alias', 'notify', 'name', 'nick',
1400                         'photo', 'keywords', 'location', 'about', 'network'];
1401                 $data = DBA::selectFirst('gcontact', $fields, ['nurl' => Strings::normaliseLink($url)]);
1402
1403                 if (!DBA::isResult($data)) {
1404                         $condition = ['alias' => [$url, Strings::normaliseLink($url), $ssl_url]];
1405                         $data = DBA::selectFirst('contact', $fields, $condition);
1406                 }
1407
1408                 if (DBA::isResult($data)) {
1409                         $data["pubkey"] = '';
1410                         $data["poll"] = '';
1411                         $data["priority"] = 0;
1412                         $data["batch"] = '';
1413                         $data["request"] = '';
1414                         $data["confirm"] = '';
1415                         $data["poco"] = '';
1416                         return $data;
1417                 }
1418
1419                 $data = ActivityPub::probeProfile($url, false);
1420                 if (!empty($data)) {
1421                         return $data;
1422                 }
1423
1424                 $fields = ['url', 'addr', 'alias', 'notify', 'poll', 'name', 'nick',
1425                         'photo', 'network', 'priority', 'batch', 'request', 'confirm'];
1426                 $data = DBA::selectFirst('fcontact', $fields, ['url' => $url]);
1427
1428                 if (!DBA::isResult($data)) {
1429                         $condition = ['alias' => [$url, Strings::normaliseLink($url), $ssl_url]];
1430                         $data = DBA::selectFirst('contact', $fields, $condition);
1431                 }
1432
1433                 if (DBA::isResult($data)) {
1434                         $data["pubkey"] = '';
1435                         $data["keywords"] = '';
1436                         $data["location"] = '';
1437                         $data["about"] = '';
1438                         $data["poco"] = '';
1439                         return $data;
1440                 }
1441
1442                 return [];
1443         }
1444
1445         /**
1446          * Fetch the contact id for a given URL and user
1447          *
1448          * First lookup in the contact table to find a record matching either `url`, `nurl`,
1449          * `addr` or `alias`.
1450          *
1451          * If there's no record and we aren't looking for a public contact, we quit.
1452          * If there's one, we check that it isn't time to update the picture else we
1453          * directly return the found contact id.
1454          *
1455          * Second, we probe the provided $url whether it's http://server.tld/profile or
1456          * nick@server.tld. We quit if we can't get any info back.
1457          *
1458          * Third, we create the contact record if it doesn't exist
1459          *
1460          * Fourth, we update the existing record with the new data (avatar, alias, nick)
1461          * if there's any updates
1462          *
1463          * @param string  $url       Contact URL
1464          * @param integer $uid       The user id for the contact (0 = public contact)
1465          * @param boolean $no_update Don't update the contact
1466          * @param array   $default   Default value for creating the contact when every else fails
1467          * @param boolean $in_loop   Internally used variable to prevent an endless loop
1468          *
1469          * @return integer Contact ID
1470          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1471          * @throws \ImagickException
1472          */
1473         public static function getIdForURL($url, $uid = 0, $no_update = false, $default = [], $in_loop = false)
1474         {
1475                 Logger::log("Get contact data for url " . $url . " and user " . $uid . " - " . System::callstack(), Logger::DEBUG);
1476
1477                 $contact_id = 0;
1478
1479                 if ($url == '') {
1480                         return 0;
1481                 }
1482
1483                 /// @todo Verify if we can't use Contact::getDetailsByUrl instead of the following
1484                 // We first try the nurl (http://server.tld/nick), most common case
1485                 $fields = ['id', 'avatar', 'updated', 'network'];
1486                 $options = ['order' => ['id']];
1487                 $contact = DBA::selectFirst('contact', $fields, ['nurl' => Strings::normaliseLink($url), 'uid' => $uid, 'deleted' => false], $options);
1488
1489                 // Then the addr (nick@server.tld)
1490                 if (!DBA::isResult($contact)) {
1491                         $contact = DBA::selectFirst('contact', $fields, ['addr' => str_replace('acct:', '', $url), 'uid' => $uid, 'deleted' => false], $options);
1492                 }
1493
1494                 // Then the alias (which could be anything)
1495                 if (!DBA::isResult($contact)) {
1496                         // The link could be provided as http although we stored it as https
1497                         $ssl_url = str_replace('http://', 'https://', $url);
1498                         $condition = ['`alias` IN (?, ?, ?) AND `uid` = ? AND NOT `deleted`', $url, Strings::normaliseLink($url), $ssl_url, $uid];
1499                         $contact = DBA::selectFirst('contact', $fields, $condition, $options);
1500                 }
1501
1502                 if (DBA::isResult($contact)) {
1503                         $contact_id = $contact["id"];
1504                         $update_contact = false;
1505
1506                         // Update the contact every 7 days (Don't update mail or feed contacts)
1507                         if (in_array($contact['network'], Protocol::FEDERATED)) {
1508                                 $update_contact = ($contact['updated'] < DateTimeFormat::utc('now -7 days'));
1509
1510                                 // We force the update if the avatar is empty
1511                                 if (empty($contact['avatar'])) {
1512                                         $update_contact = true;
1513                                 }
1514                         } elseif (empty($default) && in_array($contact['network'], [Protocol::MAIL, Protocol::PHANTOM]) && ($uid == 0)) {
1515                                 // Update public mail accounts via their user's accounts
1516                                 $fields = ['network', 'addr', 'name', 'nick', 'avatar', 'photo', 'thumb', 'micro'];
1517                                 $mailcontact = DBA::selectFirst('contact', $fields, ["`addr` = ? AND `network` = ? AND `uid` != 0", $url, Protocol::MAIL]);
1518                                 if (!DBA::isResult($mailcontact)) {
1519                                         $mailcontact = DBA::selectFirst('contact', $fields, ["`nurl` = ? AND `network` = ? AND `uid` != 0", $url, Protocol::MAIL]);
1520                                 }
1521
1522                                 if (DBA::isResult($mailcontact)) {
1523                                         DBA::update('contact', $mailcontact, ['id' => $contact_id]);
1524                                 }
1525                         }
1526
1527                         // Update the contact in the background if needed but it is called by the frontend
1528                         if ($update_contact && $no_update && in_array($contact['network'], Protocol::NATIVE_SUPPORT)) {
1529                                 Worker::add(PRIORITY_LOW, "UpdateContact", $contact_id, ($uid == 0 ? 'force' : ''));
1530                         }
1531
1532                         if (!$update_contact || $no_update) {
1533                                 return $contact_id;
1534                         }
1535                 } elseif ($uid != 0) {
1536                         // Non-existing user-specific contact, exiting
1537                         return 0;
1538                 }
1539
1540                 if ($no_update && empty($default)) {
1541                         // When we don't want to update, we look if we know this contact in any way
1542                         $data = self::getProbeDataFromDatabase($url, $contact_id);
1543                         $background_update = true;
1544                 } elseif ($no_update && !empty($default['network'])) {
1545                         // If there are default values, take these
1546                         $data = $default;
1547                         $background_update = false;
1548                 } else {
1549                         $data = [];
1550                         $background_update = false;
1551                 }
1552
1553                 if (empty($data)) {
1554                         $data = Probe::uri($url, "", $uid);
1555                         // Ensure that there is a gserver entry
1556                         if (!empty($data['baseurl']) && ($data['network'] != Protocol::PHANTOM)) {
1557                                 GServer::check($data['baseurl']);
1558                         }
1559                 }
1560
1561                 // Take the default values when probing failed
1562                 if (!empty($default) && !in_array($data["network"], array_merge(Protocol::NATIVE_SUPPORT, [Protocol::PUMPIO]))) {
1563                         $data = array_merge($data, $default);
1564                 }
1565
1566                 if (empty($data) || ($data['network'] == Protocol::PHANTOM)) {
1567                         Logger::info('No valid network found', ['url' => $url, 'data' => $data, 'callstack' => System::callstack(20)]);
1568                         return 0;
1569                 }
1570
1571                 if (!$contact_id && !empty($data['alias']) && ($data['alias'] != $url) && !$in_loop) {
1572                         $contact_id = self::getIdForURL($data["alias"], $uid, true, $default, true);
1573                 }
1574
1575                 if (!$contact_id) {
1576                         $fields = [
1577                                 'uid'       => $uid,
1578                                 'created'   => DateTimeFormat::utcNow(),
1579                                 'url'       => $data['url'],
1580                                 'nurl'      => Strings::normaliseLink($data['url']),
1581                                 'addr'      => $data['addr'] ?? '',
1582                                 'alias'     => $data['alias'] ?? '',
1583                                 'notify'    => $data['notify'] ?? '',
1584                                 'poll'      => $data['poll'] ?? '',
1585                                 'name'      => $data['name'] ?? '',
1586                                 'nick'      => $data['nick'] ?? '',
1587                                 'photo'     => $data['photo'] ?? '',
1588                                 'keywords'  => $data['keywords'] ?? '',
1589                                 'location'  => $data['location'] ?? '',
1590                                 'about'     => $data['about'] ?? '',
1591                                 'network'   => $data['network'],
1592                                 'pubkey'    => $data['pubkey'] ?? '',
1593                                 'rel'       => self::SHARING,
1594                                 'priority'  => $data['priority'] ?? 0,
1595                                 'batch'     => $data['batch'] ?? '',
1596                                 'request'   => $data['request'] ?? '',
1597                                 'confirm'   => $data['confirm'] ?? '',
1598                                 'poco'      => $data['poco'] ?? '',
1599                                 'baseurl'   => $data['baseurl'] ?? '',
1600                                 'name-date' => DateTimeFormat::utcNow(),
1601                                 'uri-date'  => DateTimeFormat::utcNow(),
1602                                 'avatar-date' => DateTimeFormat::utcNow(),
1603                                 'writable'  => 1,
1604                                 'blocked'   => 0,
1605                                 'readonly'  => 0,
1606                                 'pending'   => 0];
1607
1608                         $condition = ['nurl' => Strings::normaliseLink($data["url"]), 'uid' => $uid, 'deleted' => false];
1609
1610                         // Before inserting we do check if the entry does exist now.
1611                         $contact = DBA::selectFirst('contact', ['id'], $condition, ['order' => ['id']]);
1612                         if (!DBA::isResult($contact)) {
1613                                 Logger::info('Create new contact', $fields);
1614
1615                                 self::insert($fields);
1616
1617                                 // We intentionally aren't using lastInsertId here. There is a chance for duplicates.
1618                                 $contact = DBA::selectFirst('contact', ['id'], $condition, ['order' => ['id']]);
1619                                 if (!DBA::isResult($contact)) {
1620                                         Logger::info('Contact creation failed', $fields);
1621                                         // Shouldn't happen
1622                                         return 0;
1623                                 }
1624                         } else {
1625                                 Logger::info('Contact had been created before', ['id' => $contact["id"], 'url' => $url, 'contact' => $fields]);
1626                         }
1627
1628                         $contact_id = $contact["id"];
1629                 }
1630
1631                 if (!empty($data['photo']) && ($data['network'] != Protocol::FEED)) {
1632                         self::updateAvatar($data['photo'], $uid, $contact_id);
1633                 }
1634
1635                 if (in_array($data["network"], array_merge(Protocol::NATIVE_SUPPORT, [Protocol::PUMPIO]))) {
1636                         if ($background_update) {
1637                                 // Update in the background when we fetched the data solely from the database
1638                                 Worker::add(PRIORITY_MEDIUM, "UpdateContact", $contact_id, ($uid == 0 ? 'force' : ''));
1639                         } else {
1640                                 // Else do a direct update
1641                                 self::updateFromProbe($contact_id, '', false);
1642
1643                                 // Update the gcontact entry
1644                                 if ($uid == 0) {
1645                                         GContact::updateFromPublicContactID($contact_id);
1646                                 }
1647                         }
1648                 } else {
1649                         $fields = ['url', 'nurl', 'addr', 'alias', 'name', 'nick', 'keywords', 'location', 'about', 'avatar-date', 'baseurl'];
1650                         $contact = DBA::selectFirst('contact', $fields, ['id' => $contact_id]);
1651
1652                         // This condition should always be true
1653                         if (!DBA::isResult($contact)) {
1654                                 return $contact_id;
1655                         }
1656
1657                         $updated = [
1658                                 'url' => $data['url'],
1659                                 'nurl' => Strings::normaliseLink($data['url']),
1660                                 'updated' => DateTimeFormat::utcNow()
1661                         ];
1662
1663                         $fields = ['addr', 'alias', 'name', 'nick', 'keywords', 'location', 'about', 'baseurl'];
1664
1665                         foreach ($fields as $field) {
1666                                 $updated[$field] = ($data[$field] ?? '') ?: $contact[$field];
1667                         }
1668
1669                         if (($updated['addr'] != $contact['addr']) || (!empty($data['alias']) && ($data['alias'] != $contact['alias']))) {
1670                                 $updated['uri-date'] = DateTimeFormat::utcNow();
1671                         }
1672
1673                         if (($data['name'] != $contact['name']) || ($data['nick'] != $contact['nick'])) {
1674                                 $updated['name-date'] = DateTimeFormat::utcNow();
1675                         }
1676
1677                         DBA::update('contact', $updated, ['id' => $contact_id], $contact);
1678                 }
1679
1680                 return $contact_id;
1681         }
1682
1683         /**
1684          * Checks if the contact is archived
1685          *
1686          * @param int $cid contact id
1687          *
1688          * @return boolean Is the contact archived?
1689          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1690          */
1691         public static function isArchived(int $cid)
1692         {
1693                 if ($cid == 0) {
1694                         return false;
1695                 }
1696
1697                 $contact = DBA::selectFirst('contact', ['archive', 'url', 'batch'], ['id' => $cid]);
1698                 if (!DBA::isResult($contact)) {
1699                         return false;
1700                 }
1701
1702                 if ($contact['archive']) {
1703                         return true;
1704                 }
1705
1706                 // Check status of ActivityPub endpoints
1707                 $apcontact = APContact::getByURL($contact['url'], false);
1708                 if (!empty($apcontact)) {
1709                         if (!empty($apcontact['inbox']) && DBA::exists('inbox-status', ['archive' => true, 'url' => $apcontact['inbox']])) {
1710                                 return true;
1711                         }
1712
1713                         if (!empty($apcontact['sharedinbox']) && DBA::exists('inbox-status', ['archive' => true, 'url' => $apcontact['sharedinbox']])) {
1714                                 return true;
1715                         }
1716                 }
1717
1718                 // Check status of Diaspora endpoints
1719                 if (!empty($contact['batch'])) {
1720                         $condition = ['archive' => true, 'uid' => 0, 'network' => Protocol::FEDERATED, 'batch' => $contact['batch'], 'contact-type' => self::TYPE_RELAY];
1721                         return DBA::exists('contact', $condition);
1722                 }
1723
1724                 return false;
1725         }
1726
1727         /**
1728          * Checks if the contact is blocked
1729          *
1730          * @param int $cid contact id
1731          *
1732          * @return boolean Is the contact blocked?
1733          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1734          */
1735         public static function isBlocked($cid)
1736         {
1737                 if ($cid == 0) {
1738                         return false;
1739                 }
1740
1741                 $blocked = DBA::selectFirst('contact', ['blocked', 'url'], ['id' => $cid]);
1742                 if (!DBA::isResult($blocked)) {
1743                         return false;
1744                 }
1745
1746                 if (Network::isUrlBlocked($blocked['url'])) {
1747                         return true;
1748                 }
1749
1750                 return (bool) $blocked['blocked'];
1751         }
1752
1753         /**
1754          * Checks if the contact is hidden
1755          *
1756          * @param int $cid contact id
1757          *
1758          * @return boolean Is the contact hidden?
1759          * @throws \Exception
1760          */
1761         public static function isHidden($cid)
1762         {
1763                 if ($cid == 0) {
1764                         return false;
1765                 }
1766
1767                 $hidden = DBA::selectFirst('contact', ['hidden'], ['id' => $cid]);
1768                 if (!DBA::isResult($hidden)) {
1769                         return false;
1770                 }
1771                 return (bool) $hidden['hidden'];
1772         }
1773
1774         /**
1775          * Returns posts from a given contact url
1776          *
1777          * @param string $contact_url Contact URL
1778          *
1779          * @param bool   $thread_mode
1780          * @param int    $update
1781          * @return string posts in HTML
1782          * @throws \Exception
1783          */
1784         public static function getPostsFromUrl($contact_url, $thread_mode = false, $update = 0)
1785         {
1786                 $a = DI::app();
1787
1788                 $cid = self::getIdForURL($contact_url);
1789
1790                 $contact = DBA::selectFirst('contact', ['contact-type', 'network'], ['id' => $cid]);
1791                 if (!DBA::isResult($contact)) {
1792                         return '';
1793                 }
1794
1795                 if (empty($contact["network"]) || in_array($contact["network"], Protocol::FEDERATED)) {
1796                         $sql = "(`item`.`uid` = 0 OR (`item`.`uid` = ? AND NOT `item`.`global`))";
1797                 } else {
1798                         $sql = "`item`.`uid` = ?";
1799                 }
1800
1801                 $contact_field = ((($contact["contact-type"] == self::TYPE_COMMUNITY) || ($contact['network'] == Protocol::MAIL)) ? 'owner-id' : 'author-id');
1802
1803                 if ($thread_mode) {
1804                         $condition = ["`$contact_field` = ? AND `gravity` = ? AND " . $sql,
1805                                 $cid, GRAVITY_PARENT, local_user()];
1806                 } else {
1807                         $condition = ["`$contact_field` = ? AND `gravity` IN (?, ?) AND " . $sql,
1808                                 $cid, GRAVITY_PARENT, GRAVITY_COMMENT, local_user()];
1809                 }
1810
1811                 if (DI::mode()->isMobile()) {
1812                         $itemsPerPage = DI::pConfig()->get(local_user(), 'system', 'itemspage_mobile_network',
1813                                 DI::config()->get('system', 'itemspage_network_mobile'));
1814                 } else {
1815                         $itemsPerPage = DI::pConfig()->get(local_user(), 'system', 'itemspage_network',
1816                                 DI::config()->get('system', 'itemspage_network'));
1817                 }
1818
1819                 $pager = new Pager(DI::l10n(), DI::args()->getQueryString(), $itemsPerPage);
1820
1821                 $params = ['order' => ['received' => true],
1822                         'limit' => [$pager->getStart(), $pager->getItemsPerPage()]];
1823
1824                 if ($thread_mode) {
1825                         $r = Item::selectThreadForUser(local_user(), ['uri'], $condition, $params);
1826
1827                         $items = Item::inArray($r);
1828
1829                         $o = conversation($a, $items, 'contacts', $update, false, 'commented', local_user());
1830                 } else {
1831                         $r = Item::selectForUser(local_user(), [], $condition, $params);
1832
1833                         $items = Item::inArray($r);
1834
1835                         $o = conversation($a, $items, 'contact-posts', false);
1836                 }
1837
1838                 if (!$update) {
1839                         $o .= $pager->renderMinimal(count($items));
1840                 }
1841
1842                 return $o;
1843         }
1844
1845         /**
1846          * Returns the account type name
1847          *
1848          * The function can be called with either the user or the contact array
1849          *
1850          * @param array $contact contact or user array
1851          * @return string
1852          */
1853         public static function getAccountType(array $contact)
1854         {
1855                 // There are several fields that indicate that the contact or user is a forum
1856                 // "page-flags" is a field in the user table,
1857                 // "forum" and "prv" are used in the contact table. They stand for User::PAGE_FLAGS_COMMUNITY and User::PAGE_FLAGS_PRVGROUP.
1858                 // "community" is used in the gcontact table and is true if the contact is User::PAGE_FLAGS_COMMUNITY or User::PAGE_FLAGS_PRVGROUP.
1859                 if ((isset($contact['page-flags']) && (intval($contact['page-flags']) == User::PAGE_FLAGS_COMMUNITY))
1860                         || (isset($contact['page-flags']) && (intval($contact['page-flags']) == User::PAGE_FLAGS_PRVGROUP))
1861                         || (isset($contact['forum']) && intval($contact['forum']))
1862                         || (isset($contact['prv']) && intval($contact['prv']))
1863                         || (isset($contact['community']) && intval($contact['community']))
1864                 ) {
1865                         $type = self::TYPE_COMMUNITY;
1866                 } else {
1867                         $type = self::TYPE_PERSON;
1868                 }
1869
1870                 // The "contact-type" (contact table) and "account-type" (user table) are more general then the chaos from above.
1871                 if (isset($contact["contact-type"])) {
1872                         $type = $contact["contact-type"];
1873                 }
1874
1875                 if (isset($contact["account-type"])) {
1876                         $type = $contact["account-type"];
1877                 }
1878
1879                 switch ($type) {
1880                         case self::TYPE_ORGANISATION:
1881                                 $account_type = DI::l10n()->t("Organisation");
1882                                 break;
1883
1884                         case self::TYPE_NEWS:
1885                                 $account_type = DI::l10n()->t('News');
1886                                 break;
1887
1888                         case self::TYPE_COMMUNITY:
1889                                 $account_type = DI::l10n()->t("Forum");
1890                                 break;
1891
1892                         default:
1893                                 $account_type = "";
1894                                 break;
1895                 }
1896
1897                 return $account_type;
1898         }
1899
1900         /**
1901          * Blocks a contact
1902          *
1903          * @param int $cid
1904          * @return bool
1905          * @throws \Exception
1906          */
1907         public static function block($cid, $reason = null)
1908         {
1909                 $return = DBA::update('contact', ['blocked' => true, 'block_reason' => $reason], ['id' => $cid]);
1910
1911                 return $return;
1912         }
1913
1914         /**
1915          * Unblocks a contact
1916          *
1917          * @param int $cid
1918          * @return bool
1919          * @throws \Exception
1920          */
1921         public static function unblock($cid)
1922         {
1923                 $return = DBA::update('contact', ['blocked' => false, 'block_reason' => null], ['id' => $cid]);
1924
1925                 return $return;
1926         }
1927
1928         /**
1929          * Updates the avatar links in a contact only if needed
1930          *
1931          * @param string $avatar Link to avatar picture
1932          * @param int    $uid    User id of contact owner
1933          * @param int    $cid    Contact id
1934          * @param bool   $force  force picture update
1935          *
1936          * @return array Returns array of the different avatar sizes
1937          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1938          * @throws \ImagickException
1939          */
1940         public static function updateAvatar($avatar, $uid, $cid, $force = false)
1941         {
1942                 $contact = DBA::selectFirst('contact', ['avatar', 'photo', 'thumb', 'micro', 'nurl'], ['id' => $cid, 'self' => false]);
1943                 if (!DBA::isResult($contact)) {
1944                         return false;
1945                 } else {
1946                         $data = [$contact["photo"], $contact["thumb"], $contact["micro"]];
1947                 }
1948
1949                 foreach ($data as $image_uri) {
1950                         $image_rid = Photo::ridFromURI($image_uri);
1951                         if ($image_rid && !Photo::exists(['resource-id' => $image_rid, 'uid' => $uid])) {
1952                                 Logger::info('Regenerating avatar', ['contact uid' => $uid, 'cid' => $cid, 'missing photo' => $image_rid, 'avatar' => $contact['avatar']]);
1953                                 $force = true;
1954                         }
1955                 }
1956
1957                 if (($contact["avatar"] != $avatar) || $force) {
1958                         $photos = Photo::importProfilePhoto($avatar, $uid, $cid, true);
1959
1960                         if ($photos) {
1961                                 $fields = ['avatar' => $avatar, 'photo' => $photos[0], 'thumb' => $photos[1], 'micro' => $photos[2], 'avatar-date' => DateTimeFormat::utcNow()];
1962                                 DBA::update('contact', $fields, ['id' => $cid]);
1963
1964                                 // Update the public contact (contact id = 0)
1965                                 if ($uid != 0) {
1966                                         $pcontact = DBA::selectFirst('contact', ['id'], ['nurl' => $contact['nurl'], 'uid' => 0]);
1967                                         if (DBA::isResult($pcontact)) {
1968                                                 DBA::update('contact', $fields, ['id' => $pcontact['id']]);
1969                                         }
1970                                 }
1971
1972                                 return $photos;
1973                         }
1974                 }
1975
1976                 return $data;
1977         }
1978
1979         /**
1980          * Helper function for "updateFromProbe". Updates personal and public contact
1981          *
1982          * @param integer $id      contact id
1983          * @param integer $uid     user id
1984          * @param string  $url     The profile URL of the contact
1985          * @param array   $fields  The fields that are updated
1986          *
1987          * @throws \Exception
1988          */
1989         private static function updateContact($id, $uid, $url, array $fields)
1990         {
1991                 if (!DBA::update('contact', $fields, ['id' => $id])) {
1992                         Logger::info('Couldn\'t update contact.', ['id' => $id, 'fields' => $fields]);
1993                         return;
1994                 }
1995
1996                 // Search for duplicated contacts and get rid of them
1997                 if (self::removeDuplicates(Strings::normaliseLink($url), $uid) || ($uid != 0)) {
1998                         return;
1999                 }
2000
2001                 // Update the corresponding gcontact entry
2002                 GContact::updateFromPublicContactID($id);
2003
2004                 // Archive or unarchive the contact. We only need to do this for the public contact.
2005                 // The archive/unarchive function will update the personal contacts by themselves.
2006                 $contact = DBA::selectFirst('contact', [], ['id' => $id]);
2007                 if (!DBA::isResult($contact)) {
2008                         Logger::info('Couldn\'t select contact for archival.', ['id' => $id]);
2009                         return;
2010                 }
2011
2012                 if (!empty($fields['success_update'])) {
2013                         self::unmarkForArchival($contact);
2014                 } elseif (!empty($fields['failure_update'])) {
2015                         self::markForArchival($contact);
2016                 }
2017
2018                 $condition = ['self' => false, 'nurl' => Strings::normaliseLink($url), 'network' => Protocol::FEDERATED];
2019
2020                 // These contacts are sharing with us, we don't poll them.
2021                 // This means that we don't set the update fields in "OnePoll.php".
2022                 $condition['rel'] = self::SHARING;
2023                 DBA::update('contact', $fields, $condition);
2024
2025                 unset($fields['last-update']);
2026                 unset($fields['success_update']);
2027                 unset($fields['failure_update']);
2028
2029                 if (empty($fields)) {
2030                         return;
2031                 }
2032
2033                 // We are polling these contacts, so we mustn't set the update fields here.
2034                 $condition['rel'] = [self::FOLLOWER, self::FRIEND];
2035                 DBA::update('contact', $fields, $condition);
2036         }
2037
2038         /**
2039          * Remove duplicated contacts
2040          *
2041          * @param string  $nurl  Normalised contact url
2042          * @param integer $uid   User id
2043          * @return boolean
2044          * @throws \Exception
2045          */
2046         public static function removeDuplicates(string $nurl, int $uid)
2047         {
2048                 $condition = ['nurl' => $nurl, 'uid' => $uid, 'deleted' => false, 'network' => Protocol::FEDERATED];
2049                 $count = DBA::count('contact', $condition);
2050                 if ($count <= 1) {
2051                         return false;
2052                 }
2053
2054                 $first_contact = DBA::selectFirst('contact', ['id', 'network'], $condition, ['order' => ['id']]);
2055                 if (!DBA::isResult($first_contact)) {
2056                         // Shouldn't happen - so we handle it
2057                         return false;
2058                 }
2059
2060                 $first = $first_contact['id'];
2061                 Logger::info('Found duplicates', ['count' => $count, 'first' => $first, 'uid' => $uid, 'nurl' => $nurl]);
2062                 if (($uid != 0 && ($first_contact['network'] == Protocol::DFRN))) {
2063                         // Don't handle non public DFRN duplicates by now (legacy DFRN is very special because of the key handling)
2064                         Logger::info('Not handling non public DFRN duplicate', ['uid' => $uid, 'nurl' => $nurl]);
2065                         return false;
2066                 }
2067
2068                 // Find all duplicates
2069                 $condition = ["`nurl` = ? AND `uid` = ? AND `id` != ? AND NOT `self` AND NOT `deleted`", $nurl, $uid, $first];
2070                 $duplicates = DBA::select('contact', ['id', 'network'], $condition);
2071                 while ($duplicate = DBA::fetch($duplicates)) {
2072                         if (!in_array($duplicate['network'], Protocol::FEDERATED)) {
2073                                 continue;
2074                         }
2075
2076                         Worker::add(PRIORITY_HIGH, 'MergeContact', $first, $duplicate['id'], $uid);
2077                 }
2078                 Logger::info('Duplicates handled', ['uid' => $uid, 'nurl' => $nurl]);
2079                 return true;
2080         }
2081
2082         /**
2083          * @param integer $id      contact id
2084          * @param string  $network Optional network we are probing for
2085          * @param boolean $force   Optional forcing of network probing (otherwise we use the cached data)
2086          * @return boolean
2087          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2088          * @throws \ImagickException
2089          */
2090         public static function updateFromProbe($id, $network = '', $force = false)
2091         {
2092                 /*
2093                   Warning: Never ever fetch the public key via Probe::uri and write it into the contacts.
2094                   This will reliably kill your communication with old Friendica contacts.
2095                  */
2096
2097                 // These fields aren't updated by this routine:
2098                 // 'xmpp', 'sensitive'
2099
2100                 $fields = ['uid', 'avatar', 'name', 'nick', 'location', 'keywords', 'about',
2101                         'unsearchable', 'url', 'addr', 'batch', 'notify', 'poll', 'request', 'confirm', 'poco',
2102                         'network', 'alias', 'baseurl', 'forum', 'prv', 'contact-type', 'pubkey'];
2103                 $contact = DBA::selectFirst('contact', $fields, ['id' => $id]);
2104                 if (!DBA::isResult($contact)) {
2105                         return false;
2106                 }
2107
2108                 $uid = $contact['uid'];
2109                 unset($contact['uid']);
2110
2111                 $pubkey = $contact['pubkey'];
2112                 unset($contact['pubkey']);
2113
2114                 $contact['photo'] = $contact['avatar'];
2115                 unset($contact['avatar']);
2116
2117                 $ret = Probe::uri($contact['url'], $network, $uid, !$force);
2118
2119                 $updated = DateTimeFormat::utcNow();
2120
2121                 // We must not try to update relay contacts via probe. They are no real contacts.
2122                 // We check after the probing to be able to correct falsely detected contact types.
2123                 if (($contact['contact-type'] == self::TYPE_RELAY) &&
2124                         (!Strings::compareLink($ret['url'], $contact['url']) || in_array($ret['network'], [Protocol::FEED, Protocol::PHANTOM]))) {
2125                         self::updateContact($id, $uid, $contact['url'], ['last-update' => $updated, 'success_update' => $updated]);
2126                         Logger::info('Not updating relais', ['id' => $id, 'url' => $contact['url']]);
2127                         return true;
2128                 }
2129
2130                 // If Probe::uri fails the network code will be different ("feed" or "unkn")
2131                 if (in_array($ret['network'], [Protocol::FEED, Protocol::PHANTOM]) && ($ret['network'] != $contact['network'])) {
2132                         if ($force && ($uid == 0)) {
2133                                 self::updateContact($id, $uid, $ret['url'], ['last-update' => $updated, 'failure_update' => $updated]);
2134                         }
2135                         return false;
2136                 }
2137
2138                 if (isset($ret['hide']) && is_bool($ret['hide'])) {
2139                         $ret['unsearchable'] = $ret['hide'];
2140                 }
2141
2142                 if (isset($ret['account-type']) && is_int($ret['account-type'])) {
2143                         $ret['forum'] = false;
2144                         $ret['prv'] = false;
2145                         $ret['contact-type'] = $ret['account-type'];
2146                         if ($ret['contact-type'] == User::ACCOUNT_TYPE_COMMUNITY) {
2147                                 $apcontact = APContact::getByURL($ret['url'], false);
2148                                 if (isset($apcontact['manually-approve'])) {
2149                                         $ret['forum'] = (bool)!$apcontact['manually-approve'];
2150                                         $ret['prv'] = (bool)!$ret['forum'];
2151                                 }
2152                         }
2153                 }
2154
2155                 $new_pubkey = $ret['pubkey'];
2156
2157                 $update = false;
2158
2159                 // make sure to not overwrite existing values with blank entries except some technical fields
2160                 $keep = ['batch', 'notify', 'poll', 'request', 'confirm', 'poco', 'baseurl'];
2161                 foreach ($ret as $key => $val) {
2162                         if (!array_key_exists($key, $contact)) {
2163                                 unset($ret[$key]);
2164                         } elseif (($contact[$key] != '') && ($val === '') && !is_bool($ret[$key]) && !in_array($key, $keep)) {
2165                                 $ret[$key] = $contact[$key];
2166                         } elseif ($ret[$key] != $contact[$key]) {
2167                                 $update = true;
2168                         }
2169                 }
2170
2171                 if (!empty($ret['photo']) && ($ret['network'] != Protocol::FEED)) {
2172                         self::updateAvatar($ret['photo'], $uid, $id, $update || $force);
2173                 }
2174
2175                 if (!$update) {
2176                         if ($force) {
2177                                 self::updateContact($id, $uid, $ret['url'], ['last-update' => $updated, 'success_update' => $updated]);
2178                         }
2179
2180                         // Update the public contact
2181                         if ($uid != 0) {
2182                                 self::updateFromProbeByURL($ret['url']);
2183                         }
2184
2185                         return true;
2186                 }
2187
2188                 $ret['nurl'] = Strings::normaliseLink($ret['url']);
2189                 $ret['updated'] = $updated;
2190
2191                 // Only fill the pubkey if it had been empty before. We have to prevent identity theft.
2192                 if (empty($pubkey) && !empty($new_pubkey)) {
2193                         $ret['pubkey'] = $new_pubkey;
2194                 }
2195
2196                 if (($ret['addr'] != $contact['addr']) || (!empty($ret['alias']) && ($ret['alias'] != $contact['alias']))) {
2197                         $ret['uri-date'] = DateTimeFormat::utcNow();
2198                 }
2199
2200                 if (($ret['name'] != $contact['name']) || ($ret['nick'] != $contact['nick'])) {
2201                         $ret['name-date'] = $updated;
2202                 }
2203
2204                 if ($force && ($uid == 0)) {
2205                         $ret['last-update'] = $updated;
2206                         $ret['success_update'] = $updated;
2207                 }
2208
2209                 unset($ret['photo']);
2210
2211                 self::updateContact($id, $uid, $ret['url'], $ret);
2212
2213                 return true;
2214         }
2215
2216         public static function updateFromProbeByURL($url, $force = false)
2217         {
2218                 $id = self::getIdForURL($url);
2219
2220                 if (empty($id)) {
2221                         return $id;
2222                 }
2223
2224                 self::updateFromProbe($id, '', $force);
2225
2226                 return $id;
2227         }
2228
2229         /**
2230          * Detects if a given contact array belongs to a legacy DFRN connection
2231          *
2232          * @param array $contact
2233          * @return boolean
2234          */
2235         public static function isLegacyDFRNContact($contact)
2236         {
2237                 // Newer Friendica contacts are connected via AP, then these fields aren't set
2238                 return !empty($contact['dfrn-id']) || !empty($contact['issued-id']);
2239         }
2240
2241         /**
2242          * Detects the communication protocol for a given contact url.
2243          * This is used to detect Friendica contacts that we can communicate via AP.
2244          *
2245          * @param string $url contact url
2246          * @param string $network Network of that contact
2247          * @return string with protocol
2248          */
2249         public static function getProtocol($url, $network)
2250         {
2251                 if ($network != Protocol::DFRN) {
2252                         return $network;
2253                 }
2254
2255                 $apcontact = APContact::getByURL($url);
2256                 if (!empty($apcontact) && !empty($apcontact['generator'])) {
2257                         return Protocol::ACTIVITYPUB;
2258                 } else {
2259                         return $network;
2260                 }
2261         }
2262
2263         /**
2264          * Takes a $uid and a url/handle and adds a new contact
2265          *
2266          * Currently if the contact is DFRN, interactive needs to be true, to redirect to the
2267          * dfrn_request page.
2268          *
2269          * Otherwise this can be used to bulk add StatusNet contacts, Twitter contacts, etc.
2270          *
2271          * Returns an array
2272          * $return['success'] boolean true if successful
2273          * $return['message'] error text if success is false.
2274          *
2275          * Takes a $uid and a url/handle and adds a new contact
2276          * @param int    $uid
2277          * @param string $url
2278          * @param bool   $interactive
2279          * @param string $network
2280          * @return array
2281          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2282          * @throws \ImagickException
2283          */
2284         public static function createFromProbe($uid, $url, $interactive = false, $network = '')
2285         {
2286                 $result = ['cid' => -1, 'success' => false, 'message' => ''];
2287
2288                 $a = DI::app();
2289
2290                 // remove ajax junk, e.g. Twitter
2291                 $url = str_replace('/#!/', '/', $url);
2292
2293                 if (!Network::isUrlAllowed($url)) {
2294                         $result['message'] = DI::l10n()->t('Disallowed profile URL.');
2295                         return $result;
2296                 }
2297
2298                 if (Network::isUrlBlocked($url)) {
2299                         $result['message'] = DI::l10n()->t('Blocked domain');
2300                         return $result;
2301                 }
2302
2303                 if (!$url) {
2304                         $result['message'] = DI::l10n()->t('Connect URL missing.');
2305                         return $result;
2306                 }
2307
2308                 $arr = ['url' => $url, 'contact' => []];
2309
2310                 Hook::callAll('follow', $arr);
2311
2312                 if (empty($arr)) {
2313                         $result['message'] = DI::l10n()->t('The contact could not be added. Please check the relevant network credentials in your Settings -> Social Networks page.');
2314                         return $result;
2315                 }
2316
2317                 if (!empty($arr['contact']['name'])) {
2318                         $ret = $arr['contact'];
2319                 } else {
2320                         $ret = Probe::uri($url, $network, $uid, false);
2321                 }
2322
2323                 if (($network != '') && ($ret['network'] != $network)) {
2324                         Logger::log('Expected network ' . $network . ' does not match actual network ' . $ret['network']);
2325                         return $result;
2326                 }
2327
2328                 // check if we already have a contact
2329                 // the poll url is more reliable than the profile url, as we may have
2330                 // indirect links or webfinger links
2331
2332                 $condition = ['uid' => $uid, 'poll' => [$ret['poll'], Strings::normaliseLink($ret['poll'])], 'network' => $ret['network'], 'pending' => false];
2333                 $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
2334                 if (!DBA::isResult($contact)) {
2335                         $condition = ['uid' => $uid, 'nurl' => Strings::normaliseLink($url), 'network' => $ret['network'], 'pending' => false];
2336                         $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
2337                 }
2338
2339                 $protocol = self::getProtocol($url, $ret['network']);
2340
2341                 if (($protocol === Protocol::DFRN) && !DBA::isResult($contact)) {
2342                         if ($interactive) {
2343                                 if (strlen(DI::baseUrl()->getUrlPath())) {
2344                                         $myaddr = bin2hex(DI::baseUrl() . '/profile/' . $a->user['nickname']);
2345                                 } else {
2346                                         $myaddr = bin2hex($a->user['nickname'] . '@' . DI::baseUrl()->getHostname());
2347                                 }
2348
2349                                 DI::baseUrl()->redirect($ret['request'] . "&addr=$myaddr");
2350
2351                                 // NOTREACHED
2352                         }
2353                 } elseif (DI::config()->get('system', 'dfrn_only') && ($ret['network'] != Protocol::DFRN)) {
2354                         $result['message'] = DI::l10n()->t('This site is not configured to allow communications with other networks.') . EOL;
2355                         $result['message'] .= DI::l10n()->t('No compatible communication protocols or feeds were discovered.') . EOL;
2356                         return $result;
2357                 }
2358
2359                 // This extra param just confuses things, remove it
2360                 if ($protocol === Protocol::DIASPORA) {
2361                         $ret['url'] = str_replace('?absolute=true', '', $ret['url']);
2362                 }
2363
2364                 // do we have enough information?
2365                 if (empty($ret['name']) || empty($ret['poll']) || (empty($ret['url']) && empty($ret['addr']))) {
2366                         $result['message'] .= DI::l10n()->t('The profile address specified does not provide adequate information.') . EOL;
2367                         if (empty($ret['poll'])) {
2368                                 $result['message'] .= DI::l10n()->t('No compatible communication protocols or feeds were discovered.') . EOL;
2369                         }
2370                         if (empty($ret['name'])) {
2371                                 $result['message'] .= DI::l10n()->t('An author or name was not found.') . EOL;
2372                         }
2373                         if (empty($ret['url'])) {
2374                                 $result['message'] .= DI::l10n()->t('No browser URL could be matched to this address.') . EOL;
2375                         }
2376                         if (strpos($url, '@') !== false) {
2377                                 $result['message'] .= DI::l10n()->t('Unable to match @-style Identity Address with a known protocol or email contact.') . EOL;
2378                                 $result['message'] .= DI::l10n()->t('Use mailto: in front of address to force email check.') . EOL;
2379                         }
2380                         return $result;
2381                 }
2382
2383                 if ($protocol === Protocol::OSTATUS && DI::config()->get('system', 'ostatus_disabled')) {
2384                         $result['message'] .= DI::l10n()->t('The profile address specified belongs to a network which has been disabled on this site.') . EOL;
2385                         $ret['notify'] = '';
2386                 }
2387
2388                 if (!$ret['notify']) {
2389                         $result['message'] .= DI::l10n()->t('Limited profile. This person will be unable to receive direct/personal notifications from you.') . EOL;
2390                 }
2391
2392                 $writeable = ((($protocol === Protocol::OSTATUS) && ($ret['notify'])) ? 1 : 0);
2393
2394                 $subhub = (($protocol === Protocol::OSTATUS) ? true : false);
2395
2396                 $hidden = (($protocol === Protocol::MAIL) ? 1 : 0);
2397
2398                 $pending = false;
2399                 if ($protocol == Protocol::ACTIVITYPUB) {
2400                         $apcontact = APContact::getByURL($url, false);
2401                         if (isset($apcontact['manually-approve'])) {
2402                                 $pending = (bool)$apcontact['manually-approve'];
2403                         }
2404                 }
2405
2406                 if (in_array($protocol, [Protocol::MAIL, Protocol::DIASPORA, Protocol::ACTIVITYPUB])) {
2407                         $writeable = 1;
2408                 }
2409
2410                 if (DBA::isResult($contact)) {
2411                         // update contact
2412                         $new_relation = (($contact['rel'] == self::FOLLOWER) ? self::FRIEND : self::SHARING);
2413
2414                         $fields = ['rel' => $new_relation, 'subhub' => $subhub, 'readonly' => false];
2415                         DBA::update('contact', $fields, ['id' => $contact['id']]);
2416                 } else {
2417                         $new_relation = (in_array($protocol, [Protocol::MAIL]) ? self::FRIEND : self::SHARING);
2418
2419                         // create contact record
2420                         self::insert([
2421                                 'uid'     => $uid,
2422                                 'created' => DateTimeFormat::utcNow(),
2423                                 'url'     => $ret['url'],
2424                                 'nurl'    => Strings::normaliseLink($ret['url']),
2425                                 'addr'    => $ret['addr'],
2426                                 'alias'   => $ret['alias'],
2427                                 'batch'   => $ret['batch'],
2428                                 'notify'  => $ret['notify'],
2429                                 'poll'    => $ret['poll'],
2430                                 'poco'    => $ret['poco'],
2431                                 'name'    => $ret['name'],
2432                                 'nick'    => $ret['nick'],
2433                                 'network' => $ret['network'],
2434                                 'baseurl' => $ret['baseurl'],
2435                                 'protocol' => $protocol,
2436                                 'pubkey'  => $ret['pubkey'],
2437                                 'rel'     => $new_relation,
2438                                 'priority'=> $ret['priority'],
2439                                 'writable'=> $writeable,
2440                                 'hidden'  => $hidden,
2441                                 'blocked' => 0,
2442                                 'readonly'=> 0,
2443                                 'pending' => $pending,
2444                                 'subhub'  => $subhub
2445                         ]);
2446                 }
2447
2448                 $contact = DBA::selectFirst('contact', [], ['url' => $ret['url'], 'network' => $ret['network'], 'uid' => $uid]);
2449                 if (!DBA::isResult($contact)) {
2450                         $result['message'] .= DI::l10n()->t('Unable to retrieve contact information.') . EOL;
2451                         return $result;
2452                 }
2453
2454                 $contact_id = $contact['id'];
2455                 $result['cid'] = $contact_id;
2456
2457                 Group::addMember(User::getDefaultGroup($uid, $contact["network"]), $contact_id);
2458
2459                 // Update the avatar
2460                 self::updateAvatar($ret['photo'], $uid, $contact_id);
2461
2462                 // pull feed and consume it, which should subscribe to the hub.
2463
2464                 Worker::add(PRIORITY_HIGH, "OnePoll", $contact_id, "force");
2465
2466                 $owner = User::getOwnerDataById($uid);
2467
2468                 if (DBA::isResult($owner)) {
2469                         if (in_array($protocol, [Protocol::OSTATUS, Protocol::DFRN])) {
2470                                 // create a follow slap
2471                                 $item = [];
2472                                 $item['verb'] = Activity::FOLLOW;
2473                                 $item['follow'] = $contact["url"];
2474                                 $item['body'] = '';
2475                                 $item['title'] = '';
2476                                 $item['guid'] = '';
2477                                 $item['tag'] = '';
2478                                 $item['attach'] = '';
2479
2480                                 $slap = OStatus::salmon($item, $owner);
2481
2482                                 if (!empty($contact['notify'])) {
2483                                         Salmon::slapper($owner, $contact['notify'], $slap);
2484                                 }
2485                         } elseif ($protocol == Protocol::DIASPORA) {
2486                                 $ret = Diaspora::sendShare($a->user, $contact);
2487                                 Logger::log('share returns: ' . $ret);
2488                         } elseif ($protocol == Protocol::ACTIVITYPUB) {
2489                                 $activity_id = ActivityPub\Transmitter::activityIDFromContact($contact_id);
2490                                 if (empty($activity_id)) {
2491                                         // This really should never happen
2492                                         return false;
2493                                 }
2494
2495                                 $ret = ActivityPub\Transmitter::sendActivity('Follow', $contact['url'], $uid, $activity_id);
2496                                 Logger::log('Follow returns: ' . $ret);
2497                         }
2498                 }
2499
2500                 $result['success'] = true;
2501                 return $result;
2502         }
2503
2504         /**
2505          * Updated contact's SSL policy
2506          *
2507          * @param array  $contact    Contact array
2508          * @param string $new_policy New policy, valid: self,full
2509          *
2510          * @return array Contact array with updated values
2511          * @throws \Exception
2512          */
2513         public static function updateSslPolicy(array $contact, $new_policy)
2514         {
2515                 $ssl_changed = false;
2516                 if ((intval($new_policy) == BaseURL::SSL_POLICY_SELFSIGN || $new_policy === 'self') && strstr($contact['url'], 'https:')) {
2517                         $ssl_changed = true;
2518                         $contact['url']     =   str_replace('https:', 'http:', $contact['url']);
2519                         $contact['request'] =   str_replace('https:', 'http:', $contact['request']);
2520                         $contact['notify']  =   str_replace('https:', 'http:', $contact['notify']);
2521                         $contact['poll']    =   str_replace('https:', 'http:', $contact['poll']);
2522                         $contact['confirm'] =   str_replace('https:', 'http:', $contact['confirm']);
2523                         $contact['poco']    =   str_replace('https:', 'http:', $contact['poco']);
2524                 }
2525
2526                 if ((intval($new_policy) == BaseURL::SSL_POLICY_FULL || $new_policy === 'full') && strstr($contact['url'], 'http:')) {
2527                         $ssl_changed = true;
2528                         $contact['url']     =   str_replace('http:', 'https:', $contact['url']);
2529                         $contact['request'] =   str_replace('http:', 'https:', $contact['request']);
2530                         $contact['notify']  =   str_replace('http:', 'https:', $contact['notify']);
2531                         $contact['poll']    =   str_replace('http:', 'https:', $contact['poll']);
2532                         $contact['confirm'] =   str_replace('http:', 'https:', $contact['confirm']);
2533                         $contact['poco']    =   str_replace('http:', 'https:', $contact['poco']);
2534                 }
2535
2536                 if ($ssl_changed) {
2537                         $fields = ['url' => $contact['url'], 'request' => $contact['request'],
2538                                         'notify' => $contact['notify'], 'poll' => $contact['poll'],
2539                                         'confirm' => $contact['confirm'], 'poco' => $contact['poco']];
2540                         DBA::update('contact', $fields, ['id' => $contact['id']]);
2541                 }
2542
2543                 return $contact;
2544         }
2545
2546         /**
2547          * @param array  $importer Owner (local user) data
2548          * @param array  $contact  Existing owner-specific contact data we want to expand the relationship with. Optional.
2549          * @param array  $datarray An item-like array with at least the 'author-id' and 'author-url' keys for the contact. Mandatory.
2550          * @param bool   $sharing  True: Contact is now sharing with Owner; False: Contact is now following Owner (default)
2551          * @param string $note     Introduction additional message
2552          * @return bool|null True: follow request is accepted; False: relationship is rejected; Null: relationship is pending
2553          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2554          * @throws \ImagickException
2555          */
2556         public static function addRelationship(array $importer, array $contact, array $datarray, $sharing = false, $note = '')
2557         {
2558                 // Should always be set
2559                 if (empty($datarray['author-id'])) {
2560                         return false;
2561                 }
2562
2563                 $fields = ['url', 'name', 'nick', 'avatar', 'photo', 'network', 'blocked'];
2564                 $pub_contact = DBA::selectFirst('contact', $fields, ['id' => $datarray['author-id']]);
2565                 if (!DBA::isResult($pub_contact)) {
2566                         // Should never happen
2567                         return false;
2568                 }
2569
2570                 // Contact is blocked at node-level
2571                 if (self::isBlocked($datarray['author-id'])) {
2572                         return false;
2573                 }
2574
2575                 $url = ($datarray['author-link'] ?? '') ?: $pub_contact['url'];
2576                 $name = $pub_contact['name'];
2577                 $photo = ($pub_contact['avatar'] ?? '') ?: $pub_contact["photo"];
2578                 $nick = $pub_contact['nick'];
2579                 $network = $pub_contact['network'];
2580
2581                 // Ensure that we don't create a new contact when there already is one
2582                 $cid = self::getIdForURL($url, $importer['uid']);
2583                 if (!empty($cid)) {
2584                         $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
2585                 }
2586
2587                 if (!empty($contact)) {
2588                         if (!empty($contact['pending'])) {
2589                                 Logger::info('Pending contact request already exists.', ['url' => $url, 'uid' => $importer['uid']]);
2590                                 return null;
2591                         }
2592
2593                         // Contact is blocked at user-level
2594                         if (!empty($contact['id']) && !empty($importer['id']) &&
2595                                 self::isBlockedByUser($contact['id'], $importer['id'])) {
2596                                 return false;
2597                         }
2598
2599                         // Make sure that the existing contact isn't archived
2600                         self::unmarkForArchival($contact);
2601
2602                         if (($contact['rel'] == self::SHARING)
2603                                 || ($sharing && $contact['rel'] == self::FOLLOWER)) {
2604                                 DBA::update('contact', ['rel' => self::FRIEND, 'writable' => true, 'pending' => false],
2605                                                 ['id' => $contact['id'], 'uid' => $importer['uid']]);
2606                         }
2607
2608                         // Ensure to always have the correct network type, independent from the connection request method
2609                         self::updateFromProbe($contact['id'], '', true);
2610
2611                         return true;
2612                 } else {
2613                         // send email notification to owner?
2614                         if (DBA::exists('contact', ['nurl' => Strings::normaliseLink($url), 'uid' => $importer['uid'], 'pending' => true])) {
2615                                 Logger::log('ignoring duplicated connection request from pending contact ' . $url);
2616                                 return null;
2617                         }
2618
2619                         // create contact record
2620                         DBA::insert('contact', [
2621                                 'uid'      => $importer['uid'],
2622                                 'created'  => DateTimeFormat::utcNow(),
2623                                 'url'      => $url,
2624                                 'nurl'     => Strings::normaliseLink($url),
2625                                 'name'     => $name,
2626                                 'nick'     => $nick,
2627                                 'photo'    => $photo,
2628                                 'network'  => $network,
2629                                 'rel'      => self::FOLLOWER,
2630                                 'blocked'  => 0,
2631                                 'readonly' => 0,
2632                                 'pending'  => 1,
2633                                 'writable' => 1,
2634                         ]);
2635
2636                         $contact_id = DBA::lastInsertId();
2637
2638                         // Ensure to always have the correct network type, independent from the connection request method
2639                         self::updateFromProbe($contact_id, '', true);
2640
2641                         Contact::updateAvatar($photo, $importer["uid"], $contact_id, true);
2642
2643                         $contact_record = DBA::selectFirst('contact', ['id', 'network', 'name', 'url', 'photo'], ['id' => $contact_id]);
2644
2645                         /// @TODO Encapsulate this into a function/method
2646                         $fields = ['uid', 'username', 'email', 'page-flags', 'notify-flags', 'language'];
2647                         $user = DBA::selectFirst('user', $fields, ['uid' => $importer['uid']]);
2648                         if (DBA::isResult($user) && !in_array($user['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_FREELOVE, User::PAGE_FLAGS_COMMUNITY])) {
2649                                 // create notification
2650                                 $hash = Strings::getRandomHex();
2651
2652                                 if (is_array($contact_record)) {
2653                                         DBA::insert('intro', ['uid' => $importer['uid'], 'contact-id' => $contact_record['id'],
2654                                                                 'blocked' => false, 'knowyou' => false, 'note' => $note,
2655                                                                 'hash' => $hash, 'datetime' => DateTimeFormat::utcNow()]);
2656                                 }
2657
2658                                 Group::addMember(User::getDefaultGroup($importer['uid'], $contact_record["network"]), $contact_record['id']);
2659
2660                                 if (($user['notify-flags'] & Type::INTRO) &&
2661                                         in_array($user['page-flags'], [User::PAGE_FLAGS_NORMAL])) {
2662
2663                                         notification([
2664                                                 'type'         => Type::INTRO,
2665                                                 'notify_flags' => $user['notify-flags'],
2666                                                 'language'     => $user['language'],
2667                                                 'to_name'      => $user['username'],
2668                                                 'to_email'     => $user['email'],
2669                                                 'uid'          => $user['uid'],
2670                                                 'link'         => DI::baseUrl() . '/notifications/intros',
2671                                                 'source_name'  => ((strlen(stripslashes($contact_record['name']))) ? stripslashes($contact_record['name']) : DI::l10n()->t('[Name Withheld]')),
2672                                                 'source_link'  => $contact_record['url'],
2673                                                 'source_photo' => $contact_record['photo'],
2674                                                 'verb'         => ($sharing ? Activity::FRIEND : Activity::FOLLOW),
2675                                                 'otype'        => 'intro'
2676                                         ]);
2677                                 }
2678                         } elseif (DBA::isResult($user) && in_array($user['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_FREELOVE, User::PAGE_FLAGS_COMMUNITY])) {
2679                                 $condition = ['uid' => $importer['uid'], 'url' => $url, 'pending' => true];
2680                                 DBA::update('contact', ['pending' => false], $condition);
2681
2682                                 return true;
2683                         }
2684                 }
2685
2686                 return null;
2687         }
2688
2689         public static function removeFollower($importer, $contact, array $datarray = [], $item = "")
2690         {
2691                 if (($contact['rel'] == self::FRIEND) || ($contact['rel'] == self::SHARING)) {
2692                         DBA::update('contact', ['rel' => self::SHARING], ['id' => $contact['id']]);
2693                 } else {
2694                         Contact::remove($contact['id']);
2695                 }
2696         }
2697
2698         public static function removeSharer($importer, $contact, array $datarray = [], $item = "")
2699         {
2700                 if (($contact['rel'] == self::FRIEND) || ($contact['rel'] == self::FOLLOWER)) {
2701                         DBA::update('contact', ['rel' => self::FOLLOWER], ['id' => $contact['id']]);
2702                 } else {
2703                         Contact::remove($contact['id']);
2704                 }
2705         }
2706
2707         /**
2708          * Create a birthday event.
2709          *
2710          * Update the year and the birthday.
2711          */
2712         public static function updateBirthdays()
2713         {
2714                 $condition = [
2715                         '`bd` != ""
2716                         AND `bd` > "0001-01-01"
2717                         AND SUBSTRING(`bd`, 1, 4) != `bdyear`
2718                         AND (`contact`.`rel` = ? OR `contact`.`rel` = ?)
2719                         AND NOT `contact`.`pending`
2720                         AND NOT `contact`.`hidden`
2721                         AND NOT `contact`.`blocked`
2722                         AND NOT `contact`.`archive`
2723                         AND NOT `contact`.`deleted`',
2724                         Contact::SHARING,
2725                         Contact::FRIEND
2726                 ];
2727
2728                 $contacts = DBA::select('contact', ['id', 'uid', 'name', 'url', 'bd'], $condition);
2729
2730                 while ($contact = DBA::fetch($contacts)) {
2731                         Logger::log('update_contact_birthday: ' . $contact['bd']);
2732
2733                         $nextbd = DateTimeFormat::utcNow('Y') . substr($contact['bd'], 4);
2734
2735                         if (Event::createBirthday($contact, $nextbd)) {
2736                                 // update bdyear
2737                                 DBA::update(
2738                                         'contact',
2739                                         ['bdyear' => substr($nextbd, 0, 4), 'bd' => $nextbd],
2740                                         ['id' => $contact['id']]
2741                                 );
2742                         }
2743                 }
2744         }
2745
2746         /**
2747          * Remove the unavailable contact ids from the provided list
2748          *
2749          * @param array $contact_ids Contact id list
2750          * @return array
2751          * @throws \Exception
2752          */
2753         public static function pruneUnavailable(array $contact_ids)
2754         {
2755                 if (empty($contact_ids)) {
2756                         return [];
2757                 }
2758
2759                 $contacts = Contact::selectToArray(['id'], [
2760                         'id'      => $contact_ids,
2761                         'blocked' => false,
2762                         'pending' => false,
2763                         'archive' => false,
2764                 ]);
2765
2766                 return array_column($contacts, 'id');
2767         }
2768
2769         /**
2770          * Returns a magic link to authenticate remote visitors
2771          *
2772          * @todo  check if the return is either a fully qualified URL or a relative path to Friendica basedir
2773          *
2774          * @param string $contact_url The address of the target contact profile
2775          * @param string $url         An url that we will be redirected to after the authentication
2776          *
2777          * @return string with "redir" link
2778          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2779          * @throws \ImagickException
2780          */
2781         public static function magicLink($contact_url, $url = '')
2782         {
2783                 if (!Session::isAuthenticated()) {
2784                         return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
2785                 }
2786
2787                 $data = self::getProbeDataFromDatabase($contact_url);
2788                 if (empty($data)) {
2789                         return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
2790                 }
2791
2792                 // Prevents endless loop in case only a non-public contact exists for the contact URL
2793                 unset($data['uid']);
2794
2795                 return self::magicLinkByContact($data, $url ?: $contact_url);
2796         }
2797
2798         /**
2799          * Returns a magic link to authenticate remote visitors
2800          *
2801          * @param integer $cid The contact id of the target contact profile
2802          * @param string  $url An url that we will be redirected to after the authentication
2803          *
2804          * @return string with "redir" link
2805          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2806          * @throws \ImagickException
2807          */
2808         public static function magicLinkbyId($cid, $url = '')
2809         {
2810                 $contact = DBA::selectFirst('contact', ['id', 'network', 'url', 'uid'], ['id' => $cid]);
2811
2812                 return self::magicLinkByContact($contact, $url);
2813         }
2814
2815         /**
2816          * Returns a magic link to authenticate remote visitors
2817          *
2818          * @param array  $contact The contact array with "uid", "network" and "url"
2819          * @param string $url     An url that we will be redirected to after the authentication
2820          *
2821          * @return string with "redir" link
2822          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2823          * @throws \ImagickException
2824          */
2825         public static function magicLinkByContact($contact, $url = '')
2826         {
2827                 $destination = $url ?: $contact['url']; // Equivalent to ($url != '') ? $url : $contact['url'];
2828
2829                 if (!Session::isAuthenticated() || ($contact['network'] != Protocol::DFRN)) {
2830                         return $destination;
2831                 }
2832
2833                 // Only redirections to the same host do make sense
2834                 if (($url != '') && (parse_url($url, PHP_URL_HOST) != parse_url($contact['url'], PHP_URL_HOST))) {
2835                         return $url;
2836                 }
2837
2838                 if (!empty($contact['uid'])) {
2839                         return self::magicLink($contact['url'], $url);
2840                 }
2841
2842                 if (empty($contact['id'])) {
2843                         return $destination;
2844                 }
2845
2846                 $redirect = 'redir/' . $contact['id'];
2847
2848                 if (($url != '') && !Strings::compareLink($contact['url'], $url)) {
2849                         $redirect .= '?url=' . $url;
2850                 }
2851
2852                 return $redirect;
2853         }
2854
2855         /**
2856          * Remove a contact from all groups
2857          *
2858          * @param integer $contact_id
2859          *
2860          * @return boolean Success
2861          */
2862         public static function removeFromGroups($contact_id)
2863         {
2864                 return DBA::delete('group_member', ['contact-id' => $contact_id]);
2865         }
2866
2867         /**
2868          * Is the contact a forum?
2869          *
2870          * @param integer $contactid ID of the contact
2871          *
2872          * @return boolean "true" if it is a forum
2873          */
2874         public static function isForum($contactid)
2875         {
2876                 $fields = ['forum', 'prv'];
2877                 $condition = ['id' => $contactid];
2878                 $contact = DBA::selectFirst('contact', $fields, $condition);
2879                 if (!DBA::isResult($contact)) {
2880                         return false;
2881                 }
2882
2883                 // Is it a forum?
2884                 return ($contact['forum'] || $contact['prv']);
2885         }
2886
2887         /**
2888          * Can the remote contact receive private messages?
2889          *
2890          * @param array $contact
2891          * @return bool
2892          */
2893         public static function canReceivePrivateMessages(array $contact)
2894         {
2895                 $protocol = $contact['network'] ?? $contact['protocol'] ?? Protocol::PHANTOM;
2896                 $self = $contact['self'] ?? false;
2897
2898                 return in_array($protocol, [Protocol::DFRN, Protocol::DIASPORA, Protocol::ACTIVITYPUB]) && !$self;
2899         }
2900 }