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