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