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