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