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