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