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