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