]> git.mxchange.org Git - friendica.git/blob - src/Model/Contact.php
Fixed count, added to-do
[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($cid)
1568         {
1569                 if ($cid == 0) {
1570                         return false;
1571                 }
1572
1573                 $archived = DBA::selectFirst('contact', ['archive', 'url'], ['id' => $cid]);
1574                 if (!DBA::isResult($archived)) {
1575                         return false;
1576                 }
1577
1578                 if ($archived['archive']) {
1579                         return true;
1580                 }
1581
1582                 $apcontact = APContact::getByURL($archived['url'], false);
1583                 if (empty($apcontact)) {
1584                         return false;
1585                 }
1586
1587                 if (!empty($apcontact['inbox']) && DBA::exists('inbox-status', ['archive' => true, 'url' => $apcontact['inbox']])) {
1588                         return true;
1589                 }
1590
1591                 if (!empty($apcontact['sharedinbox']) && DBA::exists('inbox-status', ['archive' => true, 'url' => $apcontact['sharedinbox']])) {
1592                         return true;
1593                 }
1594
1595                 /// @todo Add tests for Diaspora endpoints as well
1596                 return false;
1597         }
1598
1599         /**
1600          * @brief Checks if the contact is blocked
1601          *
1602          * @param int $cid contact id
1603          *
1604          * @return boolean Is the contact blocked?
1605          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1606          */
1607         public static function isBlocked($cid)
1608         {
1609                 if ($cid == 0) {
1610                         return false;
1611                 }
1612
1613                 $blocked = DBA::selectFirst('contact', ['blocked', 'url'], ['id' => $cid]);
1614                 if (!DBA::isResult($blocked)) {
1615                         return false;
1616                 }
1617
1618                 if (Network::isUrlBlocked($blocked['url'])) {
1619                         return true;
1620                 }
1621
1622                 return (bool) $blocked['blocked'];
1623         }
1624
1625         /**
1626          * @brief Checks if the contact is hidden
1627          *
1628          * @param int $cid contact id
1629          *
1630          * @return boolean Is the contact hidden?
1631          * @throws \Exception
1632          */
1633         public static function isHidden($cid)
1634         {
1635                 if ($cid == 0) {
1636                         return false;
1637                 }
1638
1639                 $hidden = DBA::selectFirst('contact', ['hidden'], ['id' => $cid]);
1640                 if (!DBA::isResult($hidden)) {
1641                         return false;
1642                 }
1643                 return (bool) $hidden['hidden'];
1644         }
1645
1646         /**
1647          * @brief Returns posts from a given contact url
1648          *
1649          * @param string $contact_url Contact URL
1650          *
1651          * @param bool   $thread_mode
1652          * @param int    $update
1653          * @return string posts in HTML
1654          * @throws \Exception
1655          */
1656         public static function getPostsFromUrl($contact_url, $thread_mode = false, $update = 0)
1657         {
1658                 $a = self::getApp();
1659
1660                 $cid = self::getIdForURL($contact_url);
1661
1662                 $contact = DBA::selectFirst('contact', ['contact-type', 'network'], ['id' => $cid]);
1663                 if (!DBA::isResult($contact)) {
1664                         return '';
1665                 }
1666
1667                 if (empty($contact["network"]) || in_array($contact["network"], Protocol::FEDERATED)) {
1668                         $sql = "(`item`.`uid` = 0 OR (`item`.`uid` = ? AND NOT `item`.`global`))";
1669                 } else {
1670                         $sql = "`item`.`uid` = ?";
1671                 }
1672
1673                 $contact_field = ($contact["contact-type"] == self::TYPE_COMMUNITY ? 'owner-id' : 'author-id');
1674
1675                 if ($thread_mode) {
1676                         $condition = ["`$contact_field` = ? AND `gravity` = ? AND " . $sql,
1677                                 $cid, GRAVITY_PARENT, local_user()];
1678                 } else {
1679                         $condition = ["`$contact_field` = ? AND `gravity` IN (?, ?) AND " . $sql,
1680                                 $cid, GRAVITY_PARENT, GRAVITY_COMMENT, local_user()];
1681                 }
1682
1683                 $pager = new Pager($a->query_string);
1684
1685                 $params = ['order' => ['received' => true],
1686                         'limit' => [$pager->getStart(), $pager->getItemsPerPage()]];
1687
1688                 if ($thread_mode) {
1689                         $r = Item::selectThreadForUser(local_user(), ['uri'], $condition, $params);
1690
1691                         $items = Item::inArray($r);
1692
1693                         $o = conversation($a, $items, $pager, 'contacts', $update, false, 'commented', local_user());
1694                 } else {
1695                         $r = Item::selectForUser(local_user(), [], $condition, $params);
1696
1697                         $items = Item::inArray($r);
1698
1699                         $o = conversation($a, $items, $pager, 'contact-posts', false);
1700                 }
1701
1702                 if (!$update) {
1703                         $o .= $pager->renderMinimal(count($items));
1704                 }
1705
1706                 return $o;
1707         }
1708
1709         /**
1710          * @brief Returns the account type name
1711          *
1712          * The function can be called with either the user or the contact array
1713          *
1714          * @param array $contact contact or user array
1715          * @return string
1716          */
1717         public static function getAccountType(array $contact)
1718         {
1719                 // There are several fields that indicate that the contact or user is a forum
1720                 // "page-flags" is a field in the user table,
1721                 // "forum" and "prv" are used in the contact table. They stand for User::PAGE_FLAGS_COMMUNITY and User::PAGE_FLAGS_PRVGROUP.
1722                 // "community" is used in the gcontact table and is true if the contact is User::PAGE_FLAGS_COMMUNITY or User::PAGE_FLAGS_PRVGROUP.
1723                 if ((isset($contact['page-flags']) && (intval($contact['page-flags']) == User::PAGE_FLAGS_COMMUNITY))
1724                         || (isset($contact['page-flags']) && (intval($contact['page-flags']) == User::PAGE_FLAGS_PRVGROUP))
1725                         || (isset($contact['forum']) && intval($contact['forum']))
1726                         || (isset($contact['prv']) && intval($contact['prv']))
1727                         || (isset($contact['community']) && intval($contact['community']))
1728                 ) {
1729                         $type = self::TYPE_COMMUNITY;
1730                 } else {
1731                         $type = self::TYPE_PERSON;
1732                 }
1733
1734                 // The "contact-type" (contact table) and "account-type" (user table) are more general then the chaos from above.
1735                 if (isset($contact["contact-type"])) {
1736                         $type = $contact["contact-type"];
1737                 }
1738
1739                 if (isset($contact["account-type"])) {
1740                         $type = $contact["account-type"];
1741                 }
1742
1743                 switch ($type) {
1744                         case self::TYPE_ORGANISATION:
1745                                 $account_type = L10n::t("Organisation");
1746                                 break;
1747
1748                         case self::TYPE_NEWS:
1749                                 $account_type = L10n::t('News');
1750                                 break;
1751
1752                         case self::TYPE_COMMUNITY:
1753                                 $account_type = L10n::t("Forum");
1754                                 break;
1755
1756                         default:
1757                                 $account_type = "";
1758                                 break;
1759                 }
1760
1761                 return $account_type;
1762         }
1763
1764         /**
1765          * @brief Blocks a contact
1766          *
1767          * @param int $cid
1768          * @return bool
1769          * @throws \Exception
1770          */
1771         public static function block($cid, $reason = null)
1772         {
1773                 $return = DBA::update('contact', ['blocked' => true, 'block_reason' => $reason], ['id' => $cid]);
1774
1775                 return $return;
1776         }
1777
1778         /**
1779          * @brief Unblocks a contact
1780          *
1781          * @param int $cid
1782          * @return bool
1783          * @throws \Exception
1784          */
1785         public static function unblock($cid)
1786         {
1787                 $return = DBA::update('contact', ['blocked' => false, 'block_reason' => null], ['id' => $cid]);
1788
1789                 return $return;
1790         }
1791
1792         /**
1793          * @brief Updates the avatar links in a contact only if needed
1794          *
1795          * @param string $avatar Link to avatar picture
1796          * @param int    $uid    User id of contact owner
1797          * @param int    $cid    Contact id
1798          * @param bool   $force  force picture update
1799          *
1800          * @return array Returns array of the different avatar sizes
1801          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1802          * @throws \ImagickException
1803          */
1804         public static function updateAvatar($avatar, $uid, $cid, $force = false)
1805         {
1806                 $contact = DBA::selectFirst('contact', ['avatar', 'photo', 'thumb', 'micro', 'nurl'], ['id' => $cid, 'self' => false]);
1807                 if (!DBA::isResult($contact)) {
1808                         return false;
1809                 } else {
1810                         $data = [$contact["photo"], $contact["thumb"], $contact["micro"]];
1811                 }
1812
1813                 if (($contact["avatar"] != $avatar) || $force) {
1814                         $photos = Photo::importProfilePhoto($avatar, $uid, $cid, true);
1815
1816                         if ($photos) {
1817                                 $fields = ['avatar' => $avatar, 'photo' => $photos[0], 'thumb' => $photos[1], 'micro' => $photos[2], 'avatar-date' => DateTimeFormat::utcNow()];
1818                                 DBA::update('contact', $fields, ['id' => $cid]);
1819
1820                                 // Update the public contact (contact id = 0)
1821                                 if ($uid != 0) {
1822                                         $pcontact = DBA::selectFirst('contact', ['id'], ['nurl' => $contact['nurl'], 'uid' => 0]);
1823                                         if (DBA::isResult($pcontact)) {
1824                                                 DBA::update('contact', $fields, ['id' => $pcontact['id']]);
1825                                         }
1826                                 }
1827
1828                                 return $photos;
1829                         }
1830                 }
1831
1832                 return $data;
1833         }
1834
1835         /**
1836          * @brief Helper function for "updateFromProbe". Updates personal and public contact
1837          *
1838          * @param array $contact The personal contact entry
1839          * @param array $fields  The fields that are updated
1840          * @throws \Exception
1841          */
1842         private static function updateContact($id, $uid, $url, array $fields)
1843         {
1844                 DBA::update('contact', $fields, ['id' => $id]);
1845
1846                 // Search for duplicated contacts and get rid of them
1847                 if (self::handleDuplicates(Strings::normaliseLink($url), $uid, $id) || ($uid != 0)) {
1848                         return;
1849                 }
1850
1851                 // Update the corresponding gcontact entry
1852                 GContact::updateFromPublicContactID($id);
1853
1854                 // Archive or unarchive the contact. We only need to do this for the public contact.
1855                 // The archive/unarchive function will update the personal contacts by themselves.
1856                 $contact = DBA::selectFirst('contact', [], ['id' => $id]);
1857                 if (!empty($fields['success_update'])) {
1858                         self::unmarkForArchival($contact);
1859                 } elseif (!empty($fields['failure_update'])) {
1860                         self::markForArchival($contact);
1861                 }
1862
1863                 $condition = ['self' => false, 'nurl' => Strings::normaliseLink($url), 'network' => Protocol::FEDERATED];
1864
1865                 // These contacts are sharing with us, we don't poll them.
1866                 // This means that we don't set the update fields in "OnePoll.php".
1867                 $condition['rel'] = self::SHARING;
1868                 DBA::update('contact', $fields, $condition);
1869
1870                 unset($fields['last-update']);
1871                 unset($fields['success_update']);
1872                 unset($fields['failure_update']);
1873
1874                 if (empty($fields)) {
1875                         return;
1876                 }
1877
1878                 // We are polling these contacts, so we mustn't set the update fields here.
1879                 $condition['rel'] = [self::FOLLOWER, self::FRIEND];
1880                 DBA::update('contact', $fields, $condition);
1881         }
1882
1883         /**
1884          * @brief Helper function for "updateFromProbe". Remove duplicated contacts
1885          *
1886          * @param string  $nurl  Normalised contact url
1887          * @param integer $uid   User id
1888          * @param integer $id    Contact id of a duplicate
1889          * @return boolean
1890          * @throws \Exception
1891          */
1892         private static function handleDuplicates($nurl, $uid, $id)
1893         {
1894                 $condition = ['nurl' => $nurl, 'uid' => $uid, 'deleted' => false, 'network' => Protocol::FEDERATED];
1895                 $count = DBA::count('contact', $condition);
1896                 if ($count <= 1) {
1897                         return false;
1898                 }
1899
1900                 $first_contact = DBA::selectFirst('contact', ['id', 'network'], $condition, ['order' => ['id']]);
1901                 if (!DBA::isResult($first_contact)) {
1902                         // Shouldn't happen - so we handle it
1903                         return false;
1904                 }
1905
1906                 $first = $first_contact['id'];
1907                 Logger::info('Found duplicates', ['count' => $count, 'id' => $id, 'first' => $first, 'uid' => $uid, 'nurl' => $nurl]);
1908                 if (($uid != 0 && ($first_contact['network'] == Protocol::DFRN))) {
1909                         // Don't handle non public DFRN duplicates by now (legacy DFRN is very special because of the key handling)
1910                         Logger::info('Not handling non public DFRN duplicate', ['uid' => $uid, 'nurl' => $nurl]);
1911                         return false;
1912                 }
1913
1914                 // Find all duplicates
1915                 $condition = ["`nurl` = ? AND `uid` = ? AND `id` != ? AND NOT `self` AND NOT `deleted`", $nurl, $uid, $first];
1916                 $duplicates = DBA::select('contact', ['id', 'network'], $condition);
1917                 while ($duplicate = DBA::fetch($duplicates)) {
1918                         if (!in_array($duplicate['network'], Protocol::FEDERATED)) {
1919                                 continue;
1920                         }
1921
1922                         Worker::add(PRIORITY_HIGH, 'MergeContact', $first, $duplicate['id'], $uid);
1923                 }
1924                 Logger::info('Duplicates handled', ['uid' => $uid, 'nurl' => $nurl]);
1925                 return true;
1926         }
1927
1928         /**
1929          * @param integer $id      contact id
1930          * @param string  $network Optional network we are probing for
1931          * @param boolean $force   Optional forcing of network probing (otherwise we use the cached data)
1932          * @return boolean
1933          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1934          * @throws \ImagickException
1935          */
1936         public static function updateFromProbe($id, $network = '', $force = false)
1937         {
1938                 /*
1939                   Warning: Never ever fetch the public key via Probe::uri and write it into the contacts.
1940                   This will reliably kill your communication with old Friendica contacts.
1941                  */
1942
1943                 // These fields aren't updated by this routine:
1944                 // 'xmpp', 'sensitive'
1945
1946                 $fields = ['uid', 'avatar', 'name', 'nick', 'location', 'keywords', 'about', 'gender',
1947                         'unsearchable', 'url', 'addr', 'batch', 'notify', 'poll', 'request', 'confirm', 'poco',
1948                         'network', 'alias', 'baseurl', 'forum', 'prv', 'contact-type', 'pubkey'];
1949                 $contact = DBA::selectFirst('contact', $fields, ['id' => $id]);
1950                 if (!DBA::isResult($contact)) {
1951                         return false;
1952                 }
1953
1954                 $uid = $contact['uid'];
1955                 unset($contact['uid']);
1956
1957                 $pubkey = $contact['pubkey'];
1958                 unset($contact['pubkey']);
1959
1960                 $contact['photo'] = $contact['avatar'];
1961                 unset($contact['avatar']);
1962
1963                 $ret = Probe::uri($contact['url'], $network, $uid, !$force);
1964
1965                 $updated = DateTimeFormat::utcNow();
1966
1967                 // We must not try to update relay contacts via probe. They are no real contacts.
1968                 // We check after the probing to be able to correct falsely detected contact types.
1969                 if (($contact['contact-type'] == self::TYPE_RELAY) &&
1970                         (!Strings::compareLink($ret['url'], $contact['url']) || in_array($ret['network'], [Protocol::FEED, Protocol::PHANTOM]))) {
1971                         self::updateContact($id, $uid, $contact['url'], ['last-update' => $updated, 'success_update' => $updated]);
1972                         Logger::info('Not updating relais', ['id' => $id, 'url' => $contact['url']]);
1973                         return true;
1974                 }
1975
1976                 // If Probe::uri fails the network code will be different (mostly "feed" or "unkn")
1977                 if (!in_array($ret['network'], Protocol::NATIVE_SUPPORT) ||
1978                         (in_array($ret['network'], [Protocol::FEED, Protocol::PHANTOM]) && ($ret['network'] != $contact['network']))) {
1979                         if ($force && ($uid == 0)) {
1980                                 self::updateContact($id, $uid, $ret['url'], ['last-update' => $updated, 'failure_update' => $updated]);
1981                         }
1982                         return false;
1983                 }
1984
1985                 if (isset($ret['hide']) && is_bool($ret['hide'])) {
1986                         $ret['unsearchable'] = $ret['hide'];
1987                 }
1988
1989                 if (isset($ret['account-type']) && is_int($ret['account-type'])) {
1990                         $ret['forum'] = false;
1991                         $ret['prv'] = false;
1992                         $ret['contact-type'] = $ret['account-type'];
1993                         if ($ret['contact-type'] == User::ACCOUNT_TYPE_COMMUNITY) {
1994                                 $apcontact = APContact::getByURL($ret['url'], false);
1995                                 if (isset($apcontact['manually-approve'])) {
1996                                         $ret['forum'] = (bool)!$apcontact['manually-approve'];
1997                                         $ret['prv'] = (bool)!$ret['forum'];
1998                                 }
1999                         }
2000                 }
2001
2002                 $new_pubkey = $ret['pubkey'];
2003
2004                 $update = false;
2005
2006                 // make sure to not overwrite existing values with blank entries except some technical fields
2007                 $keep = ['batch', 'notify', 'poll', 'request', 'confirm', 'poco', 'baseurl'];
2008                 foreach ($ret as $key => $val) {
2009                         if (!array_key_exists($key, $contact)) {
2010                                 unset($ret[$key]);
2011                         } elseif (($contact[$key] != '') && ($val === '') && !is_bool($ret[$key]) && !in_array($key, $keep)) {
2012                                 $ret[$key] = $contact[$key];
2013                         } elseif ($ret[$key] != $contact[$key]) {
2014                                 $update = true;
2015                         }
2016                 }
2017
2018                 if ($ret['network'] != Protocol::FEED) {
2019                         self::updateAvatar($ret['photo'], $uid, $id, $update || $force);
2020                 }
2021
2022                 if (!$update) {
2023                         if ($force) {
2024                                 self::updateContact($id, $uid, $ret['url'], ['last-update' => $updated, 'success_update' => $updated]);
2025                         }
2026                         return true;
2027                 }
2028
2029                 $ret['nurl'] = Strings::normaliseLink($ret['url']);
2030                 $ret['updated'] = $updated;
2031
2032                 // Only fill the pubkey if it had been empty before. We have to prevent identity theft.
2033                 if (empty($pubkey) && !empty($new_pubkey)) {
2034                         $ret['pubkey'] = $new_pubkey;
2035                 }
2036
2037                 if (($ret['addr'] != $contact['addr']) || (!empty($ret['alias']) && ($ret['alias'] != $contact['alias']))) {
2038                         $ret['uri-date'] = DateTimeFormat::utcNow();
2039                 }
2040
2041                 if (($ret['name'] != $contact['name']) || ($ret['nick'] != $contact['nick'])) {
2042                         $ret['name-date'] = $updated;
2043                 }
2044
2045                 if ($force && ($uid == 0)) {
2046                         $ret['last-update'] = $updated;
2047                         $ret['success_update'] = $updated;
2048                 }
2049
2050                 unset($ret['photo']);
2051
2052                 self::updateContact($id, $uid, $ret['url'], $ret);
2053
2054                 return true;
2055         }
2056
2057         public static function updateFromProbeByURL($url, $force = false)
2058         {
2059                 $id = self::getIdForURL($url);
2060
2061                 if (empty($id)) {
2062                         return $id;
2063                 }
2064
2065                 self::updateFromProbe($id, '', $force);
2066
2067                 return $id;
2068         }
2069
2070         /**
2071          * Detects if a given contact array belongs to a legacy DFRN connection
2072          *
2073          * @param array $contact
2074          * @return boolean
2075          */
2076         public static function isLegacyDFRNContact($contact)
2077         {
2078                 // Newer Friendica contacts are connected via AP, then these fields aren't set
2079                 return !empty($contact['dfrn-id']) || !empty($contact['issued-id']);
2080         }
2081
2082         /**
2083          * Detects the communication protocol for a given contact url.
2084          * This is used to detect Friendica contacts that we can communicate via AP.
2085          *
2086          * @param string $url contact url
2087          * @param string $network Network of that contact
2088          * @return string with protocol
2089          */
2090         public static function getProtocol($url, $network)
2091         {
2092                 if ($network != Protocol::DFRN) {
2093                         return $network;
2094                 }
2095
2096                 $apcontact = APContact::getByURL($url);
2097                 if (!empty($apcontact) && !empty($apcontact['generator'])) {
2098                         return Protocol::ACTIVITYPUB;
2099                 } else {
2100                         return $network;
2101                 }
2102         }
2103
2104         /**
2105          * Takes a $uid and a url/handle and adds a new contact
2106          * Currently if the contact is DFRN, interactive needs to be true, to redirect to the
2107          * dfrn_request page.
2108          *
2109          * Otherwise this can be used to bulk add StatusNet contacts, Twitter contacts, etc.
2110          *
2111          * Returns an array
2112          * $return['success'] boolean true if successful
2113          * $return['message'] error text if success is false.
2114          *
2115          * @brief Takes a $uid and a url/handle and adds a new contact
2116          * @param int    $uid
2117          * @param string $url
2118          * @param bool   $interactive
2119          * @param string $network
2120          * @return array
2121          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2122          * @throws \ImagickException
2123          */
2124         public static function createFromProbe($uid, $url, $interactive = false, $network = '')
2125         {
2126                 $result = ['cid' => -1, 'success' => false, 'message' => ''];
2127
2128                 $a = \get_app();
2129
2130                 // remove ajax junk, e.g. Twitter
2131                 $url = str_replace('/#!/', '/', $url);
2132
2133                 if (!Network::isUrlAllowed($url)) {
2134                         $result['message'] = L10n::t('Disallowed profile URL.');
2135                         return $result;
2136                 }
2137
2138                 if (Network::isUrlBlocked($url)) {
2139                         $result['message'] = L10n::t('Blocked domain');
2140                         return $result;
2141                 }
2142
2143                 if (!$url) {
2144                         $result['message'] = L10n::t('Connect URL missing.');
2145                         return $result;
2146                 }
2147
2148                 $arr = ['url' => $url, 'contact' => []];
2149
2150                 Hook::callAll('follow', $arr);
2151
2152                 if (empty($arr)) {
2153                         $result['message'] = L10n::t('The contact could not be added. Please check the relevant network credentials in your Settings -> Social Networks page.');
2154                         return $result;
2155                 }
2156
2157                 if (!empty($arr['contact']['name'])) {
2158                         $ret = $arr['contact'];
2159                 } else {
2160                         $ret = Probe::uri($url, $network, $uid, false);
2161                 }
2162
2163                 if (($network != '') && ($ret['network'] != $network)) {
2164                         Logger::log('Expected network ' . $network . ' does not match actual network ' . $ret['network']);
2165                         return $result;
2166                 }
2167
2168                 // check if we already have a contact
2169                 // the poll url is more reliable than the profile url, as we may have
2170                 // indirect links or webfinger links
2171
2172                 $condition = ['uid' => $uid, 'poll' => [$ret['poll'], Strings::normaliseLink($ret['poll'])], 'network' => $ret['network'], 'pending' => false];
2173                 $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
2174                 if (!DBA::isResult($contact)) {
2175                         $condition = ['uid' => $uid, 'nurl' => Strings::normaliseLink($url), 'network' => $ret['network'], 'pending' => false];
2176                         $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
2177                 }
2178
2179                 $protocol = self::getProtocol($url, $ret['network']);
2180
2181                 if (($protocol === Protocol::DFRN) && !DBA::isResult($contact)) {
2182                         if ($interactive) {
2183                                 if (strlen($a->getURLPath())) {
2184                                         $myaddr = bin2hex(System::baseUrl() . '/profile/' . $a->user['nickname']);
2185                                 } else {
2186                                         $myaddr = bin2hex($a->user['nickname'] . '@' . $a->getHostName());
2187                                 }
2188
2189                                 $a->internalRedirect($ret['request'] . "&addr=$myaddr");
2190
2191                                 // NOTREACHED
2192                         }
2193                 } elseif (Config::get('system', 'dfrn_only') && ($ret['network'] != Protocol::DFRN)) {
2194                         $result['message'] = L10n::t('This site is not configured to allow communications with other networks.') . EOL;
2195                         $result['message'] .= L10n::t('No compatible communication protocols or feeds were discovered.') . EOL;
2196                         return $result;
2197                 }
2198
2199                 // This extra param just confuses things, remove it
2200                 if ($protocol === Protocol::DIASPORA) {
2201                         $ret['url'] = str_replace('?absolute=true', '', $ret['url']);
2202                 }
2203
2204                 // do we have enough information?
2205                 if (empty($ret['name']) || empty($ret['poll']) || (empty($ret['url']) && empty($ret['addr']))) {
2206                         $result['message'] .= L10n::t('The profile address specified does not provide adequate information.') . EOL;
2207                         if (empty($ret['poll'])) {
2208                                 $result['message'] .= L10n::t('No compatible communication protocols or feeds were discovered.') . EOL;
2209                         }
2210                         if (empty($ret['name'])) {
2211                                 $result['message'] .= L10n::t('An author or name was not found.') . EOL;
2212                         }
2213                         if (empty($ret['url'])) {
2214                                 $result['message'] .= L10n::t('No browser URL could be matched to this address.') . EOL;
2215                         }
2216                         if (strpos($url, '@') !== false) {
2217                                 $result['message'] .= L10n::t('Unable to match @-style Identity Address with a known protocol or email contact.') . EOL;
2218                                 $result['message'] .= L10n::t('Use mailto: in front of address to force email check.') . EOL;
2219                         }
2220                         return $result;
2221                 }
2222
2223                 if ($protocol === Protocol::OSTATUS && Config::get('system', 'ostatus_disabled')) {
2224                         $result['message'] .= L10n::t('The profile address specified belongs to a network which has been disabled on this site.') . EOL;
2225                         $ret['notify'] = '';
2226                 }
2227
2228                 if (!$ret['notify']) {
2229                         $result['message'] .= L10n::t('Limited profile. This person will be unable to receive direct/personal notifications from you.') . EOL;
2230                 }
2231
2232                 $writeable = ((($protocol === Protocol::OSTATUS) && ($ret['notify'])) ? 1 : 0);
2233
2234                 $subhub = (($protocol === Protocol::OSTATUS) ? true : false);
2235
2236                 $hidden = (($protocol === Protocol::MAIL) ? 1 : 0);
2237
2238                 $pending = in_array($protocol, [Protocol::ACTIVITYPUB]);
2239
2240                 if (in_array($protocol, [Protocol::MAIL, Protocol::DIASPORA, Protocol::ACTIVITYPUB])) {
2241                         $writeable = 1;
2242                 }
2243
2244                 if (DBA::isResult($contact)) {
2245                         // update contact
2246                         $new_relation = (($contact['rel'] == self::FOLLOWER) ? self::FRIEND : self::SHARING);
2247
2248                         $fields = ['rel' => $new_relation, 'subhub' => $subhub, 'readonly' => false];
2249                         DBA::update('contact', $fields, ['id' => $contact['id']]);
2250                 } else {
2251                         $new_relation = (in_array($protocol, [Protocol::MAIL]) ? self::FRIEND : self::SHARING);
2252
2253                         // create contact record
2254                         DBA::insert('contact', [
2255                                 'uid'     => $uid,
2256                                 'created' => DateTimeFormat::utcNow(),
2257                                 'url'     => $ret['url'],
2258                                 'nurl'    => Strings::normaliseLink($ret['url']),
2259                                 'addr'    => $ret['addr'],
2260                                 'alias'   => $ret['alias'],
2261                                 'batch'   => $ret['batch'],
2262                                 'notify'  => $ret['notify'],
2263                                 'poll'    => $ret['poll'],
2264                                 'poco'    => $ret['poco'],
2265                                 'name'    => $ret['name'],
2266                                 'nick'    => $ret['nick'],
2267                                 'network' => $ret['network'],
2268                                 'baseurl' => $ret['baseurl'],
2269                                 'protocol' => $protocol,
2270                                 'pubkey'  => $ret['pubkey'],
2271                                 'rel'     => $new_relation,
2272                                 'priority'=> $ret['priority'],
2273                                 'writable'=> $writeable,
2274                                 'hidden'  => $hidden,
2275                                 'blocked' => 0,
2276                                 'readonly'=> 0,
2277                                 'pending' => $pending,
2278                                 'subhub'  => $subhub
2279                         ]);
2280                 }
2281
2282                 $contact = DBA::selectFirst('contact', [], ['url' => $ret['url'], 'network' => $ret['network'], 'uid' => $uid]);
2283                 if (!DBA::isResult($contact)) {
2284                         $result['message'] .= L10n::t('Unable to retrieve contact information.') . EOL;
2285                         return $result;
2286                 }
2287
2288                 $contact_id = $contact['id'];
2289                 $result['cid'] = $contact_id;
2290
2291                 Group::addMember(User::getDefaultGroup($uid, $contact["network"]), $contact_id);
2292
2293                 // Update the avatar
2294                 self::updateAvatar($ret['photo'], $uid, $contact_id);
2295
2296                 // pull feed and consume it, which should subscribe to the hub.
2297
2298                 Worker::add(PRIORITY_HIGH, "OnePoll", $contact_id, "force");
2299
2300                 $owner = User::getOwnerDataById($uid);
2301
2302                 if (DBA::isResult($owner)) {
2303                         if (in_array($protocol, [Protocol::OSTATUS, Protocol::DFRN])) {
2304                                 // create a follow slap
2305                                 $item = [];
2306                                 $item['verb'] = ACTIVITY_FOLLOW;
2307                                 $item['follow'] = $contact["url"];
2308                                 $item['body'] = '';
2309                                 $item['title'] = '';
2310                                 $item['guid'] = '';
2311                                 $item['tag'] = '';
2312                                 $item['attach'] = '';
2313
2314                                 $slap = OStatus::salmon($item, $owner);
2315
2316                                 if (!empty($contact['notify'])) {
2317                                         Salmon::slapper($owner, $contact['notify'], $slap);
2318                                 }
2319                         } elseif ($protocol == Protocol::DIASPORA) {
2320                                 $ret = Diaspora::sendShare($a->user, $contact);
2321                                 Logger::log('share returns: ' . $ret);
2322                         } elseif ($protocol == Protocol::ACTIVITYPUB) {
2323                                 $activity_id = ActivityPub\Transmitter::activityIDFromContact($contact_id);
2324                                 if (empty($activity_id)) {
2325                                         // This really should never happen
2326                                         return false;
2327                                 }
2328
2329                                 $ret = ActivityPub\Transmitter::sendActivity('Follow', $contact['url'], $uid, $activity_id);
2330                                 Logger::log('Follow returns: ' . $ret);
2331                         }
2332                 }
2333
2334                 $result['success'] = true;
2335                 return $result;
2336         }
2337
2338         /**
2339          * @brief Updated contact's SSL policy
2340          *
2341          * @param array  $contact    Contact array
2342          * @param string $new_policy New policy, valid: self,full
2343          *
2344          * @return array Contact array with updated values
2345          * @throws \Exception
2346          */
2347         public static function updateSslPolicy(array $contact, $new_policy)
2348         {
2349                 $ssl_changed = false;
2350                 if ((intval($new_policy) == BaseURL::SSL_POLICY_SELFSIGN || $new_policy === 'self') && strstr($contact['url'], 'https:')) {
2351                         $ssl_changed = true;
2352                         $contact['url']     =   str_replace('https:', 'http:', $contact['url']);
2353                         $contact['request'] =   str_replace('https:', 'http:', $contact['request']);
2354                         $contact['notify']  =   str_replace('https:', 'http:', $contact['notify']);
2355                         $contact['poll']    =   str_replace('https:', 'http:', $contact['poll']);
2356                         $contact['confirm'] =   str_replace('https:', 'http:', $contact['confirm']);
2357                         $contact['poco']    =   str_replace('https:', 'http:', $contact['poco']);
2358                 }
2359
2360                 if ((intval($new_policy) == BaseURL::SSL_POLICY_FULL || $new_policy === 'full') && strstr($contact['url'], 'http:')) {
2361                         $ssl_changed = true;
2362                         $contact['url']     =   str_replace('http:', 'https:', $contact['url']);
2363                         $contact['request'] =   str_replace('http:', 'https:', $contact['request']);
2364                         $contact['notify']  =   str_replace('http:', 'https:', $contact['notify']);
2365                         $contact['poll']    =   str_replace('http:', 'https:', $contact['poll']);
2366                         $contact['confirm'] =   str_replace('http:', 'https:', $contact['confirm']);
2367                         $contact['poco']    =   str_replace('http:', 'https:', $contact['poco']);
2368                 }
2369
2370                 if ($ssl_changed) {
2371                         $fields = ['url' => $contact['url'], 'request' => $contact['request'],
2372                                         'notify' => $contact['notify'], 'poll' => $contact['poll'],
2373                                         'confirm' => $contact['confirm'], 'poco' => $contact['poco']];
2374                         DBA::update('contact', $fields, ['id' => $contact['id']]);
2375                 }
2376
2377                 return $contact;
2378         }
2379
2380         /**
2381          * @param array  $importer Owner (local user) data
2382          * @param array  $contact  Existing owner-specific contact data we want to expand the relationship with. Optional.
2383          * @param array  $datarray An item-like array with at least the 'author-id' and 'author-url' keys for the contact. Mandatory.
2384          * @param bool   $sharing  True: Contact is now sharing with Owner; False: Contact is now following Owner (default)
2385          * @param string $note     Introduction additional message
2386          * @return bool|null True: follow request is accepted; False: relationship is rejected; Null: relationship is pending
2387          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2388          * @throws \ImagickException
2389          */
2390         public static function addRelationship(array $importer, array $contact, array $datarray, $sharing = false, $note = '')
2391         {
2392                 // Should always be set
2393                 if (empty($datarray['author-id'])) {
2394                         return false;
2395                 }
2396
2397                 $fields = ['url', 'name', 'nick', 'avatar', 'photo', 'network', 'blocked'];
2398                 $pub_contact = DBA::selectFirst('contact', $fields, ['id' => $datarray['author-id']]);
2399                 if (!DBA::isResult($pub_contact)) {
2400                         // Should never happen
2401                         return false;
2402                 }
2403
2404                 // Contact is blocked at node-level
2405                 if (self::isBlocked($datarray['author-id'])) {
2406                         return false;
2407                 }
2408
2409                 $url = defaults($datarray, 'author-link', $pub_contact['url']);
2410                 $name = $pub_contact['name'];
2411                 $photo = defaults($pub_contact, 'avatar', $pub_contact["photo"]);
2412                 $nick = $pub_contact['nick'];
2413                 $network = $pub_contact['network'];
2414
2415                 // Ensure that we don't create a new contact when there already is one
2416                 $cid = self::getIdForURL($url, $importer['uid']);
2417                 if (!empty($cid)) {
2418                         $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
2419                 }
2420
2421                 if (!empty($contact)) {
2422                         if (!empty($contact['pending'])) {
2423                                 Logger::info('Pending contact request already exists.', ['url' => $url, 'uid' => $importer['uid']]);
2424                                 return null;
2425                         }
2426
2427                         // Contact is blocked at user-level
2428                         if (!empty($contact['id']) && !empty($importer['id']) &&
2429                                 self::isBlockedByUser($contact['id'], $importer['id'])) {
2430                                 return false;
2431                         }
2432
2433                         // Make sure that the existing contact isn't archived
2434                         self::unmarkForArchival($contact);
2435
2436                         if (($contact['rel'] == self::SHARING)
2437                                 || ($sharing && $contact['rel'] == self::FOLLOWER)) {
2438                                 DBA::update('contact', ['rel' => self::FRIEND, 'writable' => true, 'pending' => false],
2439                                                 ['id' => $contact['id'], 'uid' => $importer['uid']]);
2440                         }
2441
2442                         return true;
2443                 } else {
2444                         // send email notification to owner?
2445                         if (DBA::exists('contact', ['nurl' => Strings::normaliseLink($url), 'uid' => $importer['uid'], 'pending' => true])) {
2446                                 Logger::log('ignoring duplicated connection request from pending contact ' . $url);
2447                                 return null;
2448                         }
2449
2450                         // create contact record
2451                         DBA::insert('contact', [
2452                                 'uid'      => $importer['uid'],
2453                                 'created'  => DateTimeFormat::utcNow(),
2454                                 'url'      => $url,
2455                                 'nurl'     => Strings::normaliseLink($url),
2456                                 'name'     => $name,
2457                                 'nick'     => $nick,
2458                                 'photo'    => $photo,
2459                                 'network'  => $network,
2460                                 'rel'      => self::FOLLOWER,
2461                                 'blocked'  => 0,
2462                                 'readonly' => 0,
2463                                 'pending'  => 1,
2464                                 'writable' => 1,
2465                         ]);
2466
2467                         $contact_record = [
2468                                 'id' => DBA::lastInsertId(),
2469                                 'network' => $network,
2470                                 'name' => $name,
2471                                 'url' => $url,
2472                                 'photo' => $photo
2473                         ];
2474
2475                         Contact::updateAvatar($photo, $importer["uid"], $contact_record["id"], true);
2476
2477                         /// @TODO Encapsulate this into a function/method
2478                         $fields = ['uid', 'username', 'email', 'page-flags', 'notify-flags', 'language'];
2479                         $user = DBA::selectFirst('user', $fields, ['uid' => $importer['uid']]);
2480                         if (DBA::isResult($user) && !in_array($user['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_FREELOVE, User::PAGE_FLAGS_COMMUNITY])) {
2481                                 // create notification
2482                                 $hash = Strings::getRandomHex();
2483
2484                                 if (is_array($contact_record)) {
2485                                         DBA::insert('intro', ['uid' => $importer['uid'], 'contact-id' => $contact_record['id'],
2486                                                                 'blocked' => false, 'knowyou' => false, 'note' => $note,
2487                                                                 'hash' => $hash, 'datetime' => DateTimeFormat::utcNow()]);
2488                                 }
2489
2490                                 Group::addMember(User::getDefaultGroup($importer['uid'], $contact_record["network"]), $contact_record['id']);
2491
2492                                 if (($user['notify-flags'] & NOTIFY_INTRO) &&
2493                                         in_array($user['page-flags'], [User::PAGE_FLAGS_NORMAL])) {
2494
2495                                         notification([
2496                                                 'type'         => NOTIFY_INTRO,
2497                                                 'notify_flags' => $user['notify-flags'],
2498                                                 'language'     => $user['language'],
2499                                                 'to_name'      => $user['username'],
2500                                                 'to_email'     => $user['email'],
2501                                                 'uid'          => $user['uid'],
2502                                                 'link'         => System::baseUrl() . '/notifications/intro',
2503                                                 'source_name'  => ((strlen(stripslashes($contact_record['name']))) ? stripslashes($contact_record['name']) : L10n::t('[Name Withheld]')),
2504                                                 'source_link'  => $contact_record['url'],
2505                                                 'source_photo' => $contact_record['photo'],
2506                                                 'verb'         => ($sharing ? ACTIVITY_FRIEND : ACTIVITY_FOLLOW),
2507                                                 'otype'        => 'intro'
2508                                         ]);
2509                                 }
2510                         } elseif (DBA::isResult($user) && in_array($user['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_FREELOVE, User::PAGE_FLAGS_COMMUNITY])) {
2511                                 $condition = ['uid' => $importer['uid'], 'url' => $url, 'pending' => true];
2512                                 DBA::update('contact', ['pending' => false], $condition);
2513
2514                                 return true;
2515                         }
2516                 }
2517
2518                 return null;
2519         }
2520
2521         public static function removeFollower($importer, $contact, array $datarray = [], $item = "")
2522         {
2523                 if (($contact['rel'] == self::FRIEND) || ($contact['rel'] == self::SHARING)) {
2524                         DBA::update('contact', ['rel' => self::SHARING], ['id' => $contact['id']]);
2525                 } else {
2526                         Contact::remove($contact['id']);
2527                 }
2528         }
2529
2530         public static function removeSharer($importer, $contact, array $datarray = [], $item = "")
2531         {
2532                 if (($contact['rel'] == self::FRIEND) || ($contact['rel'] == self::FOLLOWER)) {
2533                         DBA::update('contact', ['rel' => self::FOLLOWER], ['id' => $contact['id']]);
2534                 } else {
2535                         Contact::remove($contact['id']);
2536                 }
2537         }
2538
2539         /**
2540          * @brief Create a birthday event.
2541          *
2542          * Update the year and the birthday.
2543          */
2544         public static function updateBirthdays()
2545         {
2546                 $condition = [
2547                         '`bd` != ""
2548                         AND `bd` > "0001-01-01"
2549                         AND SUBSTRING(`bd`, 1, 4) != `bdyear`
2550                         AND (`contact`.`rel` = ? OR `contact`.`rel` = ?)
2551                         AND NOT `contact`.`pending`
2552                         AND NOT `contact`.`hidden`
2553                         AND NOT `contact`.`blocked`
2554                         AND NOT `contact`.`archive`
2555                         AND NOT `contact`.`deleted`',
2556                         Contact::SHARING,
2557                         Contact::FRIEND
2558                 ];
2559
2560                 $contacts = DBA::select('contact', ['id', 'uid', 'name', 'url', 'bd'], $condition);
2561
2562                 while ($contact = DBA::fetch($contacts)) {
2563                         Logger::log('update_contact_birthday: ' . $contact['bd']);
2564
2565                         $nextbd = DateTimeFormat::utcNow('Y') . substr($contact['bd'], 4);
2566
2567                         if (Event::createBirthday($contact, $nextbd)) {
2568                                 // update bdyear
2569                                 DBA::update(
2570                                         'contact',
2571                                         ['bdyear' => substr($nextbd, 0, 4), 'bd' => $nextbd],
2572                                         ['id' => $contact['id']]
2573                                 );
2574                         }
2575                 }
2576         }
2577
2578         /**
2579          * Remove the unavailable contact ids from the provided list
2580          *
2581          * @param array $contact_ids Contact id list
2582          * @throws \Exception
2583          */
2584         public static function pruneUnavailable(array &$contact_ids)
2585         {
2586                 if (empty($contact_ids)) {
2587                         return;
2588                 }
2589
2590                 $str = DBA::escape(implode(',', $contact_ids));
2591
2592                 $stmt = DBA::p("SELECT `id` FROM `contact` WHERE `id` IN ( " . $str . ") AND `blocked` = 0 AND `pending` = 0 AND `archive` = 0");
2593
2594                 $return = [];
2595                 while($contact = DBA::fetch($stmt)) {
2596                         $return[] = $contact['id'];
2597                 }
2598
2599                 DBA::close($stmt);
2600
2601                 $contact_ids = $return;
2602         }
2603
2604         /**
2605          * @brief Returns a magic link to authenticate remote visitors
2606          *
2607          * @todo  check if the return is either a fully qualified URL or a relative path to Friendica basedir
2608          *
2609          * @param string $contact_url The address of the target contact profile
2610          * @param string $url         An url that we will be redirected to after the authentication
2611          *
2612          * @return string with "redir" link
2613          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2614          * @throws \ImagickException
2615          */
2616         public static function magicLink($contact_url, $url = '')
2617         {
2618                 if (!local_user() && !remote_user()) {
2619                         return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
2620                 }
2621
2622                 $data = self::getProbeDataFromDatabase($contact_url);
2623                 if (empty($data)) {
2624                         return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
2625                 }
2626
2627                 // Prevents endless loop in case only a non-public contact exists for the contact URL
2628                 unset($data['uid']);
2629
2630                 return self::magicLinkByContact($data, $contact_url);
2631         }
2632
2633         /**
2634          * @brief Returns a magic link to authenticate remote visitors
2635          *
2636          * @param integer $cid The contact id of the target contact profile
2637          * @param string  $url An url that we will be redirected to after the authentication
2638          *
2639          * @return string with "redir" link
2640          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2641          * @throws \ImagickException
2642          */
2643         public static function magicLinkbyId($cid, $url = '')
2644         {
2645                 $contact = DBA::selectFirst('contact', ['id', 'network', 'url', 'uid'], ['id' => $cid]);
2646
2647                 return self::magicLinkByContact($contact, $url);
2648         }
2649
2650         /**
2651          * @brief Returns a magic link to authenticate remote visitors
2652          *
2653          * @param array  $contact The contact array with "uid", "network" and "url"
2654          * @param string $url     An url that we will be redirected to after the authentication
2655          *
2656          * @return string with "redir" link
2657          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2658          * @throws \ImagickException
2659          */
2660         public static function magicLinkByContact($contact, $url = '')
2661         {
2662                 if ((!local_user() && !remote_user()) || ($contact['network'] != Protocol::DFRN)) {
2663                         return $url ?: $contact['url']; // Equivalent to ($url != '') ? $url : $contact['url'];
2664                 }
2665
2666                 // Only redirections to the same host do make sense
2667                 if (($url != '') && (parse_url($url, PHP_URL_HOST) != parse_url($contact['url'], PHP_URL_HOST))) {
2668                         return $url;
2669                 }
2670
2671                 if (!empty($contact['uid'])) {
2672                         return self::magicLink($contact['url'], $url);
2673                 }
2674
2675                 if (empty($contact['id'])) {
2676                         return $url ?: $contact['url'];
2677                 }
2678
2679                 $redirect = 'redir/' . $contact['id'];
2680
2681                 if ($url != '') {
2682                         $redirect .= '?url=' . $url;
2683                 }
2684
2685                 return $redirect;
2686         }
2687
2688         /**
2689          * Remove a contact from all groups
2690          *
2691          * @param integer $contact_id
2692          *
2693          * @return boolean Success
2694          */
2695         public static function removeFromGroups($contact_id)
2696         {
2697                 return DBA::delete('group_member', ['contact-id' => $contact_id]);
2698         }
2699
2700         /**
2701          * Is the contact a forum?
2702          *
2703          * @param integer $contactid ID of the contact
2704          *
2705          * @return boolean "true" if it is a forum
2706          */
2707         public static function isForum($contactid)
2708         {
2709                 $fields = ['forum', 'prv'];
2710                 $condition = ['id' => $contactid];
2711                 $contact = DBA::selectFirst('contact', $fields, $condition);
2712                 if (!DBA::isResult($contact)) {
2713                         return false;
2714                 }
2715
2716                 // Is it a forum?
2717                 return ($contact['forum'] || $contact['prv']);
2718         }
2719
2720         /**
2721          * Can the remote contact receive private messages?
2722          *
2723          * @param array $contact
2724          * @return bool
2725          */
2726         public static function canReceivePrivateMessages(array $contact)
2727         {
2728                 $protocol = $contact['network'] ?? $contact['protocol'] ?? Protocol::PHANTOM;
2729                 $self = $contact['self'] ?? false;
2730
2731                 return in_array($protocol, [Protocol::DFRN, Protocol::DIASPORA, Protocol::ACTIVITYPUB]) && !$self;
2732         }
2733 }