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