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