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