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