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