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