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