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