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