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