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