]> git.mxchange.org Git - friendica.git/blob - src/Model/Contact.php
Create own base URL class which holds the whole base url business logic
[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                         $fields['name-date'] = DateTimeFormat::utcNow();
604                         DBA::update('contact', $fields, ['id' => $self['id']]);
605
606                         // Update the public contact as well
607                         DBA::update('contact', $fields, ['uid' => 0, 'nurl' => $self['nurl']]);
608
609                         // Update the profile
610                         $fields = ['photo' => System::baseUrl() . '/photo/profile/' .$uid . '.jpg',
611                                 'thumb' => System::baseUrl() . '/photo/avatar/' . $uid .'.jpg'];
612                         DBA::update('profile', $fields, ['uid' => $uid, 'is-default' => true]);
613                 }
614         }
615
616         /**
617          * @brief Marks a contact for removal
618          *
619          * @param int $id contact id
620          * @return null
621          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
622          */
623         public static function remove($id)
624         {
625                 // We want just to make sure that we don't delete our "self" contact
626                 $contact = DBA::selectFirst('contact', ['uid'], ['id' => $id, 'self' => false]);
627                 if (!DBA::isResult($contact) || !intval($contact['uid'])) {
628                         return;
629                 }
630
631                 // Archive the contact
632                 DBA::update('contact', ['archive' => true, 'network' => Protocol::PHANTOM, 'deleted' => true], ['id' => $id]);
633
634                 // Delete it in the background
635                 Worker::add(PRIORITY_MEDIUM, 'RemoveContact', $id);
636         }
637
638         /**
639          * @brief Sends an unfriend message. Does not remove the contact
640          *
641          * @param array   $user     User unfriending
642          * @param array   $contact  Contact unfriended
643          * @param boolean $dissolve Remove the contact on the remote side
644          * @return void
645          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
646          * @throws \ImagickException
647          */
648         public static function terminateFriendship(array $user, array $contact, $dissolve = false)
649         {
650                 if (empty($contact['network'])) {
651                         return;
652                 }
653                 if (($contact['network'] == Protocol::DFRN) && $dissolve) {
654                         DFRN::deliver($user, $contact, 'placeholder', true);
655                 } elseif (in_array($contact['network'], [Protocol::OSTATUS, Protocol::DFRN])) {
656                         // create an unfollow slap
657                         $item = [];
658                         $item['verb'] = NAMESPACE_OSTATUS . "/unfollow";
659                         $item['follow'] = $contact["url"];
660                         $item['body'] = '';
661                         $item['title'] = '';
662                         $item['guid'] = '';
663                         $item['tag'] = '';
664                         $item['attach'] = '';
665                         $slap = OStatus::salmon($item, $user);
666
667                         if (!empty($contact['notify'])) {
668                                 Salmon::slapper($user, $contact['notify'], $slap);
669                         }
670                 } elseif ($contact['network'] == Protocol::DIASPORA) {
671                         Diaspora::sendUnshare($user, $contact);
672                 } elseif ($contact['network'] == Protocol::ACTIVITYPUB) {
673                         ActivityPub\Transmitter::sendContactUndo($contact['url'], $contact['id'], $user['uid']);
674
675                         if ($dissolve) {
676                                 ActivityPub\Transmitter::sendContactReject($contact['url'], $contact['hub-verify'], $user['uid']);
677                         }
678                 }
679         }
680
681         /**
682          * @brief Marks a contact for archival after a communication issue delay
683          *
684          * Contact has refused to recognise us as a friend. We will start a countdown.
685          * If they still don't recognise us in 32 days, the relationship is over,
686          * and we won't waste any more time trying to communicate with them.
687          * This provides for the possibility that their database is temporarily messed
688          * up or some other transient event and that there's a possibility we could recover from it.
689          *
690          * @param array $contact contact to mark for archival
691          * @return null
692          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
693          */
694         public static function markForArchival(array $contact)
695         {
696                 if (!isset($contact['url']) && !empty($contact['id'])) {
697                         $fields = ['id', 'url', 'archive', 'self', 'term-date'];
698                         $contact = DBA::selectFirst('contact', $fields, ['id' => $contact['id']]);
699                         if (!DBA::isResult($contact)) {
700                                 return;
701                         }
702                 } elseif (!isset($contact['url'])) {
703                         Logger::log('Empty contact: ' . json_encode($contact) . ' - ' . System::callstack(20), Logger::DEBUG);
704                 }
705
706                 Logger::log('Contact '.$contact['id'].' is marked for archival', Logger::DEBUG);
707
708                 // Contact already archived or "self" contact? => nothing to do
709                 if ($contact['archive'] || $contact['self']) {
710                         return;
711                 }
712
713                 if ($contact['term-date'] <= DBA::NULL_DATETIME) {
714                         DBA::update('contact', ['term-date' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
715                         DBA::update('contact', ['term-date' => DateTimeFormat::utcNow()], ['`nurl` = ? AND `term-date` <= ? AND NOT `self`', Strings::normaliseLink($contact['url']), DBA::NULL_DATETIME]);
716                 } else {
717                         /* @todo
718                          * We really should send a notification to the owner after 2-3 weeks
719                          * so they won't be surprised when the contact vanishes and can take
720                          * remedial action if this was a serious mistake or glitch
721                          */
722
723                         /// @todo Check for contact vitality via probing
724                         $archival_days = Config::get('system', 'archival_days', 32);
725
726                         $expiry = $contact['term-date'] . ' + ' . $archival_days . ' days ';
727                         if (DateTimeFormat::utcNow() > DateTimeFormat::utc($expiry)) {
728                                 /* Relationship is really truly dead. archive them rather than
729                                  * delete, though if the owner tries to unarchive them we'll start
730                                  * the whole process over again.
731                                  */
732                                 DBA::update('contact', ['archive' => 1], ['id' => $contact['id']]);
733                                 DBA::update('contact', ['archive' => 1], ['nurl' => Strings::normaliseLink($contact['url']), 'self' => false]);
734                         }
735                 }
736         }
737
738         /**
739          * @brief Cancels the archival countdown
740          *
741          * @see   Contact::markForArchival()
742          *
743          * @param array $contact contact to be unmarked for archival
744          * @return null
745          * @throws \Exception
746          */
747         public static function unmarkForArchival(array $contact)
748         {
749                 $condition = ['`id` = ? AND (`term-date` > ? OR `archive`)', $contact['id'], DBA::NULL_DATETIME];
750                 $exists = DBA::exists('contact', $condition);
751
752                 // We don't need to update, we never marked this contact for archival
753                 if (!$exists) {
754                         return;
755                 }
756
757                 Logger::log('Contact '.$contact['id'].' is marked as vital again', Logger::DEBUG);
758
759                 if (!isset($contact['url']) && !empty($contact['id'])) {
760                         $fields = ['id', 'url', 'batch'];
761                         $contact = DBA::selectFirst('contact', $fields, ['id' => $contact['id']]);
762                         if (!DBA::isResult($contact)) {
763                                 return;
764                         }
765                 }
766
767                 // It's a miracle. Our dead contact has inexplicably come back to life.
768                 $fields = ['term-date' => DBA::NULL_DATETIME, 'archive' => false];
769                 DBA::update('contact', $fields, ['id' => $contact['id']]);
770                 DBA::update('contact', $fields, ['nurl' => Strings::normaliseLink($contact['url'])]);
771
772                 if (!empty($contact['batch'])) {
773                         $condition = ['batch' => $contact['batch'], 'contact-type' => self::TYPE_RELAY];
774                         DBA::update('contact', $fields, $condition);
775                 }
776         }
777
778         /**
779          * @brief Get contact data for a given profile link
780          *
781          * The function looks at several places (contact table and gcontact table) for the contact
782          * It caches its result for the same script execution to prevent duplicate calls
783          *
784          * @param string $url     The profile link
785          * @param int    $uid     User id
786          * @param array  $default If not data was found take this data as default value
787          *
788          * @return array Contact data
789          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
790          */
791         public static function getDetailsByURL($url, $uid = -1, array $default = [])
792         {
793                 static $cache = [];
794
795                 if ($url == '') {
796                         return $default;
797                 }
798
799                 if ($uid == -1) {
800                         $uid = local_user();
801                 }
802
803                 if (isset($cache[$url][$uid])) {
804                         return $cache[$url][$uid];
805                 }
806
807                 $ssl_url = str_replace('http://', 'https://', $url);
808
809                 // Fetch contact data from the contact table for the given user
810                 $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`,
811                         `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
812                 FROM `contact` WHERE `nurl` = ? AND `uid` = ?", Strings::normaliseLink($url), $uid);
813                 $r = DBA::toArray($s);
814
815                 // Fetch contact data from the contact table for the given user, checking with the alias
816                 if (!DBA::isResult($r)) {
817                         $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`,
818                                 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
819                         FROM `contact` WHERE `alias` IN (?, ?, ?) AND `uid` = ?", Strings::normaliseLink($url), $url, $ssl_url, $uid);
820                         $r = DBA::toArray($s);
821                 }
822
823                 // Fetch the data from the contact table with "uid=0" (which is filled automatically)
824                 if (!DBA::isResult($r)) {
825                         $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`,
826                         `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
827                         FROM `contact` WHERE `nurl` = ? AND `uid` = 0", Strings::normaliseLink($url));
828                         $r = DBA::toArray($s);
829                 }
830
831                 // Fetch the data from the contact table with "uid=0" (which is filled automatically) - checked with the alias
832                 if (!DBA::isResult($r)) {
833                         $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`,
834                         `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
835                         FROM `contact` WHERE `alias` IN (?, ?, ?) AND `uid` = 0", Strings::normaliseLink($url), $url, $ssl_url);
836                         $r = DBA::toArray($s);
837                 }
838
839                 // Fetch the data from the gcontact table
840                 if (!DBA::isResult($r)) {
841                         $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`,
842                         `keywords`, `gender`, `photo`, `photo` AS `thumb`, `photo` AS `micro`, 0 AS `forum`, 0 AS `prv`, `community`, `contact-type`, `birthday`, 0 AS `self`
843                         FROM `gcontact` WHERE `nurl` = ?", Strings::normaliseLink($url));
844                         $r = DBA::toArray($s);
845                 }
846
847                 if (DBA::isResult($r)) {
848                         // If there is more than one entry we filter out the connector networks
849                         if (count($r) > 1) {
850                                 foreach ($r as $id => $result) {
851                                         if ($result["network"] == Protocol::STATUSNET) {
852                                                 unset($r[$id]);
853                                         }
854                                 }
855                         }
856
857                         $profile = array_shift($r);
858
859                         // "bd" always contains the upcoming birthday of a contact.
860                         // "birthday" might contain the birthday including the year of birth.
861                         if ($profile["birthday"] > DBA::NULL_DATE) {
862                                 $bd_timestamp = strtotime($profile["birthday"]);
863                                 $month = date("m", $bd_timestamp);
864                                 $day = date("d", $bd_timestamp);
865
866                                 $current_timestamp = time();
867                                 $current_year = date("Y", $current_timestamp);
868                                 $current_month = date("m", $current_timestamp);
869                                 $current_day = date("d", $current_timestamp);
870
871                                 $profile["bd"] = $current_year . "-" . $month . "-" . $day;
872                                 $current = $current_year . "-" . $current_month . "-" . $current_day;
873
874                                 if ($profile["bd"] < $current) {
875                                         $profile["bd"] = ( ++$current_year) . "-" . $month . "-" . $day;
876                                 }
877                         } else {
878                                 $profile["bd"] = DBA::NULL_DATE;
879                         }
880                 } else {
881                         $profile = $default;
882                 }
883
884                 if (empty($profile["photo"]) && isset($default["photo"])) {
885                         $profile["photo"] = $default["photo"];
886                 }
887
888                 if (empty($profile["name"]) && isset($default["name"])) {
889                         $profile["name"] = $default["name"];
890                 }
891
892                 if (empty($profile["network"]) && isset($default["network"])) {
893                         $profile["network"] = $default["network"];
894                 }
895
896                 if (empty($profile["thumb"]) && isset($profile["photo"])) {
897                         $profile["thumb"] = $profile["photo"];
898                 }
899
900                 if (empty($profile["micro"]) && isset($profile["thumb"])) {
901                         $profile["micro"] = $profile["thumb"];
902                 }
903
904                 if ((empty($profile["addr"]) || empty($profile["name"])) && (defaults($profile, "gid", 0) != 0)
905                         && in_array($profile["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS])
906                 ) {
907                         Worker::add(PRIORITY_LOW, "UpdateGContact", $profile["gid"]);
908                 }
909
910                 // Show contact details of Diaspora contacts only if connected
911                 if ((defaults($profile, "cid", 0) == 0) && (defaults($profile, "network", "") == Protocol::DIASPORA)) {
912                         $profile["location"] = "";
913                         $profile["about"] = "";
914                         $profile["gender"] = "";
915                         $profile["birthday"] = DBA::NULL_DATE;
916                 }
917
918                 $cache[$url][$uid] = $profile;
919
920                 return $profile;
921         }
922
923         /**
924          * @brief Get contact data for a given address
925          *
926          * The function looks at several places (contact table and gcontact table) for the contact
927          *
928          * @param string $addr The profile link
929          * @param int    $uid  User id
930          *
931          * @return array Contact data
932          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
933          * @throws \ImagickException
934          */
935         public static function getDetailsByAddr($addr, $uid = -1)
936         {
937                 if ($addr == '') {
938                         return [];
939                 }
940
941                 if ($uid == -1) {
942                         $uid = local_user();
943                 }
944
945                 // Fetch contact data from the contact table for the given user
946                 $r = q("SELECT `id`, `id` AS `cid`, 0 AS `gid`, 0 AS `zid`, `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, `xmpp`,
947                         `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
948                         FROM `contact` WHERE `addr` = '%s' AND `uid` = %d AND NOT `deleted`",
949                         DBA::escape($addr),
950                         intval($uid)
951                 );
952                 // Fetch the data from the contact table with "uid=0" (which is filled automatically)
953                 if (!DBA::isResult($r)) {
954                         $r = q("SELECT `id`, 0 AS `cid`, `id` AS `zid`, 0 AS `gid`, `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, `xmpp`,
955                                 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
956                                 FROM `contact` WHERE `addr` = '%s' AND `uid` = 0 AND NOT `deleted`",
957                                 DBA::escape($addr)
958                         );
959                 }
960
961                 // Fetch the data from the gcontact table
962                 if (!DBA::isResult($r)) {
963                         $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`,
964                                 `keywords`, `gender`, `photo`, `photo` AS `thumb`, `photo` AS `micro`, `community` AS `forum`, 0 AS `prv`, `community`, `contact-type`, `birthday`, 0 AS `self`
965                                 FROM `gcontact` WHERE `addr` = '%s'",
966                                 DBA::escape($addr)
967                         );
968                 }
969
970                 if (!DBA::isResult($r)) {
971                         $data = Probe::uri($addr);
972
973                         $profile = self::getDetailsByURL($data['url'], $uid);
974                 } else {
975                         $profile = $r[0];
976                 }
977
978                 return $profile;
979         }
980
981         /**
982          * @brief Returns the data array for the photo menu of a given contact
983          *
984          * @param array $contact contact
985          * @param int   $uid     optional, default 0
986          * @return array
987          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
988          * @throws \ImagickException
989          */
990         public static function photoMenu(array $contact, $uid = 0)
991         {
992                 $pm_url = '';
993                 $status_link = '';
994                 $photos_link = '';
995                 $contact_drop_link = '';
996                 $poke_link = '';
997
998                 if ($uid == 0) {
999                         $uid = local_user();
1000                 }
1001
1002                 if (empty($contact['uid']) || ($contact['uid'] != $uid)) {
1003                         if ($uid == 0) {
1004                                 $profile_link = self::magicLink($contact['url']);
1005                                 $menu = ['profile' => [L10n::t('View Profile'), $profile_link, true]];
1006
1007                                 return $menu;
1008                         }
1009
1010                         // Look for our own contact if the uid doesn't match and isn't public
1011                         $contact_own = DBA::selectFirst('contact', [], ['nurl' => $contact['nurl'], 'network' => $contact['network'], 'uid' => $uid]);
1012                         if (DBA::isResult($contact_own)) {
1013                                 return self::photoMenu($contact_own, $uid);
1014                         }
1015                 }
1016
1017                 $sparkle = false;
1018                 if (($contact['network'] === Protocol::DFRN) && !$contact['self']) {
1019                         $sparkle = true;
1020                         $profile_link = System::baseUrl() . '/redir/' . $contact['id'] . '?url=' . $contact['url'];
1021                 } else {
1022                         $profile_link = $contact['url'];
1023                 }
1024
1025                 if ($profile_link === 'mailbox') {
1026                         $profile_link = '';
1027                 }
1028
1029                 if ($sparkle) {
1030                         $status_link = $profile_link . '?tab=status';
1031                         $photos_link = str_replace('/profile/', '/photos/', $profile_link);
1032                         $profile_link = $profile_link . '?tab=profile';
1033                 }
1034
1035                 if (in_array($contact['network'], [Protocol::DFRN, Protocol::DIASPORA]) && !$contact['self']) {
1036                         $pm_url = System::baseUrl() . '/message/new/' . $contact['id'];
1037                 }
1038
1039                 if (($contact['network'] == Protocol::DFRN) && !$contact['self']) {
1040                         $poke_link = System::baseUrl() . '/poke/?f=&c=' . $contact['id'];
1041                 }
1042
1043                 $contact_url = System::baseUrl() . '/contact/' . $contact['id'];
1044
1045                 $posts_link = System::baseUrl() . '/contact/' . $contact['id'] . '/conversations';
1046
1047                 if (!$contact['self']) {
1048                         $contact_drop_link = System::baseUrl() . '/contact/' . $contact['id'] . '/drop?confirm=1';
1049                 }
1050
1051                 /**
1052                  * Menu array:
1053                  * "name" => [ "Label", "link", (bool)Should the link opened in a new tab? ]
1054                  */
1055                 if (empty($contact['uid'])) {
1056                         $connlnk = 'follow/?url=' . $contact['url'];
1057                         $menu = [
1058                                 'profile' => [L10n::t('View Profile'),   $profile_link, true],
1059                                 'network' => [L10n::t('Network Posts'),  $posts_link,   false],
1060                                 'edit'    => [L10n::t('View Contact'),   $contact_url,  false],
1061                                 'follow'  => [L10n::t('Connect/Follow'), $connlnk,      true],
1062                         ];
1063                 } else {
1064                         $menu = [
1065                                 'status'  => [L10n::t('View Status'),   $status_link,       true],
1066                                 'profile' => [L10n::t('View Profile'),  $profile_link,      true],
1067                                 'photos'  => [L10n::t('View Photos'),   $photos_link,       true],
1068                                 'network' => [L10n::t('Network Posts'), $posts_link,        false],
1069                                 'edit'    => [L10n::t('View Contact'),  $contact_url,       false],
1070                                 'drop'    => [L10n::t('Drop Contact'),  $contact_drop_link, false],
1071                                 'pm'      => [L10n::t('Send PM'),       $pm_url,            false],
1072                                 'poke'    => [L10n::t('Poke'),          $poke_link,         false],
1073                         ];
1074                 }
1075
1076                 $args = ['contact' => $contact, 'menu' => &$menu];
1077
1078                 Hook::callAll('contact_photo_menu', $args);
1079
1080                 $menucondensed = [];
1081
1082                 foreach ($menu as $menuname => $menuitem) {
1083                         if ($menuitem[1] != '') {
1084                                 $menucondensed[$menuname] = $menuitem;
1085                         }
1086                 }
1087
1088                 return $menucondensed;
1089         }
1090
1091         /**
1092          * @brief Returns ungrouped contact count or list for user
1093          *
1094          * Returns either the total number of ungrouped contacts for the given user
1095          * id or a paginated list of ungrouped contacts.
1096          *
1097          * @param int $uid uid
1098          * @return array
1099          * @throws \Exception
1100          */
1101         public static function getUngroupedList($uid)
1102         {
1103                 return q("SELECT *
1104                            FROM `contact`
1105                            WHERE `uid` = %d
1106                            AND NOT `self`
1107                            AND NOT `deleted`
1108                            AND NOT `blocked`
1109                            AND NOT `pending`
1110                            AND `id` NOT IN (
1111                                 SELECT DISTINCT(`contact-id`)
1112                                 FROM `group_member`
1113                                 INNER JOIN `group` ON `group`.`id` = `group_member`.`gid`
1114                                 WHERE `group`.`uid` = %d
1115                            )", intval($uid), intval($uid));
1116         }
1117
1118         /**
1119          * @brief Fetch the contact id for a given URL and user
1120          *
1121          * First lookup in the contact table to find a record matching either `url`, `nurl`,
1122          * `addr` or `alias`.
1123          *
1124          * If there's no record and we aren't looking for a public contact, we quit.
1125          * If there's one, we check that it isn't time to update the picture else we
1126          * directly return the found contact id.
1127          *
1128          * Second, we probe the provided $url whether it's http://server.tld/profile or
1129          * nick@server.tld. We quit if we can't get any info back.
1130          *
1131          * Third, we create the contact record if it doesn't exist
1132          *
1133          * Fourth, we update the existing record with the new data (avatar, alias, nick)
1134          * if there's any updates
1135          *
1136          * @param string  $url       Contact URL
1137          * @param integer $uid       The user id for the contact (0 = public contact)
1138          * @param boolean $no_update Don't update the contact
1139          * @param array   $default   Default value for creating the contact when every else fails
1140          * @param boolean $in_loop   Internally used variable to prevent an endless loop
1141          *
1142          * @return integer Contact ID
1143          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1144          * @throws \ImagickException
1145          */
1146         public static function getIdForURL($url, $uid = 0, $no_update = false, $default = [], $in_loop = false)
1147         {
1148                 Logger::log("Get contact data for url " . $url . " and user " . $uid . " - " . System::callstack(), Logger::DEBUG);
1149
1150                 $contact_id = 0;
1151
1152                 if ($url == '') {
1153                         return 0;
1154                 }
1155
1156                 /// @todo Verify if we can't use Contact::getDetailsByUrl instead of the following
1157                 // We first try the nurl (http://server.tld/nick), most common case
1158                 $contact = DBA::selectFirst('contact', ['id', 'avatar', 'avatar-date'], ['nurl' => Strings::normaliseLink($url), 'uid' => $uid, 'deleted' => false]);
1159
1160                 // Then the addr (nick@server.tld)
1161                 if (!DBA::isResult($contact)) {
1162                         $contact = DBA::selectFirst('contact', ['id', 'avatar', 'avatar-date'], ['addr' => $url, 'uid' => $uid, 'deleted' => false]);
1163                 }
1164
1165                 // Then the alias (which could be anything)
1166                 if (!DBA::isResult($contact)) {
1167                         // The link could be provided as http although we stored it as https
1168                         $ssl_url = str_replace('http://', 'https://', $url);
1169                         $condition = ['`alias` IN (?, ?, ?) AND `uid` = ? AND NOT `deleted`', $url, Strings::normaliseLink($url), $ssl_url, $uid];
1170                         $contact = DBA::selectFirst('contact', ['id', 'avatar', 'avatar-date'], $condition);
1171                 }
1172
1173                 if (DBA::isResult($contact)) {
1174                         $contact_id = $contact["id"];
1175
1176                         // Update the contact every 7 days
1177                         $update_contact = ($contact['avatar-date'] < DateTimeFormat::utc('now -7 days'));
1178
1179                         // We force the update if the avatar is empty
1180                         if (empty($contact['avatar'])) {
1181                                 $update_contact = true;
1182                         }
1183                         if (!$update_contact || $no_update) {
1184                                 return $contact_id;
1185                         }
1186                 } elseif ($uid != 0) {
1187                         // Non-existing user-specific contact, exiting
1188                         return 0;
1189                 }
1190
1191                 // When we don't want to update, we look if some of our users already know this contact
1192                 if ($no_update) {
1193                         $fields = ['url', 'addr', 'alias', 'notify', 'poll', 'name', 'nick',
1194                                 'photo', 'keywords', 'location', 'about', 'network',
1195                                 'priority', 'batch', 'request', 'confirm', 'poco'];
1196                         $data = DBA::selectFirst('contact', $fields, ['nurl' => Strings::normaliseLink($url)]);
1197
1198                         if (DBA::isResult($data)) {
1199                                 // For security reasons we don't fetch key data from our users
1200                                 $data["pubkey"] = '';
1201                         }
1202                 } else {
1203                         $data = [];
1204                 }
1205
1206                 if (empty($data)) {
1207                         $data = Probe::uri($url, "", $uid);
1208
1209                         // Ensure that there is a gserver entry
1210                         if (!empty($data['baseurl']) && ($data['network'] != Protocol::PHANTOM)) {
1211                                 PortableContact::checkServer($data['baseurl']);
1212                         }
1213                 }
1214
1215                 // Last try in gcontact for unsupported networks
1216                 if (!in_array($data["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::OSTATUS, Protocol::DIASPORA, Protocol::PUMPIO, Protocol::MAIL, Protocol::FEED])) {
1217                         if ($uid != 0) {
1218                                 return 0;
1219                         }
1220
1221                         // Get data from the gcontact table
1222                         $fields = ['name', 'nick', 'url', 'photo', 'addr', 'alias', 'network'];
1223                         $contact = DBA::selectFirst('gcontact', $fields, ['nurl' => Strings::normaliseLink($url)]);
1224                         if (!DBA::isResult($contact)) {
1225                                 $contact = DBA::selectFirst('contact', $fields, ['nurl' => Strings::normaliseLink($url)]);
1226                         }
1227
1228                         if (!DBA::isResult($contact)) {
1229                                 $fields = ['url', 'addr', 'alias', 'notify', 'poll', 'name', 'nick',
1230                                         'photo', 'keywords', 'location', 'about', 'network',
1231                                         'priority', 'batch', 'request', 'confirm', 'poco'];
1232                                 $contact = DBA::selectFirst('contact', $fields, ['addr' => $url]);
1233                         }
1234
1235                         // The link could be provided as http although we stored it as https
1236                         $ssl_url = str_replace('http://', 'https://', $url);
1237
1238                         if (!DBA::isResult($contact)) {
1239                                 $condition = ['alias' => [$url, Strings::normaliseLink($url), $ssl_url]];
1240                                 $contact = DBA::selectFirst('contact', $fields, $condition);
1241                         }
1242
1243                         if (!DBA::isResult($contact)) {
1244                                 $fields = ['url', 'addr', 'alias', 'notify', 'poll', 'name', 'nick',
1245                                         'photo', 'network', 'priority', 'batch', 'request', 'confirm'];
1246                                 $condition = ['url' => [$url, Strings::normaliseLink($url), $ssl_url]];
1247                                 $contact = DBA::selectFirst('fcontact', $fields, $condition);
1248                         }
1249
1250                         if (!empty($default)) {
1251                                 $contact = $default;
1252                         }
1253
1254                         if (!DBA::isResult($contact)) {
1255                                 return 0;
1256                         } else {
1257                                 $data = array_merge($data, $contact);
1258                         }
1259                 }
1260
1261                 if (!$contact_id && ($data["alias"] != '') && ($data["alias"] != $url) && !$in_loop) {
1262                         $contact_id = self::getIdForURL($data["alias"], $uid, true, $default, true);
1263                 }
1264
1265                 if (!$contact_id) {
1266                         $fields = [
1267                                 'uid'       => $uid,
1268                                 'created'   => DateTimeFormat::utcNow(),
1269                                 'url'       => $data["url"],
1270                                 'nurl'      => Strings::normaliseLink($data["url"]),
1271                                 'addr'      => $data["addr"],
1272                                 'alias'     => $data["alias"],
1273                                 'notify'    => $data["notify"],
1274                                 'poll'      => $data["poll"],
1275                                 'name'      => $data["name"],
1276                                 'nick'      => $data["nick"],
1277                                 'photo'     => $data["photo"],
1278                                 'keywords'  => $data["keywords"],
1279                                 'location'  => $data["location"],
1280                                 'about'     => $data["about"],
1281                                 'network'   => $data["network"],
1282                                 'pubkey'    => $data["pubkey"],
1283                                 'rel'       => self::SHARING,
1284                                 'priority'  => $data["priority"],
1285                                 'batch'     => $data["batch"],
1286                                 'request'   => $data["request"],
1287                                 'confirm'   => $data["confirm"],
1288                                 'poco'      => $data["poco"],
1289                                 'name-date' => DateTimeFormat::utcNow(),
1290                                 'uri-date'  => DateTimeFormat::utcNow(),
1291                                 'avatar-date' => DateTimeFormat::utcNow(),
1292                                 'writable'  => 1,
1293                                 'blocked'   => 0,
1294                                 'readonly'  => 0,
1295                                 'pending'   => 0];
1296
1297                         $condition = ['nurl' => Strings::normaliseLink($data["url"]), 'uid' => $uid, 'deleted' => false];
1298
1299                         DBA::update('contact', $fields, $condition, true);
1300
1301                         $s = DBA::select('contact', ['id'], $condition, ['order' => ['id'], 'limit' => 2]);
1302                         $contacts = DBA::toArray($s);
1303                         if (!DBA::isResult($contacts)) {
1304                                 return 0;
1305                         }
1306
1307                         $contact_id = $contacts[0]["id"];
1308
1309                         // Update the newly created contact from data in the gcontact table
1310                         $gcontact = DBA::selectFirst('gcontact', ['location', 'about', 'keywords', 'gender'], ['nurl' => Strings::normaliseLink($data["url"])]);
1311                         if (DBA::isResult($gcontact)) {
1312                                 // Only use the information when the probing hadn't fetched these values
1313                                 if ($data['keywords'] != '') {
1314                                         unset($gcontact['keywords']);
1315                                 }
1316                                 if ($data['location'] != '') {
1317                                         unset($gcontact['location']);
1318                                 }
1319                                 if ($data['about'] != '') {
1320                                         unset($gcontact['about']);
1321                                 }
1322                                 DBA::update('contact', $gcontact, ['id' => $contact_id]);
1323                         }
1324
1325                         if (count($contacts) > 1 && $uid == 0 && $contact_id != 0 && $data["url"] != "") {
1326                                 $condition = ["`nurl` = ? AND `uid` = ? AND `id` != ? AND NOT `self`",
1327                                         Strings::normaliseLink($data["url"]), 0, $contact_id];
1328                                 Logger::log('Deleting duplicate contact ' . json_encode($condition), Logger::DEBUG);
1329                                 DBA::delete('contact', $condition);
1330                         }
1331                 }
1332
1333                 self::updateAvatar($data["photo"], $uid, $contact_id);
1334
1335                 $fields = ['url', 'nurl', 'addr', 'alias', 'name', 'nick', 'keywords', 'location', 'about', 'avatar-date', 'pubkey'];
1336                 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact_id]);
1337
1338                 // This condition should always be true
1339                 if (!DBA::isResult($contact)) {
1340                         return $contact_id;
1341                 }
1342
1343                 $updated = ['addr' => $data['addr'],
1344                         'alias' => $data['alias'],
1345                         'url' => $data['url'],
1346                         'nurl' => Strings::normaliseLink($data['url']),
1347                         'name' => $data['name'],
1348                         'nick' => $data['nick']];
1349
1350                 if ($data['keywords'] != '') {
1351                         $updated['keywords'] = $data['keywords'];
1352                 }
1353                 if ($data['location'] != '') {
1354                         $updated['location'] = $data['location'];
1355                 }
1356
1357                 // Update the technical stuff as well - if filled
1358                 if ($data['notify'] != '') {
1359                         $updated['notify'] = $data['notify'];
1360                 }
1361                 if ($data['poll'] != '') {
1362                         $updated['poll'] = $data['poll'];
1363                 }
1364                 if ($data['batch'] != '') {
1365                         $updated['batch'] = $data['batch'];
1366                 }
1367                 if ($data['request'] != '') {
1368                         $updated['request'] = $data['request'];
1369                 }
1370                 if ($data['confirm'] != '') {
1371                         $updated['confirm'] = $data['confirm'];
1372                 }
1373                 if ($data['poco'] != '') {
1374                         $updated['poco'] = $data['poco'];
1375                 }
1376
1377                 // Only fill the pubkey if it had been empty before. We have to prevent identity theft.
1378                 if (empty($contact['pubkey'])) {
1379                         $updated['pubkey'] = $data['pubkey'];
1380                 }
1381
1382                 if (($data["addr"] != $contact["addr"]) || ($data["alias"] != $contact["alias"])) {
1383                         $updated['uri-date'] = DateTimeFormat::utcNow();
1384                 }
1385                 if (($data["name"] != $contact["name"]) || ($data["nick"] != $contact["nick"])) {
1386                         $updated['name-date'] = DateTimeFormat::utcNow();
1387                 }
1388
1389                 $updated['avatar-date'] = DateTimeFormat::utcNow();
1390
1391                 DBA::update('contact', $updated, ['id' => $contact_id], $contact);
1392
1393                 return $contact_id;
1394         }
1395
1396         /**
1397          * @brief Checks if the contact is blocked
1398          *
1399          * @param int $cid contact id
1400          *
1401          * @return boolean Is the contact blocked?
1402          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1403          */
1404         public static function isBlocked($cid)
1405         {
1406                 if ($cid == 0) {
1407                         return false;
1408                 }
1409
1410                 $blocked = DBA::selectFirst('contact', ['blocked', 'url'], ['id' => $cid]);
1411                 if (!DBA::isResult($blocked)) {
1412                         return false;
1413                 }
1414
1415                 if (Network::isUrlBlocked($blocked['url'])) {
1416                         return true;
1417                 }
1418
1419                 return (bool) $blocked['blocked'];
1420         }
1421
1422         /**
1423          * @brief Checks if the contact is hidden
1424          *
1425          * @param int $cid contact id
1426          *
1427          * @return boolean Is the contact hidden?
1428          * @throws \Exception
1429          */
1430         public static function isHidden($cid)
1431         {
1432                 if ($cid == 0) {
1433                         return false;
1434                 }
1435
1436                 $hidden = DBA::selectFirst('contact', ['hidden'], ['id' => $cid]);
1437                 if (!DBA::isResult($hidden)) {
1438                         return false;
1439                 }
1440                 return (bool) $hidden['hidden'];
1441         }
1442
1443         /**
1444          * @brief Returns posts from a given contact url
1445          *
1446          * @param string $contact_url Contact URL
1447          *
1448          * @param bool   $thread_mode
1449          * @param int    $update
1450          * @return string posts in HTML
1451          * @throws \Exception
1452          */
1453         public static function getPostsFromUrl($contact_url, $thread_mode = false, $update = 0)
1454         {
1455                 $a = self::getApp();
1456
1457                 $cid = self::getIdForURL($contact_url);
1458
1459                 $contact = DBA::selectFirst('contact', ['contact-type', 'network'], ['id' => $cid]);
1460                 if (!DBA::isResult($contact)) {
1461                         return '';
1462                 }
1463
1464                 if (in_array($contact["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS, ""])) {
1465                         $sql = "(`item`.`uid` = 0 OR (`item`.`uid` = ? AND NOT `item`.`global`))";
1466                 } else {
1467                         $sql = "`item`.`uid` = ?";
1468                 }
1469
1470                 $contact_field = ($contact["contact-type"] == self::TYPE_COMMUNITY ? 'owner-id' : 'author-id');
1471
1472                 if ($thread_mode) {
1473                         $condition = ["`$contact_field` = ? AND `gravity` = ? AND " . $sql,
1474                                 $cid, GRAVITY_PARENT, local_user()];
1475                 } else {
1476                         $condition = ["`$contact_field` = ? AND `gravity` IN (?, ?) AND " . $sql,
1477                                 $cid, GRAVITY_PARENT, GRAVITY_COMMENT, local_user()];
1478                 }
1479
1480                 $pager = new Pager($a->query_string);
1481
1482                 $params = ['order' => ['created' => true],
1483                         'limit' => [$pager->getStart(), $pager->getItemsPerPage()]];
1484
1485                 if ($thread_mode) {
1486                         $r = Item::selectThreadForUser(local_user(), ['uri'], $condition, $params);
1487
1488                         $items = Item::inArray($r);
1489
1490                         $o = conversation($a, $items, $pager, 'contacts', $update, false, 'commented', local_user());
1491                 } else {
1492                         $r = Item::selectForUser(local_user(), [], $condition, $params);
1493
1494                         $items = Item::inArray($r);
1495
1496                         $o = conversation($a, $items, $pager, 'contact-posts', false);
1497                 }
1498
1499                 if (!$update) {
1500                         $o .= $pager->renderMinimal(count($items));
1501                 }
1502
1503                 return $o;
1504         }
1505
1506         /**
1507          * @brief Returns the account type name
1508          *
1509          * The function can be called with either the user or the contact array
1510          *
1511          * @param array $contact contact or user array
1512          * @return string
1513          */
1514         public static function getAccountType(array $contact)
1515         {
1516                 // There are several fields that indicate that the contact or user is a forum
1517                 // "page-flags" is a field in the user table,
1518                 // "forum" and "prv" are used in the contact table. They stand for User::PAGE_FLAGS_COMMUNITY and User::PAGE_FLAGS_PRVGROUP.
1519                 // "community" is used in the gcontact table and is true if the contact is User::PAGE_FLAGS_COMMUNITY or User::PAGE_FLAGS_PRVGROUP.
1520                 if ((isset($contact['page-flags']) && (intval($contact['page-flags']) == User::PAGE_FLAGS_COMMUNITY))
1521                         || (isset($contact['page-flags']) && (intval($contact['page-flags']) == User::PAGE_FLAGS_PRVGROUP))
1522                         || (isset($contact['forum']) && intval($contact['forum']))
1523                         || (isset($contact['prv']) && intval($contact['prv']))
1524                         || (isset($contact['community']) && intval($contact['community']))
1525                 ) {
1526                         $type = self::TYPE_COMMUNITY;
1527                 } else {
1528                         $type = self::TYPE_PERSON;
1529                 }
1530
1531                 // The "contact-type" (contact table) and "account-type" (user table) are more general then the chaos from above.
1532                 if (isset($contact["contact-type"])) {
1533                         $type = $contact["contact-type"];
1534                 }
1535
1536                 if (isset($contact["account-type"])) {
1537                         $type = $contact["account-type"];
1538                 }
1539
1540                 switch ($type) {
1541                         case self::TYPE_ORGANISATION:
1542                                 $account_type = L10n::t("Organisation");
1543                                 break;
1544
1545                         case self::TYPE_NEWS:
1546                                 $account_type = L10n::t('News');
1547                                 break;
1548
1549                         case self::TYPE_COMMUNITY:
1550                                 $account_type = L10n::t("Forum");
1551                                 break;
1552
1553                         default:
1554                                 $account_type = "";
1555                                 break;
1556                 }
1557
1558                 return $account_type;
1559         }
1560
1561         /**
1562          * @brief Blocks a contact
1563          *
1564          * @param int $uid
1565          * @return bool
1566          * @throws \Exception
1567          */
1568         public static function block($uid)
1569         {
1570                 $return = DBA::update('contact', ['blocked' => true], ['id' => $uid]);
1571
1572                 return $return;
1573         }
1574
1575         /**
1576          * @brief Unblocks a contact
1577          *
1578          * @param int $uid
1579          * @return bool
1580          * @throws \Exception
1581          */
1582         public static function unblock($uid)
1583         {
1584                 $return = DBA::update('contact', ['blocked' => false], ['id' => $uid]);
1585
1586                 return $return;
1587         }
1588
1589         /**
1590          * @brief Updates the avatar links in a contact only if needed
1591          *
1592          * @param string $avatar Link to avatar picture
1593          * @param int    $uid    User id of contact owner
1594          * @param int    $cid    Contact id
1595          * @param bool   $force  force picture update
1596          *
1597          * @return array Returns array of the different avatar sizes
1598          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1599          * @throws \ImagickException
1600          */
1601         public static function updateAvatar($avatar, $uid, $cid, $force = false)
1602         {
1603                 $contact = DBA::selectFirst('contact', ['avatar', 'photo', 'thumb', 'micro', 'nurl'], ['id' => $cid]);
1604                 if (!DBA::isResult($contact)) {
1605                         return false;
1606                 } else {
1607                         $data = [$contact["photo"], $contact["thumb"], $contact["micro"]];
1608                 }
1609
1610                 if (($contact["avatar"] != $avatar) || $force) {
1611                         $photos = Photo::importProfilePhoto($avatar, $uid, $cid, true);
1612
1613                         if ($photos) {
1614                                 DBA::update(
1615                                         'contact',
1616                                         ['avatar' => $avatar, 'photo' => $photos[0], 'thumb' => $photos[1], 'micro' => $photos[2], 'avatar-date' => DateTimeFormat::utcNow()],
1617                                         ['id' => $cid]
1618                                 );
1619
1620                                 // Update the public contact (contact id = 0)
1621                                 if ($uid != 0) {
1622                                         $pcontact = DBA::selectFirst('contact', ['id'], ['nurl' => $contact['nurl'], 'uid' => 0]);
1623                                         if (DBA::isResult($pcontact)) {
1624                                                 self::updateAvatar($avatar, 0, $pcontact['id'], $force);
1625                                         }
1626                                 }
1627
1628                                 return $photos;
1629                         }
1630                 }
1631
1632                 return $data;
1633         }
1634
1635         /**
1636          * @param integer $id      contact id
1637          * @param string  $network Optional network we are probing for
1638          * @param boolean $force   Optional forcing of network probing (otherwise we use the cached data)
1639          * @return boolean
1640          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1641          * @throws \ImagickException
1642          */
1643         public static function updateFromProbe($id, $network = '', $force = false)
1644         {
1645                 /*
1646                   Warning: Never ever fetch the public key via Probe::uri and write it into the contacts.
1647                   This will reliably kill your communication with Friendica contacts.
1648                  */
1649
1650                 $fields = ['avatar', 'uid', 'name', 'nick', 'url', 'addr', 'batch', 'notify',
1651                         'poll', 'request', 'confirm', 'poco', 'network', 'alias'];
1652                 $contact = DBA::selectFirst('contact', $fields, ['id' => $id]);
1653                 if (!DBA::isResult($contact)) {
1654                         return false;
1655                 }
1656
1657                 $uid = $contact['uid'];
1658                 unset($contact['uid']);
1659
1660                 $contact['photo'] = $contact['avatar'];
1661                 unset($contact['avatar']);
1662
1663                 $ret = Probe::uri($contact['url'], $network, $uid, !$force);
1664
1665                 // If Probe::uri fails the network code will be different (mostly "feed" or "unkn")
1666                 if ((in_array($ret['network'], [Protocol::FEED, Protocol::PHANTOM])) && ($ret['network'] != $contact['network'])) {
1667                         return false;
1668                 }
1669
1670                 $update = false;
1671
1672                 // make sure to not overwrite existing values with blank entries
1673                 foreach ($ret as $key => $val) {
1674                         if (!isset($contact[$key])) {
1675                                 unset($ret[$key]);
1676                         } elseif (($contact[$key] != '') && ($val == '')) {
1677                                 $ret[$key] = $contact[$key];
1678                         } elseif ($ret[$key] != $contact[$key]) {
1679                                 $update = true;
1680                         }
1681                 }
1682
1683                 if (!$update) {
1684                         return true;
1685                 }
1686
1687                 $ret['nurl'] = Strings::normaliseLink($ret['url']);
1688
1689                 self::updateAvatar($ret['photo'], $uid, $id, true);
1690
1691                 unset($ret['photo']);
1692                 DBA::update('contact', $ret, ['id' => $id]);
1693
1694                 // Update the corresponding gcontact entry
1695                 PortableContact::lastUpdated($ret["url"]);
1696
1697                 return true;
1698         }
1699
1700         /**
1701          * Takes a $uid and a url/handle and adds a new contact
1702          * Currently if the contact is DFRN, interactive needs to be true, to redirect to the
1703          * dfrn_request page.
1704          *
1705          * Otherwise this can be used to bulk add StatusNet contacts, Twitter contacts, etc.
1706          *
1707          * Returns an array
1708          * $return['success'] boolean true if successful
1709          * $return['message'] error text if success is false.
1710          *
1711          * @brief Takes a $uid and a url/handle and adds a new contact
1712          * @param int    $uid
1713          * @param string $url
1714          * @param bool   $interactive
1715          * @param string $network
1716          * @return array
1717          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1718          * @throws \ImagickException
1719          */
1720         public static function createFromProbe($uid, $url, $interactive = false, $network = '')
1721         {
1722                 $result = ['cid' => -1, 'success' => false, 'message' => ''];
1723
1724                 $a = \get_app();
1725
1726                 // remove ajax junk, e.g. Twitter
1727                 $url = str_replace('/#!/', '/', $url);
1728
1729                 if (!Network::isUrlAllowed($url)) {
1730                         $result['message'] = L10n::t('Disallowed profile URL.');
1731                         return $result;
1732                 }
1733
1734                 if (Network::isUrlBlocked($url)) {
1735                         $result['message'] = L10n::t('Blocked domain');
1736                         return $result;
1737                 }
1738
1739                 if (!$url) {
1740                         $result['message'] = L10n::t('Connect URL missing.');
1741                         return $result;
1742                 }
1743
1744                 $arr = ['url' => $url, 'contact' => []];
1745
1746                 Hook::callAll('follow', $arr);
1747
1748                 if (empty($arr)) {
1749                         $result['message'] = L10n::t('The contact could not be added. Please check the relevant network credentials in your Settings -> Social Networks page.');
1750                         return $result;
1751                 }
1752
1753                 if (!empty($arr['contact']['name'])) {
1754                         $ret = $arr['contact'];
1755                 } else {
1756                         $ret = Probe::uri($url, $network, $uid, false);
1757                 }
1758
1759                 if (($network != '') && ($ret['network'] != $network)) {
1760                         Logger::log('Expected network ' . $network . ' does not match actual network ' . $ret['network']);
1761                         return $result;
1762                 }
1763
1764                 // check if we already have a contact
1765                 // the poll url is more reliable than the profile url, as we may have
1766                 // indirect links or webfinger links
1767
1768                 $condition = ['uid' => $uid, 'poll' => [$ret['poll'], Strings::normaliseLink($ret['poll'])], 'network' => $ret['network'], 'pending' => false];
1769                 $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
1770                 if (!DBA::isResult($contact)) {
1771                         $condition = ['uid' => $uid, 'nurl' => Strings::normaliseLink($url), 'network' => $ret['network'], 'pending' => false];
1772                         $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
1773                 }
1774
1775                 if (($ret['network'] === Protocol::DFRN) && !DBA::isResult($contact)) {
1776                         if ($interactive) {
1777                                 if (strlen($a->getURLPath())) {
1778                                         $myaddr = bin2hex(System::baseUrl() . '/profile/' . $a->user['nickname']);
1779                                 } else {
1780                                         $myaddr = bin2hex($a->user['nickname'] . '@' . $a->getHostName());
1781                                 }
1782
1783                                 $a->internalRedirect($ret['request'] . "&addr=$myaddr");
1784
1785                                 // NOTREACHED
1786                         }
1787                 } elseif (Config::get('system', 'dfrn_only') && ($ret['network'] != Protocol::DFRN)) {
1788                         $result['message'] = L10n::t('This site is not configured to allow communications with other networks.') . EOL;
1789                         $result['message'] .= L10n::t('No compatible communication protocols or feeds were discovered.') . EOL;
1790                         return $result;
1791                 }
1792
1793                 // This extra param just confuses things, remove it
1794                 if ($ret['network'] === Protocol::DIASPORA) {
1795                         $ret['url'] = str_replace('?absolute=true', '', $ret['url']);
1796                 }
1797
1798                 // do we have enough information?
1799                 if (empty($ret['name']) || empty($ret['poll']) || (empty($ret['url']) && empty($ret['addr']))) {
1800                         $result['message'] .= L10n::t('The profile address specified does not provide adequate information.') . EOL;
1801                         if (empty($ret['poll'])) {
1802                                 $result['message'] .= L10n::t('No compatible communication protocols or feeds were discovered.') . EOL;
1803                         }
1804                         if (empty($ret['name'])) {
1805                                 $result['message'] .= L10n::t('An author or name was not found.') . EOL;
1806                         }
1807                         if (empty($ret['url'])) {
1808                                 $result['message'] .= L10n::t('No browser URL could be matched to this address.') . EOL;
1809                         }
1810                         if (strpos($url, '@') !== false) {
1811                                 $result['message'] .= L10n::t('Unable to match @-style Identity Address with a known protocol or email contact.') . EOL;
1812                                 $result['message'] .= L10n::t('Use mailto: in front of address to force email check.') . EOL;
1813                         }
1814                         return $result;
1815                 }
1816
1817                 if ($ret['network'] === Protocol::OSTATUS && Config::get('system', 'ostatus_disabled')) {
1818                         $result['message'] .= L10n::t('The profile address specified belongs to a network which has been disabled on this site.') . EOL;
1819                         $ret['notify'] = '';
1820                 }
1821
1822                 if (!$ret['notify']) {
1823                         $result['message'] .= L10n::t('Limited profile. This person will be unable to receive direct/personal notifications from you.') . EOL;
1824                 }
1825
1826                 $writeable = ((($ret['network'] === Protocol::OSTATUS) && ($ret['notify'])) ? 1 : 0);
1827
1828                 $subhub = (($ret['network'] === Protocol::OSTATUS) ? true : false);
1829
1830                 $hidden = (($ret['network'] === Protocol::MAIL) ? 1 : 0);
1831
1832                 $pending = in_array($ret['network'], [Protocol::ACTIVITYPUB]);
1833
1834                 if (in_array($ret['network'], [Protocol::MAIL, Protocol::DIASPORA, Protocol::ACTIVITYPUB])) {
1835                         $writeable = 1;
1836                 }
1837
1838                 if (DBA::isResult($contact)) {
1839                         // update contact
1840                         $new_relation = (($contact['rel'] == self::FOLLOWER) ? self::FRIEND : self::SHARING);
1841
1842                         $fields = ['rel' => $new_relation, 'subhub' => $subhub, 'readonly' => false];
1843                         DBA::update('contact', $fields, ['id' => $contact['id']]);
1844                 } else {
1845                         $new_relation = (in_array($ret['network'], [Protocol::MAIL]) ? self::FRIEND : self::SHARING);
1846
1847                         // create contact record
1848                         DBA::insert('contact', [
1849                                 'uid'     => $uid,
1850                                 'created' => DateTimeFormat::utcNow(),
1851                                 'url'     => $ret['url'],
1852                                 'nurl'    => Strings::normaliseLink($ret['url']),
1853                                 'addr'    => $ret['addr'],
1854                                 'alias'   => $ret['alias'],
1855                                 'batch'   => $ret['batch'],
1856                                 'notify'  => $ret['notify'],
1857                                 'poll'    => $ret['poll'],
1858                                 'poco'    => $ret['poco'],
1859                                 'name'    => $ret['name'],
1860                                 'nick'    => $ret['nick'],
1861                                 'network' => $ret['network'],
1862                                 'pubkey'  => $ret['pubkey'],
1863                                 'rel'     => $new_relation,
1864                                 'priority'=> $ret['priority'],
1865                                 'writable'=> $writeable,
1866                                 'hidden'  => $hidden,
1867                                 'blocked' => 0,
1868                                 'readonly'=> 0,
1869                                 'pending' => $pending,
1870                                 'subhub'  => $subhub
1871                         ]);
1872                 }
1873
1874                 $contact = DBA::selectFirst('contact', [], ['url' => $ret['url'], 'network' => $ret['network'], 'uid' => $uid]);
1875                 if (!DBA::isResult($contact)) {
1876                         $result['message'] .= L10n::t('Unable to retrieve contact information.') . EOL;
1877                         return $result;
1878                 }
1879
1880                 $contact_id = $contact['id'];
1881                 $result['cid'] = $contact_id;
1882
1883                 Group::addMember(User::getDefaultGroup($uid, $contact["network"]), $contact_id);
1884
1885                 // Update the avatar
1886                 self::updateAvatar($ret['photo'], $uid, $contact_id);
1887
1888                 // pull feed and consume it, which should subscribe to the hub.
1889
1890                 Worker::add(PRIORITY_HIGH, "OnePoll", $contact_id, "force");
1891
1892                 $owner = User::getOwnerDataById($uid);
1893
1894                 if (DBA::isResult($owner)) {
1895                         if (in_array($contact['network'], [Protocol::OSTATUS, Protocol::DFRN])) {
1896                                 // create a follow slap
1897                                 $item = [];
1898                                 $item['verb'] = ACTIVITY_FOLLOW;
1899                                 $item['follow'] = $contact["url"];
1900                                 $item['body'] = '';
1901                                 $item['title'] = '';
1902                                 $item['guid'] = '';
1903                                 $item['tag'] = '';
1904                                 $item['attach'] = '';
1905
1906                                 $slap = OStatus::salmon($item, $owner);
1907
1908                                 if (!empty($contact['notify'])) {
1909                                         Salmon::slapper($owner, $contact['notify'], $slap);
1910                                 }
1911                         } elseif ($contact['network'] == Protocol::DIASPORA) {
1912                                 $ret = Diaspora::sendShare($a->user, $contact);
1913                                 Logger::log('share returns: ' . $ret);
1914                         } elseif ($contact['network'] == Protocol::ACTIVITYPUB) {
1915                                 $activity_id = ActivityPub\Transmitter::activityIDFromContact($contact_id);
1916                                 if (empty($activity_id)) {
1917                                         // This really should never happen
1918                                         return false;
1919                                 }
1920
1921                                 $ret = ActivityPub\Transmitter::sendActivity('Follow', $contact['url'], $uid, $activity_id);
1922                                 Logger::log('Follow returns: ' . $ret);
1923                         }
1924                 }
1925
1926                 $result['success'] = true;
1927                 return $result;
1928         }
1929
1930         /**
1931          * @brief Updated contact's SSL policy
1932          *
1933          * @param array  $contact    Contact array
1934          * @param string $new_policy New policy, valid: self,full
1935          *
1936          * @return array Contact array with updated values
1937          * @throws \Exception
1938          */
1939         public static function updateSslPolicy(array $contact, $new_policy)
1940         {
1941                 $ssl_changed = false;
1942                 if ((intval($new_policy) == BaseURL::SSL_POLICY_SELFSIGN || $new_policy === 'self') && strstr($contact['url'], 'https:')) {
1943                         $ssl_changed = true;
1944                         $contact['url']     =   str_replace('https:', 'http:', $contact['url']);
1945                         $contact['request'] =   str_replace('https:', 'http:', $contact['request']);
1946                         $contact['notify']  =   str_replace('https:', 'http:', $contact['notify']);
1947                         $contact['poll']    =   str_replace('https:', 'http:', $contact['poll']);
1948                         $contact['confirm'] =   str_replace('https:', 'http:', $contact['confirm']);
1949                         $contact['poco']    =   str_replace('https:', 'http:', $contact['poco']);
1950                 }
1951
1952                 if ((intval($new_policy) == BaseURL::SSL_POLICY_FULL || $new_policy === 'full') && strstr($contact['url'], 'http:')) {
1953                         $ssl_changed = true;
1954                         $contact['url']     =   str_replace('http:', 'https:', $contact['url']);
1955                         $contact['request'] =   str_replace('http:', 'https:', $contact['request']);
1956                         $contact['notify']  =   str_replace('http:', 'https:', $contact['notify']);
1957                         $contact['poll']    =   str_replace('http:', 'https:', $contact['poll']);
1958                         $contact['confirm'] =   str_replace('http:', 'https:', $contact['confirm']);
1959                         $contact['poco']    =   str_replace('http:', 'https:', $contact['poco']);
1960                 }
1961
1962                 if ($ssl_changed) {
1963                         $fields = ['url' => $contact['url'], 'request' => $contact['request'],
1964                                         'notify' => $contact['notify'], 'poll' => $contact['poll'],
1965                                         'confirm' => $contact['confirm'], 'poco' => $contact['poco']];
1966                         DBA::update('contact', $fields, ['id' => $contact['id']]);
1967                 }
1968
1969                 return $contact;
1970         }
1971
1972         public static function addRelationship($importer, $contact, $datarray, $item = '', $sharing = false) {
1973                 // Should always be set
1974                 if (empty($datarray['author-id'])) {
1975                         return;
1976                 }
1977
1978                 $fields = ['url', 'name', 'nick', 'photo', 'network'];
1979                 $pub_contact = DBA::selectFirst('contact', $fields, ['id' => $datarray['author-id']]);
1980                 if (!DBA::isResult($pub_contact)) {
1981                         // Should never happen
1982                         return;
1983                 }
1984
1985                 $url = defaults($datarray, 'author-link', $pub_contact['url']);
1986                 $name = $pub_contact['name'];
1987                 $photo = $pub_contact['photo'];
1988                 $nick = $pub_contact['nick'];
1989                 $network = $pub_contact['network'];
1990
1991                 if (is_array($contact)) {
1992                         if (($contact['rel'] == self::SHARING)
1993                                 || ($sharing && $contact['rel'] == self::FOLLOWER)) {
1994                                 DBA::update('contact', ['rel' => self::FRIEND, 'writable' => true],
1995                                                 ['id' => $contact['id'], 'uid' => $importer['uid']]);
1996                         }
1997
1998                         if ($contact['network'] == Protocol::ACTIVITYPUB) {
1999                                 ActivityPub\Transmitter::sendContactAccept($contact['url'], $contact['hub-verify'], $importer['uid']);
2000                         }
2001
2002                         // send email notification to owner?
2003                 } else {
2004                         if (DBA::exists('contact', ['nurl' => Strings::normaliseLink($url), 'uid' => $importer['uid'], 'pending' => true])) {
2005                                 Logger::log('ignoring duplicated connection request from pending contact ' . $url);
2006                                 return;
2007                         }
2008                         // create contact record
2009                         q("INSERT INTO `contact` (`uid`, `created`, `url`, `nurl`, `name`, `nick`, `photo`, `network`, `rel`,
2010                                 `blocked`, `readonly`, `pending`, `writable`)
2011                                 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, 0, 0, 1, 1)",
2012                                 intval($importer['uid']),
2013                                 DBA::escape(DateTimeFormat::utcNow()),
2014                                 DBA::escape($url),
2015                                 DBA::escape(Strings::normaliseLink($url)),
2016                                 DBA::escape($name),
2017                                 DBA::escape($nick),
2018                                 DBA::escape($photo),
2019                                 DBA::escape($network),
2020                                 intval(self::FOLLOWER)
2021                         );
2022
2023                         $contact_record = [
2024                                 'id' => DBA::lastInsertId(),
2025                                 'network' => $network,
2026                                 'name' => $name,
2027                                 'url' => $url,
2028                                 'photo' => $photo
2029                         ];
2030
2031                         Contact::updateAvatar($photo, $importer["uid"], $contact_record["id"], true);
2032
2033                         /// @TODO Encapsulate this into a function/method
2034                         $fields = ['uid', 'username', 'email', 'page-flags', 'notify-flags', 'language'];
2035                         $user = DBA::selectFirst('user', $fields, ['uid' => $importer['uid']]);
2036                         if (DBA::isResult($user) && !in_array($user['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_FREELOVE, User::PAGE_FLAGS_COMMUNITY])) {
2037                                 // create notification
2038                                 $hash = Strings::getRandomHex();
2039
2040                                 if (is_array($contact_record)) {
2041                                         DBA::insert('intro', ['uid' => $importer['uid'], 'contact-id' => $contact_record['id'],
2042                                                                 'blocked' => false, 'knowyou' => false,
2043                                                                 'hash' => $hash, 'datetime' => DateTimeFormat::utcNow()]);
2044                                 }
2045
2046                                 Group::addMember(User::getDefaultGroup($importer['uid'], $contact_record["network"]), $contact_record['id']);
2047
2048                                 if (($user['notify-flags'] & NOTIFY_INTRO) &&
2049                                         in_array($user['page-flags'], [User::PAGE_FLAGS_NORMAL])) {
2050
2051                                         notification([
2052                                                 'type'         => NOTIFY_INTRO,
2053                                                 'notify_flags' => $user['notify-flags'],
2054                                                 'language'     => $user['language'],
2055                                                 'to_name'      => $user['username'],
2056                                                 'to_email'     => $user['email'],
2057                                                 'uid'          => $user['uid'],
2058                                                 'link'         => System::baseUrl() . '/notifications/intro',
2059                                                 'source_name'  => ((strlen(stripslashes($contact_record['name']))) ? stripslashes($contact_record['name']) : L10n::t('[Name Withheld]')),
2060                                                 'source_link'  => $contact_record['url'],
2061                                                 'source_photo' => $contact_record['photo'],
2062                                                 'verb'         => ($sharing ? ACTIVITY_FRIEND : ACTIVITY_FOLLOW),
2063                                                 'otype'        => 'intro'
2064                                         ]);
2065
2066                                 }
2067                         } elseif (DBA::isResult($user) && in_array($user['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_FREELOVE, User::PAGE_FLAGS_COMMUNITY])) {
2068                                 $condition = ['uid' => $importer['uid'], 'url' => $url, 'pending' => true];
2069                                 DBA::update('contact', ['pending' => false], $condition);
2070
2071                                 $contact = DBA::selectFirst('contact', ['url', 'network', 'hub-verify'], ['id' => $contact_record['id']]);
2072
2073                                 if ($contact['network'] == Protocol::ACTIVITYPUB) {
2074                                         ActivityPub\Transmitter::sendContactAccept($contact['url'], $contact['hub-verify'], $importer['uid']);
2075                                 }
2076                         }
2077                 }
2078         }
2079
2080         public static function removeFollower($importer, $contact, array $datarray = [], $item = "")
2081         {
2082                 if (($contact['rel'] == self::FRIEND) || ($contact['rel'] == self::SHARING)) {
2083                         DBA::update('contact', ['rel' => self::SHARING], ['id' => $contact['id']]);
2084                 } else {
2085                         Contact::remove($contact['id']);
2086                 }
2087         }
2088
2089         public static function removeSharer($importer, $contact, array $datarray = [], $item = "")
2090         {
2091                 if (($contact['rel'] == self::FRIEND) || ($contact['rel'] == self::FOLLOWER)) {
2092                         DBA::update('contact', ['rel' => self::FOLLOWER], ['id' => $contact['id']]);
2093                 } else {
2094                         Contact::remove($contact['id']);
2095                 }
2096         }
2097
2098         /**
2099          * @brief Create a birthday event.
2100          *
2101          * Update the year and the birthday.
2102          */
2103         public static function updateBirthdays()
2104         {
2105                 $condition = [
2106                         '`bd` != ""
2107                         AND `bd` > "0001-01-01"
2108                         AND SUBSTRING(`bd`, 1, 4) != `bdyear`
2109                         AND (`contact`.`rel` = ? OR `contact`.`rel` = ?)
2110                         AND NOT `contact`.`pending`
2111                         AND NOT `contact`.`hidden`
2112                         AND NOT `contact`.`blocked`
2113                         AND NOT `contact`.`archive`
2114                         AND NOT `contact`.`deleted`',
2115                         Contact::SHARING,
2116                         Contact::FRIEND
2117                 ];
2118
2119                 $contacts = DBA::select('contact', ['id', 'uid', 'name', 'url', 'bd'], $condition);
2120
2121                 while ($contact = DBA::fetch($contacts)) {
2122                         Logger::log('update_contact_birthday: ' . $contact['bd']);
2123
2124                         $nextbd = DateTimeFormat::utcNow('Y') . substr($contact['bd'], 4);
2125
2126                         if (Event::createBirthday($contact, $nextbd)) {
2127                                 // update bdyear
2128                                 DBA::update(
2129                                         'contact',
2130                                         ['bdyear' => substr($nextbd, 0, 4), 'bd' => $nextbd],
2131                                         ['id' => $contact['id']]
2132                                 );
2133                         }
2134                 }
2135         }
2136
2137         /**
2138          * Remove the unavailable contact ids from the provided list
2139          *
2140          * @param array $contact_ids Contact id list
2141          * @throws \Exception
2142          */
2143         public static function pruneUnavailable(array &$contact_ids)
2144         {
2145                 if (empty($contact_ids)) {
2146                         return;
2147                 }
2148
2149                 $str = DBA::escape(implode(',', $contact_ids));
2150
2151                 $stmt = DBA::p("SELECT `id` FROM `contact` WHERE `id` IN ( " . $str . ") AND `blocked` = 0 AND `pending` = 0 AND `archive` = 0");
2152
2153                 $return = [];
2154                 while($contact = DBA::fetch($stmt)) {
2155                         $return[] = $contact['id'];
2156                 }
2157
2158                 DBA::close($stmt);
2159
2160                 $contact_ids = $return;
2161         }
2162
2163         /**
2164          * @brief Returns a magic link to authenticate remote visitors
2165          *
2166          * @todo  check if the return is either a fully qualified URL or a relative path to Friendica basedir
2167          *
2168          * @param string $contact_url The address of the target contact profile
2169          * @param string $url         An url that we will be redirected to after the authentication
2170          *
2171          * @return string with "redir" link
2172          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2173          * @throws \ImagickException
2174          */
2175         public static function magicLink($contact_url, $url = '')
2176         {
2177                 if (!local_user() && !remote_user()) {
2178                         return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
2179                 }
2180
2181                 $cid = self::getIdForURL($contact_url, 0, true);
2182                 if (empty($cid)) {
2183                         return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
2184                 }
2185
2186                 return self::magicLinkbyId($cid, $url);
2187         }
2188
2189         /**
2190          * @brief Returns a magic link to authenticate remote visitors
2191          *
2192          * @param integer $cid The contact id of the target contact profile
2193          * @param string  $url An url that we will be redirected to after the authentication
2194          *
2195          * @return string with "redir" link
2196          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2197          * @throws \ImagickException
2198          */
2199         public static function magicLinkbyId($cid, $url = '')
2200         {
2201                 $contact = DBA::selectFirst('contact', ['id', 'network', 'url', 'uid'], ['id' => $cid]);
2202
2203                 return self::magicLinkByContact($contact, $url);
2204         }
2205
2206         /**
2207          * @brief Returns a magic link to authenticate remote visitors
2208          *
2209          * @param array  $contact The contact array with "uid", "network" and "url"
2210          * @param string $url     An url that we will be redirected to after the authentication
2211          *
2212          * @return string with "redir" link
2213          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2214          * @throws \ImagickException
2215          */
2216         public static function magicLinkByContact($contact, $url = '')
2217         {
2218                 if ((!local_user() && !remote_user()) || ($contact['network'] != Protocol::DFRN)) {
2219                         return $url ?: $contact['url']; // Equivalent to ($url != '') ? $url : $contact['url'];
2220                 }
2221
2222                 // Only redirections to the same host do make sense
2223                 if (($url != '') && (parse_url($url, PHP_URL_HOST) != parse_url($contact['url'], PHP_URL_HOST))) {
2224                         return $url;
2225                 }
2226
2227                 if ($contact['uid'] != 0) {
2228                         return self::magicLink($contact['url'], $url);
2229                 }
2230
2231                 $redirect = 'redir/' . $contact['id'];
2232
2233                 if ($url != '') {
2234                         $redirect .= '?url=' . $url;
2235                 }
2236
2237                 return $redirect;
2238         }
2239
2240         /**
2241          * Remove a contact from all groups
2242          *
2243          * @param integer $contact_id
2244          *
2245          * @return boolean Success
2246          */
2247         public static function removeFromGroups($contact_id)
2248         {
2249                 return DBA::delete('group_member', ['contact-id' => $contact_id]);
2250         }
2251
2252         /**
2253          * Is the contact a forum?
2254          *
2255          * @param integer $contactid ID of the contact
2256          *
2257          * @return boolean "true" if it is a forum
2258          */
2259         public static function isForum($contactid)
2260         {
2261                 $fields = ['forum', 'prv'];
2262                 $condition = ['id' => $contactid];
2263                 $contact = DBA::selectFirst('contact', $fields, $condition);
2264                 if (!DBA::isResult($contact)) {
2265                         return false;
2266                 }
2267
2268                 // Is it a forum?
2269                 return ($contact['forum'] || $contact['prv']);
2270         }
2271 }