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