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