]> git.mxchange.org Git - friendica.git/blob - src/Model/Contact.php
"Contact\User" class created
[friendica.git] / src / Model / Contact.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2020, Friendica
4  *
5  * @license GNU AGPL version 3 or any later version
6  *
7  * This program is free software: you can redistribute it and/or modify
8  * it under the terms of the GNU Affero General Public License as
9  * published by the Free Software Foundation, either version 3 of the
10  * License, or (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU Affero General Public License for more details.
16  *
17  * You should have received a copy of the GNU Affero General Public License
18  * along with this program.  If not, see <https://www.gnu.org/licenses/>.
19  *
20  */
21
22 namespace Friendica\Model;
23
24 use DOMDocument;
25 use DOMXPath;
26 use Friendica\App\BaseURL;
27 use Friendica\Content\Pager;
28 use Friendica\Core\Hook;
29 use Friendica\Core\Logger;
30 use Friendica\Core\Protocol;
31 use Friendica\Core\Session;
32 use Friendica\Core\System;
33 use Friendica\Core\Worker;
34 use Friendica\Database\DBA;
35 use Friendica\DI;
36 use Friendica\Model\Notify\Type;
37 use Friendica\Network\HTTPException;
38 use Friendica\Network\Probe;
39 use Friendica\Protocol\Activity;
40 use Friendica\Protocol\ActivityPub;
41 use Friendica\Protocol\DFRN;
42 use Friendica\Protocol\Diaspora;
43 use Friendica\Protocol\OStatus;
44 use Friendica\Protocol\Salmon;
45 use Friendica\Util\DateTimeFormat;
46 use Friendica\Util\Images;
47 use Friendica\Util\Network;
48 use Friendica\Util\Proxy;
49 use Friendica\Util\Strings;
50
51 /**
52  * functions for interacting with a contact
53  */
54 class Contact
55 {
56         /**
57          * @deprecated since version 2019.03
58          * @see User::PAGE_FLAGS_NORMAL
59          */
60         const PAGE_NORMAL    = User::PAGE_FLAGS_NORMAL;
61         /**
62          * @deprecated since version 2019.03
63          * @see User::PAGE_FLAGS_SOAPBOX
64          */
65         const PAGE_SOAPBOX   = User::PAGE_FLAGS_SOAPBOX;
66         /**
67          * @deprecated since version 2019.03
68          * @see User::PAGE_FLAGS_COMMUNITY
69          */
70         const PAGE_COMMUNITY = User::PAGE_FLAGS_COMMUNITY;
71         /**
72          * @deprecated since version 2019.03
73          * @see User::PAGE_FLAGS_FREELOVE
74          */
75         const PAGE_FREELOVE  = User::PAGE_FLAGS_FREELOVE;
76         /**
77          * @deprecated since version 2019.03
78          * @see User::PAGE_FLAGS_BLOG
79          */
80         const PAGE_BLOG      = User::PAGE_FLAGS_BLOG;
81         /**
82          * @deprecated since version 2019.03
83          * @see User::PAGE_FLAGS_PRVGROUP
84          */
85         const PAGE_PRVGROUP  = User::PAGE_FLAGS_PRVGROUP;
86         /**
87          * @}
88          */
89
90         /**
91          * Account types
92          *
93          * TYPE_UNKNOWN - unknown type
94          *
95          * TYPE_PERSON - the account belongs to a person
96          *      Associated page types: PAGE_NORMAL, PAGE_SOAPBOX, PAGE_FREELOVE
97          *
98          * TYPE_ORGANISATION - the account belongs to an organisation
99          *      Associated page type: PAGE_SOAPBOX
100          *
101          * TYPE_NEWS - the account is a news reflector
102          *      Associated page type: PAGE_SOAPBOX
103          *
104          * TYPE_COMMUNITY - the account is community forum
105          *      Associated page types: PAGE_COMMUNITY, PAGE_PRVGROUP
106          *
107          * TYPE_RELAY - the account is a relay
108          *      This will only be assigned to contacts, not to user accounts
109          * @{
110          */
111         const TYPE_UNKNOWN =     -1;
112         const TYPE_PERSON =       User::ACCOUNT_TYPE_PERSON;
113         const TYPE_ORGANISATION = User::ACCOUNT_TYPE_ORGANISATION;
114         const TYPE_NEWS =         User::ACCOUNT_TYPE_NEWS;
115         const TYPE_COMMUNITY =    User::ACCOUNT_TYPE_COMMUNITY;
116         const TYPE_RELAY =        User::ACCOUNT_TYPE_RELAY;
117         /**
118          * @}
119          */
120
121         /**
122          * Contact_is
123          *
124          * Relationship types
125          * @{
126          */
127         const FOLLOWER = 1;
128         const SHARING  = 2;
129         const FRIEND   = 3;
130         /**
131          * @}
132          */
133
134         /**
135          * @param array $fields    Array of selected fields, empty for all
136          * @param array $condition Array of fields for condition
137          * @param array $params    Array of several parameters
138          * @return array
139          * @throws \Exception
140          */
141         public static function selectToArray(array $fields = [], array $condition = [], array $params = [])
142         {
143                 return DBA::selectToArray('contact', $fields, $condition, $params);
144         }
145
146         /**
147          * @param array $fields    Array of selected fields, empty for all
148          * @param array $condition Array of fields for condition
149          * @param array $params    Array of several parameters
150          * @return array
151          * @throws \Exception
152          */
153         public static function selectFirst(array $fields = [], array $condition = [], array $params = [])
154         {
155                 $contact = DBA::selectFirst('contact', $fields, $condition, $params);
156
157                 return $contact;
158         }
159
160         /**
161          * Insert a row into the contact table
162          * Important: You can't use DBA::lastInsertId() after this call since it will be set to 0.
163          *
164          * @param array        $fields              field array
165          * @param bool         $on_duplicate_update Do an update on a duplicate entry
166          *
167          * @return boolean was the insert successful?
168          * @throws \Exception
169          */
170         public static function insert(array $fields, bool $on_duplicate_update = false)
171         {
172                 $ret = DBA::insert('contact', $fields, $on_duplicate_update);
173                 $contact = DBA::selectFirst('contact', ['nurl', 'uid'], ['id' => DBA::lastInsertId()]);
174                 if (!DBA::isResult($contact)) {
175                         // Shouldn't happen
176                         return $ret;
177                 }
178
179                 // Search for duplicated contacts and get rid of them
180                 self::removeDuplicates($contact['nurl'], $contact['uid']);
181
182                 return $ret;
183         }
184
185         /**
186          * @param integer $id     Contact ID
187          * @param array   $fields Array of selected fields, empty for all
188          * @return array|boolean Contact record if it exists, false otherwise
189          * @throws \Exception
190          */
191         public static function getById($id, $fields = [])
192         {
193                 return DBA::selectFirst('contact', $fields, ['id' => $id]);
194         }
195
196         /**
197          * Fetches a contact by a given url
198          *
199          * @param string  $url    profile url
200          * @param boolean $update true = always update, false = never update, null = update when not found or outdated
201          * @param array   $fields Field list
202          * @param integer $uid    User ID of the contact
203          * @return array contact array
204          */
205         public static function getByURL(string $url, $update = null, array $fields = [], int $uid = 0)
206         {
207                 if ($update || is_null($update)) {
208                         $cid = self::getIdForURL($url, $uid, $update);
209                         if (empty($cid)) {
210                                 return [];
211                         }
212
213                         $contact = self::getById($cid, $fields);
214                         if (empty($contact)) {
215                                 return [];
216                         }
217                         return $contact;
218                 }
219
220                 // Add internal fields
221                 $removal = [];
222                 if (!empty($fields)) {
223                         foreach (['id', 'updated', 'network'] as $internal) {
224                                 if (!in_array($internal, $fields)) {
225                                         $fields[] = $internal;
226                                         $removal[] = $internal;
227                                 }
228                         }
229                 }
230
231                 // We first try the nurl (http://server.tld/nick), most common case
232                 $options = ['order' => ['id']];
233                 $contact = DBA::selectFirst('contact', $fields, ['nurl' => Strings::normaliseLink($url), 'uid' => $uid, 'deleted' => false], $options);
234
235                 // Then the addr (nick@server.tld)
236                 if (!DBA::isResult($contact)) {
237                         $contact = DBA::selectFirst('contact', $fields, ['addr' => str_replace('acct:', '', $url), 'uid' => $uid, 'deleted' => false], $options);
238                 }
239
240                 // Then the alias (which could be anything)
241                 if (!DBA::isResult($contact)) {
242                         // The link could be provided as http although we stored it as https
243                         $ssl_url = str_replace('http://', 'https://', $url);
244                         $condition = ['`alias` IN (?, ?, ?) AND `uid` = ? AND NOT `deleted`', $url, Strings::normaliseLink($url), $ssl_url, $uid];
245                         $contact = DBA::selectFirst('contact', $fields, $condition, $options);
246                 }
247                 
248                 if (!DBA::isResult($contact)) {
249                         return [];
250                 }
251
252                 // Update the contact in the background if needed
253                 if ((($contact['updated'] < DateTimeFormat::utc('now -7 days')) || empty($contact['avatar'])) &&
254                         in_array($contact['network'], Protocol::FEDERATED)) {
255                         Worker::add(PRIORITY_LOW, "UpdateContact", $contact['id'], ($uid == 0 ? 'force' : ''));
256                 }
257
258                 // Remove the internal fields
259                 foreach ($removal as $internal) {
260                         unset($contact[$internal]);
261                 }
262
263                 return $contact;
264         }
265
266         /**
267          * Fetches a contact for a given user by a given url.
268          * In difference to "getByURL" the function will fetch a public contact when no user contact had been found.
269          *
270          * @param string  $url    profile url
271          * @param integer $uid    User ID of the contact
272          * @param boolean $update true = always update, false = never update, null = update when not found or outdated
273          * @param array   $fields Field list
274          * @return array contact array
275          */
276         public static function getByURLForUser(string $url, int $uid = 0, $update = false, array $fields = [])
277         {
278                 if ($uid != 0) {
279                         $contact = self::getByURL($url, $update, $fields, $uid);
280                         if (!empty($contact)) {
281                                 if (!empty($contact['id'])) {
282                                         $contact['cid'] = $contact['id'];
283                                         $contact['zid'] = 0;
284                                 }
285                                 return $contact;
286                         }
287                 }
288
289                 $contact = self::getByURL($url, $update, $fields);
290                 if (!empty($contact['id'])) {           
291                         $contact['cid'] = 0;
292                         $contact['zid'] = $contact['id'];
293                 }
294                 return $contact;
295         }
296
297         /**
298          * Tests if the given contact is a follower
299          *
300          * @param int $cid Either public contact id or user's contact id
301          * @param int $uid User ID
302          *
303          * @return boolean is the contact id a follower?
304          * @throws HTTPException\InternalServerErrorException
305          * @throws \ImagickException
306          */
307         public static function isFollower($cid, $uid)
308         {
309                 if (Contact\User::isBlocked($cid, $uid)) {
310                         return false;
311                 }
312
313                 $cdata = self::getPublicAndUserContacID($cid, $uid);
314                 if (empty($cdata['user'])) {
315                         return false;
316                 }
317
318                 $condition = ['id' => $cdata['user'], 'rel' => [self::FOLLOWER, self::FRIEND]];
319                 return DBA::exists('contact', $condition);
320         }
321
322         /**
323          * Tests if the given contact url is a follower
324          *
325          * @param string $url Contact URL
326          * @param int    $uid User ID
327          *
328          * @return boolean is the contact id a follower?
329          * @throws HTTPException\InternalServerErrorException
330          * @throws \ImagickException
331          */
332         public static function isFollowerByURL($url, $uid)
333         {
334                 $cid = self::getIdForURL($url, $uid, false);
335
336                 if (empty($cid)) {
337                         return false;
338                 }
339
340                 return self::isFollower($cid, $uid);
341         }
342
343         /**
344          * Tests if the given user follow the given contact
345          *
346          * @param int $cid Either public contact id or user's contact id
347          * @param int $uid User ID
348          *
349          * @return boolean is the contact url being followed?
350          * @throws HTTPException\InternalServerErrorException
351          * @throws \ImagickException
352          */
353         public static function isSharing($cid, $uid)
354         {
355                 if (Contact\User::isBlocked($cid, $uid)) {
356                         return false;
357                 }
358
359                 $cdata = self::getPublicAndUserContacID($cid, $uid);
360                 if (empty($cdata['user'])) {
361                         return false;
362                 }
363
364                 $condition = ['id' => $cdata['user'], 'rel' => [self::SHARING, self::FRIEND]];
365                 return DBA::exists('contact', $condition);
366         }
367
368         /**
369          * Tests if the given user follow the given contact url
370          *
371          * @param string $url Contact URL
372          * @param int    $uid User ID
373          *
374          * @return boolean is the contact url being followed?
375          * @throws HTTPException\InternalServerErrorException
376          * @throws \ImagickException
377          */
378         public static function isSharingByURL($url, $uid)
379         {
380                 $cid = self::getIdForURL($url, $uid, false);
381
382                 if (empty($cid)) {
383                         return false;
384                 }
385
386                 return self::isSharing($cid, $uid);
387         }
388
389         /**
390          * Get the basepath for a given contact link
391          *
392          * @param string $url The contact link
393          * @param boolean $dont_update Don't update the contact
394          *
395          * @return string basepath
396          * @throws HTTPException\InternalServerErrorException
397          * @throws \ImagickException
398          */
399         public static function getBasepath($url, $dont_update = false)
400         {
401                 $contact = DBA::selectFirst('contact', ['id', 'baseurl'], ['uid' => 0, 'nurl' => Strings::normaliseLink($url)]);
402                 if (!DBA::isResult($contact)) {
403                         return '';
404                 }
405
406                 if (!empty($contact['baseurl'])) {
407                         return $contact['baseurl'];
408                 } elseif ($dont_update) {
409                         return '';
410                 }
411
412                 // Update the existing contact
413                 self::updateFromProbe($contact['id'], '', true);
414
415                 // And fetch the result
416                 $contact = DBA::selectFirst('contact', ['baseurl'], ['id' => $contact['id']]);
417                 if (empty($contact['baseurl'])) {
418                         Logger::info('No baseurl for contact', ['url' => $url]);
419                         return '';
420                 }
421
422                 Logger::info('Found baseurl for contact', ['url' => $url, 'baseurl' => $contact['baseurl']]);
423                 return $contact['baseurl'];
424         }
425
426         /**
427          * Check if the given contact url is on the same server
428          *
429          * @param string $url The contact link
430          *
431          * @return boolean Is it the same server?
432          */
433         public static function isLocal($url)
434         {
435                 return Strings::compareLink(self::getBasepath($url, true), DI::baseUrl());
436         }
437
438         /**
439          * Check if the given contact ID is on the same server
440          *
441          * @param string $url The contact link
442          *
443          * @return boolean Is it the same server?
444          */
445         public static function isLocalById(int $cid)
446         {
447                 $contact = DBA::selectFirst('contact', ['url', 'baseurl'], ['id' => $cid]);
448                 if (!DBA::isResult($contact)) {
449                         return false;
450                 }
451
452                 if (empty($contact['baseurl'])) {
453                         $baseurl = self::getBasepath($contact['url'], true);
454                 } else {
455                         $baseurl = $contact['baseurl'];
456                 }
457
458                 return Strings::compareLink($baseurl, DI::baseUrl());
459         }
460
461         /**
462          * Returns the public contact id of the given user id
463          *
464          * @param  integer $uid User ID
465          *
466          * @return integer|boolean Public contact id for given user id
467          * @throws \Exception
468          */
469         public static function getPublicIdByUserId($uid)
470         {
471                 $self = DBA::selectFirst('contact', ['url'], ['self' => true, 'uid' => $uid]);
472                 if (!DBA::isResult($self)) {
473                         return false;
474                 }
475                 return self::getIdForURL($self['url'], 0, false);
476         }
477
478         /**
479          * Returns the contact id for the user and the public contact id for a given contact id
480          *
481          * @param int $cid Either public contact id or user's contact id
482          * @param int $uid User ID
483          *
484          * @return array with public and user's contact id
485          * @throws HTTPException\InternalServerErrorException
486          * @throws \ImagickException
487          */
488         public static function getPublicAndUserContacID($cid, $uid)
489         {
490                 if (empty($uid) || empty($cid)) {
491                         return [];
492                 }
493
494                 $contact = DBA::selectFirst('contact', ['id', 'uid', 'url'], ['id' => $cid]);
495                 if (!DBA::isResult($contact)) {
496                         return [];
497                 }
498
499                 // We quit when the user id don't match the user id of the provided contact
500                 if (($contact['uid'] != $uid) && ($contact['uid'] != 0)) {
501                         return [];
502                 }
503
504                 if ($contact['uid'] != 0) {
505                         $pcid = Contact::getIdForURL($contact['url'], 0, false, ['url' => $contact['url']]);
506                         if (empty($pcid)) {
507                                 return [];
508                         }
509                         $ucid = $contact['id'];
510                 } else {
511                         $pcid = $contact['id'];
512                         $ucid = Contact::getIdForURL($contact['url'], $uid, false);
513                 }
514
515                 return ['public' => $pcid, 'user' => $ucid];
516         }
517
518         /**
519          * Returns contact details for a given contact id in combination with a user id
520          *
521          * @param int $cid A contact ID
522          * @param int $uid The User ID
523          * @param array $fields The selected fields for the contact
524          *
525          * @return array The contact details
526          *
527          * @throws \Exception
528          */
529         public static function getContactForUser($cid, $uid, array $fields = [])
530         {
531                 $contact = DBA::selectFirst('contact', $fields, ['id' => $cid, 'uid' => $uid]);
532
533                 if (!DBA::isResult($contact)) {
534                         return [];
535                 } else {
536                         return $contact;
537                 }
538         }
539
540         /**
541          * Returns a list of contacts belonging in a group
542          *
543          * @param int $gid
544          * @return array
545          * @throws \Exception
546          */
547         public static function getByGroupId($gid)
548         {
549                 $return = [];
550
551                 if (intval($gid)) {
552                         $stmt = DBA::p('SELECT `group_member`.`contact-id`, `contact`.*
553                                 FROM `contact`
554                                 INNER JOIN `group_member`
555                                         ON `contact`.`id` = `group_member`.`contact-id`
556                                 WHERE `gid` = ?
557                                 AND `contact`.`uid` = ?
558                                 AND NOT `contact`.`self`
559                                 AND NOT `contact`.`deleted`
560                                 AND NOT `contact`.`blocked`
561                                 AND NOT `contact`.`pending`
562                                 ORDER BY `contact`.`name` ASC',
563                                 $gid,
564                                 local_user()
565                         );
566
567                         if (DBA::isResult($stmt)) {
568                                 $return = DBA::toArray($stmt);
569                         }
570                 }
571
572                 return $return;
573         }
574
575         /**
576          * Creates the self-contact for the provided user id
577          *
578          * @param int $uid
579          * @return bool Operation success
580          * @throws HTTPException\InternalServerErrorException
581          */
582         public static function createSelfFromUserId($uid)
583         {
584                 // Only create the entry if it doesn't exist yet
585                 if (DBA::exists('contact', ['uid' => $uid, 'self' => true])) {
586                         return true;
587                 }
588
589                 $user = DBA::selectFirst('user', ['uid', 'username', 'nickname'], ['uid' => $uid]);
590                 if (!DBA::isResult($user)) {
591                         return false;
592                 }
593
594                 $return = DBA::insert('contact', [
595                         'uid'         => $user['uid'],
596                         'created'     => DateTimeFormat::utcNow(),
597                         'self'        => 1,
598                         'name'        => $user['username'],
599                         'nick'        => $user['nickname'],
600                         'photo'       => DI::baseUrl() . '/photo/profile/' . $user['uid'] . '.jpg',
601                         'thumb'       => DI::baseUrl() . '/photo/avatar/'  . $user['uid'] . '.jpg',
602                         'micro'       => DI::baseUrl() . '/photo/micro/'   . $user['uid'] . '.jpg',
603                         'blocked'     => 0,
604                         'pending'     => 0,
605                         'url'         => DI::baseUrl() . '/profile/' . $user['nickname'],
606                         'nurl'        => Strings::normaliseLink(DI::baseUrl() . '/profile/' . $user['nickname']),
607                         'addr'        => $user['nickname'] . '@' . substr(DI::baseUrl(), strpos(DI::baseUrl(), '://') + 3),
608                         'request'     => DI::baseUrl() . '/dfrn_request/' . $user['nickname'],
609                         'notify'      => DI::baseUrl() . '/dfrn_notify/'  . $user['nickname'],
610                         'poll'        => DI::baseUrl() . '/dfrn_poll/'    . $user['nickname'],
611                         'confirm'     => DI::baseUrl() . '/dfrn_confirm/' . $user['nickname'],
612                         'poco'        => DI::baseUrl() . '/poco/'         . $user['nickname'],
613                         'name-date'   => DateTimeFormat::utcNow(),
614                         'uri-date'    => DateTimeFormat::utcNow(),
615                         'avatar-date' => DateTimeFormat::utcNow(),
616                         'closeness'   => 0
617                 ]);
618
619                 return $return;
620         }
621
622         /**
623          * Updates the self-contact for the provided user id
624          *
625          * @param int     $uid
626          * @param boolean $update_avatar Force the avatar update
627          * @throws HTTPException\InternalServerErrorException
628          */
629         public static function updateSelfFromUserID($uid, $update_avatar = false)
630         {
631                 $fields = ['id', 'name', 'nick', 'location', 'about', 'keywords', 'avatar',
632                         'xmpp', 'contact-type', 'forum', 'prv', 'avatar-date', 'url', 'nurl', 'unsearchable',
633                         'photo', 'thumb', 'micro', 'addr', 'request', 'notify', 'poll', 'confirm', 'poco'];
634                 $self = DBA::selectFirst('contact', $fields, ['uid' => $uid, 'self' => true]);
635                 if (!DBA::isResult($self)) {
636                         return;
637                 }
638
639                 $fields = ['nickname', 'page-flags', 'account-type'];
640                 $user = DBA::selectFirst('user', $fields, ['uid' => $uid]);
641                 if (!DBA::isResult($user)) {
642                         return;
643                 }
644
645                 $fields = ['name', 'photo', 'thumb', 'about', 'address', 'locality', 'region',
646                         'country-name', 'pub_keywords', 'xmpp', 'net-publish'];
647                 $profile = DBA::selectFirst('profile', $fields, ['uid' => $uid]);
648                 if (!DBA::isResult($profile)) {
649                         return;
650                 }
651
652                 $file_suffix = 'jpg';
653
654                 $fields = ['name' => $profile['name'], 'nick' => $user['nickname'],
655                         'avatar-date' => $self['avatar-date'], 'location' => Profile::formatLocation($profile),
656                         'about' => $profile['about'], 'keywords' => $profile['pub_keywords'],
657                         'contact-type' => $user['account-type'],
658                         'xmpp' => $profile['xmpp']];
659
660                 $avatar = Photo::selectFirst(['resource-id', 'type'], ['uid' => $uid, 'profile' => true]);
661                 if (DBA::isResult($avatar)) {
662                         if ($update_avatar) {
663                                 $fields['avatar-date'] = DateTimeFormat::utcNow();
664                         }
665
666                         // Creating the path to the avatar, beginning with the file suffix
667                         $types = Images::supportedTypes();
668                         if (isset($types[$avatar['type']])) {
669                                 $file_suffix = $types[$avatar['type']];
670                         }
671
672                         // We are adding a timestamp value so that other systems won't use cached content
673                         $timestamp = strtotime($fields['avatar-date']);
674
675                         $prefix = DI::baseUrl() . '/photo/' .$avatar['resource-id'] . '-';
676                         $suffix = '.' . $file_suffix . '?ts=' . $timestamp;
677
678                         $fields['photo'] = $prefix . '4' . $suffix;
679                         $fields['thumb'] = $prefix . '5' . $suffix;
680                         $fields['micro'] = $prefix . '6' . $suffix;
681                 } else {
682                         // We hadn't found a photo entry, so we use the default avatar
683                         $fields['photo'] = DI::baseUrl() . '/images/person-300.jpg';
684                         $fields['thumb'] = DI::baseUrl() . '/images/person-80.jpg';
685                         $fields['micro'] = DI::baseUrl() . '/images/person-48.jpg';
686                 }
687
688                 $fields['avatar'] = DI::baseUrl() . '/photo/profile/' .$uid . '.' . $file_suffix;
689                 $fields['forum'] = $user['page-flags'] == User::PAGE_FLAGS_COMMUNITY;
690                 $fields['prv'] = $user['page-flags'] == User::PAGE_FLAGS_PRVGROUP;
691                 $fields['unsearchable'] = !$profile['net-publish'];
692
693                 // it seems as if ported accounts can have wrong values, so we make sure that now everything is fine.
694                 $fields['url'] = DI::baseUrl() . '/profile/' . $user['nickname'];
695                 $fields['nurl'] = Strings::normaliseLink($fields['url']);
696                 $fields['addr'] = $user['nickname'] . '@' . substr(DI::baseUrl(), strpos(DI::baseUrl(), '://') + 3);
697                 $fields['request'] = DI::baseUrl() . '/dfrn_request/' . $user['nickname'];
698                 $fields['notify'] = DI::baseUrl() . '/dfrn_notify/' . $user['nickname'];
699                 $fields['poll'] = DI::baseUrl() . '/dfrn_poll/'. $user['nickname'];
700                 $fields['confirm'] = DI::baseUrl() . '/dfrn_confirm/' . $user['nickname'];
701                 $fields['poco'] = DI::baseUrl() . '/poco/' . $user['nickname'];
702
703                 $update = false;
704
705                 foreach ($fields as $field => $content) {
706                         if ($self[$field] != $content) {
707                                 $update = true;
708                         }
709                 }
710
711                 if ($update) {
712                         if ($fields['name'] != $self['name']) {
713                                 $fields['name-date'] = DateTimeFormat::utcNow();
714                         }
715                         $fields['updated'] = DateTimeFormat::utcNow();
716                         DBA::update('contact', $fields, ['id' => $self['id']]);
717
718                         // Update the public contact as well
719                         DBA::update('contact', $fields, ['uid' => 0, 'nurl' => $self['nurl']]);
720
721                         // Update the profile
722                         $fields = ['photo' => DI::baseUrl() . '/photo/profile/' .$uid . '.' . $file_suffix,
723                                 'thumb' => DI::baseUrl() . '/photo/avatar/' . $uid .'.' . $file_suffix];
724                         DBA::update('profile', $fields, ['uid' => $uid]);
725                 }
726         }
727
728         /**
729          * Marks a contact for removal
730          *
731          * @param int $id contact id
732          * @return null
733          * @throws HTTPException\InternalServerErrorException
734          */
735         public static function remove($id)
736         {
737                 // We want just to make sure that we don't delete our "self" contact
738                 $contact = DBA::selectFirst('contact', ['uid'], ['id' => $id, 'self' => false]);
739                 if (!DBA::isResult($contact) || !intval($contact['uid'])) {
740                         return;
741                 }
742
743                 // Archive the contact
744                 DBA::update('contact', ['archive' => true, 'network' => Protocol::PHANTOM, 'deleted' => true], ['id' => $id]);
745
746                 // Delete it in the background
747                 Worker::add(PRIORITY_MEDIUM, 'RemoveContact', $id);
748         }
749
750         /**
751          * Sends an unfriend message. Does not remove the contact
752          *
753          * @param array   $user     User unfriending
754          * @param array   $contact  Contact unfriended
755          * @param boolean $dissolve Remove the contact on the remote side
756          * @return void
757          * @throws HTTPException\InternalServerErrorException
758          * @throws \ImagickException
759          */
760         public static function terminateFriendship(array $user, array $contact, $dissolve = false)
761         {
762                 if (empty($contact['network'])) {
763                         return;
764                 }
765
766                 $protocol = $contact['network'];
767                 if (($protocol == Protocol::DFRN) && !self::isLegacyDFRNContact($contact)) {
768                         $protocol = Protocol::ACTIVITYPUB;
769                 }
770
771                 if (($protocol == Protocol::DFRN) && $dissolve) {
772                         DFRN::deliver($user, $contact, 'placeholder', true);
773                 } elseif (in_array($protocol, [Protocol::OSTATUS, Protocol::DFRN])) {
774                         // create an unfollow slap
775                         $item = [];
776                         $item['verb'] = Activity::O_UNFOLLOW;
777                         $item['gravity'] = GRAVITY_ACTIVITY;
778                         $item['follow'] = $contact["url"];
779                         $item['body'] = '';
780                         $item['title'] = '';
781                         $item['guid'] = '';
782                         $item['uri-id'] = 0;
783                         $item['attach'] = '';
784                         $slap = OStatus::salmon($item, $user);
785
786                         if (!empty($contact['notify'])) {
787                                 Salmon::slapper($user, $contact['notify'], $slap);
788                         }
789                 } elseif ($protocol == Protocol::DIASPORA) {
790                         Diaspora::sendUnshare($user, $contact);
791                 } elseif ($protocol == Protocol::ACTIVITYPUB) {
792                         ActivityPub\Transmitter::sendContactUndo($contact['url'], $contact['id'], $user['uid']);
793
794                         if ($dissolve) {
795                                 ActivityPub\Transmitter::sendContactReject($contact['url'], $contact['hub-verify'], $user['uid']);
796                         }
797                 }
798         }
799
800         /**
801          * Marks a contact for archival after a communication issue delay
802          *
803          * Contact has refused to recognise us as a friend. We will start a countdown.
804          * If they still don't recognise us in 32 days, the relationship is over,
805          * and we won't waste any more time trying to communicate with them.
806          * This provides for the possibility that their database is temporarily messed
807          * up or some other transient event and that there's a possibility we could recover from it.
808          *
809          * @param array $contact contact to mark for archival
810          * @return null
811          * @throws HTTPException\InternalServerErrorException
812          */
813         public static function markForArchival(array $contact)
814         {
815                 if (!isset($contact['url']) && !empty($contact['id'])) {
816                         $fields = ['id', 'url', 'archive', 'self', 'term-date'];
817                         $contact = DBA::selectFirst('contact', $fields, ['id' => $contact['id']]);
818                         if (!DBA::isResult($contact)) {
819                                 return;
820                         }
821                 } elseif (!isset($contact['url'])) {
822                         Logger::info('Empty contact', ['contact' => $contact, 'callstack' => System::callstack(20)]);
823                 }
824
825                 Logger::info('Contact is marked for archival', ['id' => $contact['id']]);
826
827                 // Contact already archived or "self" contact? => nothing to do
828                 if ($contact['archive'] || $contact['self']) {
829                         return;
830                 }
831
832                 if ($contact['term-date'] <= DBA::NULL_DATETIME) {
833                         DBA::update('contact', ['term-date' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
834                         DBA::update('contact', ['term-date' => DateTimeFormat::utcNow()], ['`nurl` = ? AND `term-date` <= ? AND NOT `self`', Strings::normaliseLink($contact['url']), DBA::NULL_DATETIME]);
835                 } else {
836                         /* @todo
837                          * We really should send a notification to the owner after 2-3 weeks
838                          * so they won't be surprised when the contact vanishes and can take
839                          * remedial action if this was a serious mistake or glitch
840                          */
841
842                         /// @todo Check for contact vitality via probing
843                         $archival_days = DI::config()->get('system', 'archival_days', 32);
844
845                         $expiry = $contact['term-date'] . ' + ' . $archival_days . ' days ';
846                         if (DateTimeFormat::utcNow() > DateTimeFormat::utc($expiry)) {
847                                 /* Relationship is really truly dead. archive them rather than
848                                  * delete, though if the owner tries to unarchive them we'll start
849                                  * the whole process over again.
850                                  */
851                                 DBA::update('contact', ['archive' => true], ['id' => $contact['id']]);
852                                 DBA::update('contact', ['archive' => true], ['nurl' => Strings::normaliseLink($contact['url']), 'self' => false]);
853                         }
854                 }
855         }
856
857         /**
858          * Cancels the archival countdown
859          *
860          * @see   Contact::markForArchival()
861          *
862          * @param array $contact contact to be unmarked for archival
863          * @return null
864          * @throws \Exception
865          */
866         public static function unmarkForArchival(array $contact)
867         {
868                 // Always unarchive the relay contact entry
869                 if (!empty($contact['batch']) && !empty($contact['term-date']) && ($contact['term-date'] > DBA::NULL_DATETIME)) {
870                         $fields = ['failed' => false, 'term-date' => DBA::NULL_DATETIME, 'archive' => false];
871                         $condition = ['uid' => 0, 'network' => Protocol::FEDERATED, 'batch' => $contact['batch'], 'contact-type' => self::TYPE_RELAY];
872                         DBA::update('contact', $fields, $condition);
873                 }
874
875                 $condition = ['`id` = ? AND (`term-date` > ? OR `archive`)', $contact['id'], DBA::NULL_DATETIME];
876                 $exists = DBA::exists('contact', $condition);
877
878                 // We don't need to update, we never marked this contact for archival
879                 if (!$exists) {
880                         return;
881                 }
882
883                 Logger::info('Contact is marked as vital again', ['id' => $contact['id']]);
884
885                 if (!isset($contact['url']) && !empty($contact['id'])) {
886                         $fields = ['id', 'url', 'batch'];
887                         $contact = DBA::selectFirst('contact', $fields, ['id' => $contact['id']]);
888                         if (!DBA::isResult($contact)) {
889                                 return;
890                         }
891                 }
892
893                 // It's a miracle. Our dead contact has inexplicably come back to life.
894                 $fields = ['failed' => false, 'term-date' => DBA::NULL_DATETIME, 'archive' => false];
895                 DBA::update('contact', $fields, ['id' => $contact['id']]);
896                 DBA::update('contact', $fields, ['nurl' => Strings::normaliseLink($contact['url']), 'self' => false]);
897         }
898
899         /**
900          * Returns the data array for the photo menu of a given contact
901          *
902          * @param array $contact contact
903          * @param int   $uid     optional, default 0
904          * @return array
905          * @throws HTTPException\InternalServerErrorException
906          * @throws \ImagickException
907          */
908         public static function photoMenu(array $contact, $uid = 0)
909         {
910                 $pm_url = '';
911                 $status_link = '';
912                 $photos_link = '';
913                 $contact_drop_link = '';
914                 $poke_link = '';
915
916                 if ($uid == 0) {
917                         $uid = local_user();
918                 }
919
920                 if (empty($contact['uid']) || ($contact['uid'] != $uid)) {
921                         if ($uid == 0) {
922                                 $profile_link = self::magicLink($contact['url']);
923                                 $menu = ['profile' => [DI::l10n()->t('View Profile'), $profile_link, true]];
924
925                                 return $menu;
926                         }
927
928                         // Look for our own contact if the uid doesn't match and isn't public
929                         $contact_own = DBA::selectFirst('contact', [], ['nurl' => $contact['nurl'], 'network' => $contact['network'], 'uid' => $uid]);
930                         if (DBA::isResult($contact_own)) {
931                                 return self::photoMenu($contact_own, $uid);
932                         }
933                 }
934
935                 $sparkle = false;
936                 if (($contact['network'] === Protocol::DFRN) && !$contact['self'] && empty($contact['pending'])) {
937                         $sparkle = true;
938                         $profile_link = DI::baseUrl() . '/redir/' . $contact['id'];
939                 } else {
940                         $profile_link = $contact['url'];
941                 }
942
943                 if ($profile_link === 'mailbox') {
944                         $profile_link = '';
945                 }
946
947                 if ($sparkle) {
948                         $status_link = $profile_link . '/status';
949                         $photos_link = str_replace('/profile/', '/photos/', $profile_link);
950                         $profile_link = $profile_link . '/profile';
951                 }
952
953                 if (self::canReceivePrivateMessages($contact) && empty($contact['pending'])) {
954                         $pm_url = DI::baseUrl() . '/message/new/' . $contact['id'];
955                 }
956
957                 if (($contact['network'] == Protocol::DFRN) && !$contact['self'] && empty($contact['pending'])) {
958                         $poke_link = 'contact/' . $contact['id'] . '/poke';
959                 }
960
961                 $contact_url = DI::baseUrl() . '/contact/' . $contact['id'];
962
963                 $posts_link = DI::baseUrl() . '/contact/' . $contact['id'] . '/conversations';
964
965                 if (!$contact['self']) {
966                         $contact_drop_link = DI::baseUrl() . '/contact/' . $contact['id'] . '/drop?confirm=1';
967                 }
968
969                 $follow_link = '';
970                 $unfollow_link = '';
971                 if (!$contact['self'] && in_array($contact['network'], Protocol::NATIVE_SUPPORT)) {
972                         if ($contact['uid'] && in_array($contact['rel'], [self::SHARING, self::FRIEND])) {
973                                 $unfollow_link = 'unfollow?url=' . urlencode($contact['url']);
974                         } elseif(!$contact['pending']) {
975                                 $follow_link = 'follow?url=' . urlencode($contact['url']);
976                         }
977                 }
978
979                 if (!empty($follow_link) || !empty($unfollow_link)) {
980                         $contact_drop_link = '';
981                 }
982
983                 /**
984                  * Menu array:
985                  * "name" => [ "Label", "link", (bool)Should the link opened in a new tab? ]
986                  */
987                 if (empty($contact['uid'])) {
988                         $menu = [
989                                 'profile' => [DI::l10n()->t('View Profile')  , $profile_link , true],
990                                 'network' => [DI::l10n()->t('Network Posts') , $posts_link   , false],
991                                 'edit'    => [DI::l10n()->t('View Contact')  , $contact_url  , false],
992                                 'follow'  => [DI::l10n()->t('Connect/Follow'), $follow_link  , true],
993                                 'unfollow'=> [DI::l10n()->t('UnFollow')      , $unfollow_link, true],
994                         ];
995                 } else {
996                         $menu = [
997                                 'status'  => [DI::l10n()->t('View Status')   , $status_link      , true],
998                                 'profile' => [DI::l10n()->t('View Profile')  , $profile_link     , true],
999                                 'photos'  => [DI::l10n()->t('View Photos')   , $photos_link      , true],
1000                                 'network' => [DI::l10n()->t('Network Posts') , $posts_link       , false],
1001                                 'edit'    => [DI::l10n()->t('View Contact')  , $contact_url      , false],
1002                                 'drop'    => [DI::l10n()->t('Drop Contact')  , $contact_drop_link, false],
1003                                 'pm'      => [DI::l10n()->t('Send PM')       , $pm_url           , false],
1004                                 'poke'    => [DI::l10n()->t('Poke')          , $poke_link        , false],
1005                                 'follow'  => [DI::l10n()->t('Connect/Follow'), $follow_link      , true],
1006                                 'unfollow'=> [DI::l10n()->t('UnFollow')      , $unfollow_link    , true],
1007                         ];
1008
1009                         if (!empty($contact['pending'])) {
1010                                 $intro = DBA::selectFirst('intro', ['id'], ['contact-id' => $contact['id']]);
1011                                 if (DBA::isResult($intro)) {
1012                                         $menu['follow'] = [DI::l10n()->t('Approve'), 'notifications/intros/' . $intro['id'], true];
1013                                 }
1014                         }
1015                 }
1016
1017                 $args = ['contact' => $contact, 'menu' => &$menu];
1018
1019                 Hook::callAll('contact_photo_menu', $args);
1020
1021                 $menucondensed = [];
1022
1023                 foreach ($menu as $menuname => $menuitem) {
1024                         if ($menuitem[1] != '') {
1025                                 $menucondensed[$menuname] = $menuitem;
1026                         }
1027                 }
1028
1029                 return $menucondensed;
1030         }
1031
1032         /**
1033          * Returns ungrouped contact count or list for user
1034          *
1035          * Returns either the total number of ungrouped contacts for the given user
1036          * id or a paginated list of ungrouped contacts.
1037          *
1038          * @param int $uid uid
1039          * @return array
1040          * @throws \Exception
1041          */
1042         public static function getUngroupedList($uid)
1043         {
1044                 return q("SELECT *
1045                            FROM `contact`
1046                            WHERE `uid` = %d
1047                            AND NOT `self`
1048                            AND NOT `deleted`
1049                            AND NOT `blocked`
1050                            AND NOT `pending`
1051                            AND `id` NOT IN (
1052                                 SELECT DISTINCT(`contact-id`)
1053                                 FROM `group_member`
1054                                 INNER JOIN `group` ON `group`.`id` = `group_member`.`gid`
1055                                 WHERE `group`.`uid` = %d
1056                            )", intval($uid), intval($uid));
1057         }
1058
1059         /**
1060          * Have a look at all contact tables for a given profile url.
1061          * This function works as a replacement for probing the contact.
1062          *
1063          * @param string  $url Contact URL
1064          * @param integer $cid Contact ID
1065          *
1066          * @return array Contact array in the "probe" structure
1067         */
1068         private static function getProbeDataFromDatabase($url, $cid = null)
1069         {
1070                 // The link could be provided as http although we stored it as https
1071                 $ssl_url = str_replace('http://', 'https://', $url);
1072
1073                 $fields = ['id', 'uid', 'url', 'addr', 'alias', 'notify', 'poll', 'name', 'nick',
1074                         'photo', 'keywords', 'location', 'about', 'network',
1075                         'priority', 'batch', 'request', 'confirm', 'poco'];
1076
1077                 if (!empty($cid)) {
1078                         $data = DBA::selectFirst('contact', $fields, ['id' => $cid]);
1079                         if (DBA::isResult($data)) {
1080                                 return $data;
1081                         }
1082                 }
1083
1084                 $data = DBA::selectFirst('contact', $fields, ['nurl' => Strings::normaliseLink($url)]);
1085
1086                 if (!DBA::isResult($data)) {
1087                         $condition = ['alias' => [$url, Strings::normaliseLink($url), $ssl_url]];
1088                         $data = DBA::selectFirst('contact', $fields, $condition);
1089                 }
1090
1091                 if (DBA::isResult($data)) {
1092                         // For security reasons we don't fetch key data from our users
1093                         $data["pubkey"] = '';
1094                         return $data;
1095                 }
1096
1097                 $fields = ['url', 'addr', 'alias', 'notify', 'name', 'nick',
1098                         'photo', 'keywords', 'location', 'about', 'network'];
1099                 $condition = ['alias' => [$url, Strings::normaliseLink($url), $ssl_url]];
1100                 $data = DBA::selectFirst('contact', $fields, $condition);
1101
1102                 if (DBA::isResult($data)) {
1103                         $data["pubkey"] = '';
1104                         $data["poll"] = '';
1105                         $data["priority"] = 0;
1106                         $data["batch"] = '';
1107                         $data["request"] = '';
1108                         $data["confirm"] = '';
1109                         $data["poco"] = '';
1110                         return $data;
1111                 }
1112
1113                 $data = ActivityPub::probeProfile($url, false);
1114                 if (!empty($data)) {
1115                         return $data;
1116                 }
1117
1118                 $fields = ['url', 'addr', 'alias', 'notify', 'poll', 'name', 'nick',
1119                         'photo', 'network', 'priority', 'batch', 'request', 'confirm'];
1120                 $data = DBA::selectFirst('fcontact', $fields, ['url' => $url]);
1121
1122                 if (!DBA::isResult($data)) {
1123                         $condition = ['alias' => [$url, Strings::normaliseLink($url), $ssl_url]];
1124                         $data = DBA::selectFirst('contact', $fields, $condition);
1125                 }
1126
1127                 if (DBA::isResult($data)) {
1128                         $data["pubkey"] = '';
1129                         $data["keywords"] = '';
1130                         $data["location"] = '';
1131                         $data["about"] = '';
1132                         $data["poco"] = '';
1133                         return $data;
1134                 }
1135
1136                 return [];
1137         }
1138
1139         /**
1140          * Fetch the contact id for a given URL and user
1141          *
1142          * First lookup in the contact table to find a record matching either `url`, `nurl`,
1143          * `addr` or `alias`.
1144          *
1145          * If there's no record and we aren't looking for a public contact, we quit.
1146          * If there's one, we check that it isn't time to update the picture else we
1147          * directly return the found contact id.
1148          *
1149          * Second, we probe the provided $url whether it's http://server.tld/profile or
1150          * nick@server.tld. We quit if we can't get any info back.
1151          *
1152          * Third, we create the contact record if it doesn't exist
1153          *
1154          * Fourth, we update the existing record with the new data (avatar, alias, nick)
1155          * if there's any updates
1156          *
1157          * @param string  $url       Contact URL
1158          * @param integer $uid       The user id for the contact (0 = public contact)
1159          * @param boolean $update    true = always update, false = never update, null = update when not found or outdated
1160          * @param array   $default   Default value for creating the contact when every else fails
1161          * @param boolean $in_loop   Internally used variable to prevent an endless loop
1162          *
1163          * @return integer Contact ID
1164          * @throws HTTPException\InternalServerErrorException
1165          * @throws \ImagickException
1166          */
1167         public static function getIdForURL($url, $uid = 0, $update = null, $default = [], $in_loop = false)
1168         {
1169                 Logger::info('Get contact data', ['url' => $url, 'user' => $uid]);
1170
1171                 $contact_id = 0;
1172
1173                 if ($url == '') {
1174                         return 0;
1175                 }
1176
1177                 $contact = self::getByURL($url, false, ['id', 'avatar', 'updated', 'network'], $uid);
1178
1179                 if (!empty($contact)) {
1180                         $contact_id = $contact["id"];
1181
1182                         if (empty($default) && in_array($contact['network'], [Protocol::MAIL, Protocol::PHANTOM]) && ($uid == 0)) {
1183                                 // Update public mail accounts via their user's accounts
1184                                 $fields = ['network', 'addr', 'name', 'nick', 'avatar', 'photo', 'thumb', 'micro'];
1185                                 $mailcontact = DBA::selectFirst('contact', $fields, ["`addr` = ? AND `network` = ? AND `uid` != 0", $url, Protocol::MAIL]);
1186                                 if (!DBA::isResult($mailcontact)) {
1187                                         $mailcontact = DBA::selectFirst('contact', $fields, ["`nurl` = ? AND `network` = ? AND `uid` != 0", $url, Protocol::MAIL]);
1188                                 }
1189
1190                                 if (DBA::isResult($mailcontact)) {
1191                                         DBA::update('contact', $mailcontact, ['id' => $contact_id]);
1192                                 }
1193                         }
1194
1195                         if (empty($update)) {
1196                                 return $contact_id;
1197                         }
1198                 } elseif ($uid != 0) {
1199                         // Non-existing user-specific contact, exiting
1200                         return 0;
1201                 }
1202
1203                 if (!$update && empty($default)) {
1204                         // When we don't want to update, we look if we know this contact in any way
1205                         $data = self::getProbeDataFromDatabase($url, $contact_id);
1206                         $background_update = true;
1207                 } elseif (!$update && !empty($default['network'])) {
1208                         // If there are default values, take these
1209                         $data = $default;
1210                         $background_update = false;
1211                 } else {
1212                         $data = [];
1213                         $background_update = false;
1214                 }
1215
1216                 if ((empty($data) && is_null($update)) || $update) {
1217                         $data = Probe::uri($url, "", $uid);
1218                 }
1219
1220                 // Take the default values when probing failed
1221                 if (!empty($default) && !in_array($data["network"], array_merge(Protocol::NATIVE_SUPPORT, [Protocol::PUMPIO]))) {
1222                         $data = array_merge($data, $default);
1223                 }
1224
1225                 if (empty($data) || ($data['network'] == Protocol::PHANTOM)) {
1226                         Logger::info('No valid network found', ['url' => $url, 'data' => $data, 'callstack' => System::callstack(20)]);
1227                         return 0;
1228                 }
1229
1230                 if (!empty($data['baseurl'])) {
1231                         $data['baseurl'] = GServer::cleanURL($data['baseurl']);
1232                 }
1233
1234                 if (!empty($data['baseurl']) && empty($data['gsid'])) {
1235                         $data['gsid'] = GServer::getID($data['baseurl']);
1236                 }
1237
1238                 if (!$contact_id && !empty($data['alias']) && ($data['alias'] != $data['url']) && !$in_loop) {
1239                         $contact_id = self::getIdForURL($data["alias"], $uid, false, $default, true);
1240                 }
1241
1242                 if (!$contact_id) {
1243                         $fields = [
1244                                 'uid'       => $uid,
1245                                 'created'   => DateTimeFormat::utcNow(),
1246                                 'url'       => $data['url'],
1247                                 'nurl'      => Strings::normaliseLink($data['url']),
1248                                 'addr'      => $data['addr'] ?? '',
1249                                 'alias'     => $data['alias'] ?? '',
1250                                 'notify'    => $data['notify'] ?? '',
1251                                 'poll'      => $data['poll'] ?? '',
1252                                 'name'      => $data['name'] ?? '',
1253                                 'nick'      => $data['nick'] ?? '',
1254                                 'keywords'  => $data['keywords'] ?? '',
1255                                 'location'  => $data['location'] ?? '',
1256                                 'about'     => $data['about'] ?? '',
1257                                 'network'   => $data['network'],
1258                                 'pubkey'    => $data['pubkey'] ?? '',
1259                                 'rel'       => self::SHARING,
1260                                 'priority'  => $data['priority'] ?? 0,
1261                                 'batch'     => $data['batch'] ?? '',
1262                                 'request'   => $data['request'] ?? '',
1263                                 'confirm'   => $data['confirm'] ?? '',
1264                                 'poco'      => $data['poco'] ?? '',
1265                                 'baseurl'   => $data['baseurl'] ?? '',
1266                                 'gsid'      => $data['gsid'] ?? null,
1267                                 'name-date' => DateTimeFormat::utcNow(),
1268                                 'uri-date'  => DateTimeFormat::utcNow(),
1269                                 'avatar-date' => DateTimeFormat::utcNow(),
1270                                 'writable'  => 1,
1271                                 'blocked'   => 0,
1272                                 'readonly'  => 0,
1273                                 'pending'   => 0];
1274
1275                         $condition = ['nurl' => Strings::normaliseLink($data["url"]), 'uid' => $uid, 'deleted' => false];
1276
1277                         // Before inserting we do check if the entry does exist now.
1278                         $contact = DBA::selectFirst('contact', ['id'], $condition, ['order' => ['id']]);
1279                         if (!DBA::isResult($contact)) {
1280                                 Logger::info('Create new contact', $fields);
1281
1282                                 self::insert($fields);
1283
1284                                 // We intentionally aren't using lastInsertId here. There is a chance for duplicates.
1285                                 $contact = DBA::selectFirst('contact', ['id'], $condition, ['order' => ['id']]);
1286                                 if (!DBA::isResult($contact)) {
1287                                         Logger::info('Contact creation failed', $fields);
1288                                         // Shouldn't happen
1289                                         return 0;
1290                                 }
1291                         } else {
1292                                 Logger::info('Contact had been created before', ['id' => $contact["id"], 'url' => $url, 'contact' => $fields]);
1293                         }
1294
1295                         $contact_id = $contact["id"];
1296                 }
1297
1298                 if (!empty($data['photo']) && ($data['network'] != Protocol::FEED)) {
1299                         self::updateAvatar($contact_id, $data['photo']);
1300                 }
1301
1302                 if (in_array($data["network"], array_merge(Protocol::NATIVE_SUPPORT, [Protocol::PUMPIO]))) {
1303                         if ($background_update) {
1304                                 // Update in the background when we fetched the data solely from the database
1305                                 Worker::add(PRIORITY_MEDIUM, "UpdateContact", $contact_id, ($uid == 0 ? 'force' : ''));
1306                         } else {
1307                                 // Else do a direct update
1308                                 self::updateFromProbe($contact_id, '', false);
1309                         }
1310                 } else {
1311                         $fields = ['url', 'nurl', 'addr', 'alias', 'name', 'nick', 'keywords', 'location', 'about', 'avatar-date', 'baseurl', 'gsid'];
1312                         $contact = DBA::selectFirst('contact', $fields, ['id' => $contact_id]);
1313
1314                         // This condition should always be true
1315                         if (!DBA::isResult($contact)) {
1316                                 return $contact_id;
1317                         }
1318
1319                         $updated = [
1320                                 'url' => $data['url'],
1321                                 'nurl' => Strings::normaliseLink($data['url']),
1322                                 'updated' => DateTimeFormat::utcNow(),
1323                                 'failed' => false
1324                         ];
1325
1326                         $fields = ['addr', 'alias', 'name', 'nick', 'keywords', 'location', 'about', 'baseurl', 'gsid'];
1327
1328                         foreach ($fields as $field) {
1329                                 $updated[$field] = ($data[$field] ?? '') ?: $contact[$field];
1330                         }
1331
1332                         if (($updated['addr'] != $contact['addr']) || (!empty($data['alias']) && ($data['alias'] != $contact['alias']))) {
1333                                 $updated['uri-date'] = DateTimeFormat::utcNow();
1334                         }
1335
1336                         if (($data['name'] != $contact['name']) || ($data['nick'] != $contact['nick'])) {
1337                                 $updated['name-date'] = DateTimeFormat::utcNow();
1338                         }
1339
1340                         DBA::update('contact', $updated, ['id' => $contact_id], $contact);
1341                 }
1342
1343                 return $contact_id;
1344         }
1345
1346         /**
1347          * Checks if the contact is archived
1348          *
1349          * @param int $cid contact id
1350          *
1351          * @return boolean Is the contact archived?
1352          * @throws HTTPException\InternalServerErrorException
1353          */
1354         public static function isArchived(int $cid)
1355         {
1356                 if ($cid == 0) {
1357                         return false;
1358                 }
1359
1360                 $contact = DBA::selectFirst('contact', ['archive', 'url', 'batch'], ['id' => $cid]);
1361                 if (!DBA::isResult($contact)) {
1362                         return false;
1363                 }
1364
1365                 if ($contact['archive']) {
1366                         return true;
1367                 }
1368
1369                 // Check status of ActivityPub endpoints
1370                 $apcontact = APContact::getByURL($contact['url'], false);
1371                 if (!empty($apcontact)) {
1372                         if (!empty($apcontact['inbox']) && DBA::exists('inbox-status', ['archive' => true, 'url' => $apcontact['inbox']])) {
1373                                 return true;
1374                         }
1375
1376                         if (!empty($apcontact['sharedinbox']) && DBA::exists('inbox-status', ['archive' => true, 'url' => $apcontact['sharedinbox']])) {
1377                                 return true;
1378                         }
1379                 }
1380
1381                 // Check status of Diaspora endpoints
1382                 if (!empty($contact['batch'])) {
1383                         $condition = ['archive' => true, 'uid' => 0, 'network' => Protocol::FEDERATED, 'batch' => $contact['batch'], 'contact-type' => self::TYPE_RELAY];
1384                         return DBA::exists('contact', $condition);
1385                 }
1386
1387                 return false;
1388         }
1389
1390         /**
1391          * Checks if the contact is blocked
1392          *
1393          * @param int $cid contact id
1394          *
1395          * @return boolean Is the contact blocked?
1396          * @throws HTTPException\InternalServerErrorException
1397          */
1398         public static function isBlocked($cid)
1399         {
1400                 if ($cid == 0) {
1401                         return false;
1402                 }
1403
1404                 $blocked = DBA::selectFirst('contact', ['blocked', 'url'], ['id' => $cid]);
1405                 if (!DBA::isResult($blocked)) {
1406                         return false;
1407                 }
1408
1409                 if (Network::isUrlBlocked($blocked['url'])) {
1410                         return true;
1411                 }
1412
1413                 return (bool) $blocked['blocked'];
1414         }
1415
1416         /**
1417          * Checks if the contact is hidden
1418          *
1419          * @param int $cid contact id
1420          *
1421          * @return boolean Is the contact hidden?
1422          * @throws \Exception
1423          */
1424         public static function isHidden($cid)
1425         {
1426                 if ($cid == 0) {
1427                         return false;
1428                 }
1429
1430                 $hidden = DBA::selectFirst('contact', ['hidden'], ['id' => $cid]);
1431                 if (!DBA::isResult($hidden)) {
1432                         return false;
1433                 }
1434                 return (bool) $hidden['hidden'];
1435         }
1436
1437         /**
1438          * Returns posts from a given contact url
1439          *
1440          * @param string $contact_url Contact URL
1441          * @param bool   $thread_mode
1442          * @param int    $update
1443          * @return string posts in HTML
1444          * @throws \Exception
1445          */
1446         public static function getPostsFromUrl($contact_url, $thread_mode = false, $update = 0)
1447         {
1448                 return self::getPostsFromId(self::getIdForURL($contact_url), $thread_mode, $update);
1449         }
1450
1451         /**
1452          * Returns posts from a given contact id
1453          *
1454          * @param integer $cid
1455          * @param bool    $thread_mode
1456          * @param integer $update
1457          * @return string posts in HTML
1458          * @throws \Exception
1459          */
1460         public static function getPostsFromId($cid, $thread_mode = false, $update = 0)
1461         {
1462                 $a = DI::app();
1463
1464                 $contact = DBA::selectFirst('contact', ['contact-type', 'network'], ['id' => $cid]);
1465                 if (!DBA::isResult($contact)) {
1466                         return '';
1467                 }
1468
1469                 if (empty($contact["network"]) || in_array($contact["network"], Protocol::FEDERATED)) {
1470                         $sql = "(`item`.`uid` = 0 OR (`item`.`uid` = ? AND NOT `item`.`global`))";
1471                 } else {
1472                         $sql = "`item`.`uid` = ?";
1473                 }
1474
1475                 $contact_field = ((($contact["contact-type"] == self::TYPE_COMMUNITY) || ($contact['network'] == Protocol::MAIL)) ? 'owner-id' : 'author-id');
1476
1477                 if ($thread_mode) {
1478                         $condition = ["`$contact_field` = ? AND `gravity` = ? AND " . $sql,
1479                                 $cid, GRAVITY_PARENT, local_user()];
1480                 } else {
1481                         $condition = ["`$contact_field` = ? AND `gravity` IN (?, ?) AND " . $sql,
1482                                 $cid, GRAVITY_PARENT, GRAVITY_COMMENT, local_user()];
1483                 }
1484
1485                 if (DI::mode()->isMobile()) {
1486                         $itemsPerPage = DI::pConfig()->get(local_user(), 'system', 'itemspage_mobile_network',
1487                                 DI::config()->get('system', 'itemspage_network_mobile'));
1488                 } else {
1489                         $itemsPerPage = DI::pConfig()->get(local_user(), 'system', 'itemspage_network',
1490                                 DI::config()->get('system', 'itemspage_network'));
1491                 }
1492
1493                 $pager = new Pager(DI::l10n(), DI::args()->getQueryString(), $itemsPerPage);
1494
1495                 $params = ['order' => ['received' => true],
1496                         'limit' => [$pager->getStart(), $pager->getItemsPerPage()]];
1497
1498                 if ($thread_mode) {
1499                         $r = Item::selectThreadForUser(local_user(), ['uri'], $condition, $params);
1500
1501                         $items = Item::inArray($r);
1502
1503                         $o = conversation($a, $items, 'contacts', $update, false, 'commented', local_user());
1504                 } else {
1505                         $r = Item::selectForUser(local_user(), [], $condition, $params);
1506
1507                         $items = Item::inArray($r);
1508
1509                         $o = conversation($a, $items, 'contact-posts', false);
1510                 }
1511
1512                 if (!$update) {
1513                         $o .= $pager->renderMinimal(count($items));
1514                 }
1515
1516                 return $o;
1517         }
1518
1519         /**
1520          * Returns the account type name
1521          *
1522          * The function can be called with either the user or the contact array
1523          *
1524          * @param array $contact contact or user array
1525          * @return string
1526          */
1527         public static function getAccountType(array $contact)
1528         {
1529                 // There are several fields that indicate that the contact or user is a forum
1530                 // "page-flags" is a field in the user table,
1531                 // "forum" and "prv" are used in the contact table. They stand for User::PAGE_FLAGS_COMMUNITY and User::PAGE_FLAGS_PRVGROUP.
1532                 if ((isset($contact['page-flags']) && (intval($contact['page-flags']) == User::PAGE_FLAGS_COMMUNITY))
1533                         || (isset($contact['page-flags']) && (intval($contact['page-flags']) == User::PAGE_FLAGS_PRVGROUP))
1534                         || (isset($contact['forum']) && intval($contact['forum']))
1535                         || (isset($contact['prv']) && intval($contact['prv']))
1536                         || (isset($contact['community']) && intval($contact['community']))
1537                 ) {
1538                         $type = self::TYPE_COMMUNITY;
1539                 } else {
1540                         $type = self::TYPE_PERSON;
1541                 }
1542
1543                 // The "contact-type" (contact table) and "account-type" (user table) are more general then the chaos from above.
1544                 if (isset($contact["contact-type"])) {
1545                         $type = $contact["contact-type"];
1546                 }
1547
1548                 if (isset($contact["account-type"])) {
1549                         $type = $contact["account-type"];
1550                 }
1551
1552                 switch ($type) {
1553                         case self::TYPE_ORGANISATION:
1554                                 $account_type = DI::l10n()->t("Organisation");
1555                                 break;
1556
1557                         case self::TYPE_NEWS:
1558                                 $account_type = DI::l10n()->t('News');
1559                                 break;
1560
1561                         case self::TYPE_COMMUNITY:
1562                                 $account_type = DI::l10n()->t("Forum");
1563                                 break;
1564
1565                         default:
1566                                 $account_type = "";
1567                                 break;
1568                 }
1569
1570                 return $account_type;
1571         }
1572
1573         /**
1574          * Blocks a contact
1575          *
1576          * @param int $cid
1577          * @return bool
1578          * @throws \Exception
1579          */
1580         public static function block($cid, $reason = null)
1581         {
1582                 $return = DBA::update('contact', ['blocked' => true, 'block_reason' => $reason], ['id' => $cid]);
1583
1584                 return $return;
1585         }
1586
1587         /**
1588          * Unblocks a contact
1589          *
1590          * @param int $cid
1591          * @return bool
1592          * @throws \Exception
1593          */
1594         public static function unblock($cid)
1595         {
1596                 $return = DBA::update('contact', ['blocked' => false, 'block_reason' => null], ['id' => $cid]);
1597
1598                 return $return;
1599         }
1600
1601         /**
1602          * Ensure that cached avatar exist
1603          *
1604          * @param integer $cid
1605          */
1606         public static function checkAvatarCache(int $cid)
1607         {
1608                 $contact = DBA::selectFirst('contact', ['url', 'avatar', 'photo', 'thumb', 'micro'], ['id' => $cid, 'uid' => 0, 'self' => false]);
1609                 if (!DBA::isResult($contact)) {
1610                         return;
1611                 }
1612
1613                 if (empty($contact['avatar']) || (!empty($contact['photo']) && !empty($contact['thumb']) && !empty($contact['micro']))) {
1614                         return;
1615                 }
1616
1617                 Logger::info('Adding avatar cache', ['id' => $cid, 'contact' => $contact]);
1618
1619                 self::updateAvatar($cid, $contact['avatar'], true);
1620         }
1621
1622         /**
1623          * Return the photo path for a given contact array in the given size
1624          *
1625          * @param array $contact  contact array
1626          * @param string $field   Fieldname of the photo in the contact array
1627          * @param string $default Default path when no picture had been found
1628          * @param string $size    Size of the avatar picture
1629          * @param string $avatar  Avatar path that is displayed when no photo had been found
1630          * @return string photo path
1631          */
1632         private static function getAvatarPath(array $contact, string $field, string $default, string $size, string $avatar)
1633         {
1634                 if (!empty($contact)) {
1635                         $contact = self::checkAvatarCacheByArray($contact);
1636                         if (!empty($contact[$field])) {
1637                                 $avatar = $contact[$field];
1638                         }
1639                 }
1640
1641                 if (empty($avatar)) {
1642                         return $default;
1643                 }
1644
1645                 if (Proxy::isLocalImage($avatar)) {
1646                         return $avatar;
1647                 } else {
1648                         return Proxy::proxifyUrl($avatar, false, $size);
1649                 }
1650         }
1651
1652         /**
1653          * Return the photo path for a given contact array
1654          *
1655          * @param array $contact Contact array
1656          * @param string $avatar  Avatar path that is displayed when no photo had been found
1657          * @return string photo path
1658          */
1659         public static function getPhoto(array $contact, string $avatar = '')
1660         {
1661                 return self::getAvatarPath($contact, 'photo', DI::baseUrl() . '/images/person-300.jpg', Proxy::SIZE_SMALL, $avatar);
1662         }
1663
1664         /**
1665          * Return the photo path (thumb size) for a given contact array
1666          *
1667          * @param array $contact Contact array
1668          * @param string $avatar  Avatar path that is displayed when no photo had been found
1669          * @return string photo path
1670          */
1671         public static function getThumb(array $contact, string $avatar = '')
1672         {
1673                 return self::getAvatarPath($contact, 'thumb', DI::baseUrl() . '/images/person-80.jpg', Proxy::SIZE_THUMB, $avatar);
1674         }
1675
1676         /**
1677          * Return the photo path (micro size) for a given contact array
1678          *
1679          * @param array $contact Contact array
1680          * @param string $avatar  Avatar path that is displayed when no photo had been found
1681          * @return string photo path
1682          */
1683         public static function getMicro(array $contact, string $avatar = '')
1684         {
1685                 return self::getAvatarPath($contact, 'micro', DI::baseUrl() . '/images/person-48.jpg', Proxy::SIZE_MICRO, $avatar);
1686         }
1687
1688         /**
1689          * Check the given contact array for avatar cache fields
1690          *
1691          * @param array $contact
1692          * @return array contact array with avatar cache fields
1693          */
1694         private static function checkAvatarCacheByArray(array $contact)
1695         {
1696                 $update = false;
1697                 $contact_fields = [];
1698                 $fields = ['photo', 'thumb', 'micro'];
1699                 foreach ($fields as $field) {
1700                         if (isset($contact[$field])) {
1701                                 $contact_fields[] = $field;
1702                         }
1703                         if (isset($contact[$field]) && empty($contact[$field])) {
1704                                 $update = true;
1705                         }
1706                 }
1707
1708                 if (!$update) {
1709                         return $contact;
1710                 }
1711
1712                 if (!empty($contact['id']) && !empty($contact['avatar'])) {
1713                         self::updateAvatar($contact['id'], $contact['avatar'], true);
1714
1715                         $new_contact = self::getById($contact['id'], $contact_fields);
1716                         if (DBA::isResult($new_contact)) {
1717                                 // We only update the cache fields
1718                                 $contact = array_merge($contact, $new_contact);
1719                         }
1720                 }
1721
1722                 /// add the default avatars if the fields aren't filled
1723                 if (isset($contact['photo']) && empty($contact['photo'])) {
1724                         $contact['photo'] = DI::baseUrl() . '/images/person-300.jpg';
1725                 }
1726                 if (isset($contact['thumb']) && empty($contact['thumb'])) {
1727                         $contact['thumb'] = DI::baseUrl() . '/images/person-80.jpg';
1728                 }
1729                 if (isset($contact['micro']) && empty($contact['micro'])) {
1730                         $contact['micro'] = DI::baseUrl() . '/images/person-48.jpg';
1731                 }
1732
1733                 return $contact;
1734         }
1735
1736         /**
1737          * Updates the avatar links in a contact only if needed
1738          *
1739          * @param int    $cid    Contact id
1740          * @param string $avatar Link to avatar picture
1741          * @param bool   $force  force picture update
1742          *
1743          * @return void
1744          * @throws HTTPException\InternalServerErrorException
1745          * @throws HTTPException\NotFoundException
1746          * @throws \ImagickException
1747          */
1748         public static function updateAvatar(int $cid, string $avatar, bool $force = false)
1749         {
1750                 $contact = DBA::selectFirst('contact', ['uid', 'avatar', 'photo', 'thumb', 'micro', 'nurl'], ['id' => $cid, 'self' => false]);
1751                 if (!DBA::isResult($contact)) {
1752                         return;
1753                 }
1754
1755                 $uid = $contact['uid'];
1756
1757                 // Only update the cached photo links of public contacts when they already are cached
1758                 if (($uid == 0) && !$force && empty($contact['thumb']) && empty($contact['micro'])) {
1759                         if ($contact['avatar'] != $avatar) {
1760                                 DBA::update('contact', ['avatar' => $avatar], ['id' => $cid]);
1761                                 Logger::info('Only update the avatar', ['id' => $cid, 'avatar' => $avatar, 'contact' => $contact]);
1762                         }
1763                         return;
1764                 }
1765
1766                 $data = [
1767                         $contact['photo'] ?? '',
1768                         $contact['thumb'] ?? '',
1769                         $contact['micro'] ?? '',
1770                 ];
1771
1772                 $update = ($contact['avatar'] != $avatar) || $force;
1773
1774                 if (!$update) {
1775                         foreach ($data as $image_uri) {
1776                                 $image_rid = Photo::ridFromURI($image_uri);
1777                                 if ($image_rid && !Photo::exists(['resource-id' => $image_rid, 'uid' => $uid])) {
1778                                         Logger::info('Regenerating avatar', ['contact uid' => $uid, 'cid' => $cid, 'missing photo' => $image_rid, 'avatar' => $contact['avatar']]);
1779                                         $update = true;
1780                                 }
1781                         }
1782                 }
1783
1784                 if ($update) {
1785                         $photos = Photo::importProfilePhoto($avatar, $uid, $cid, true);
1786                         if ($photos) {
1787                                 $fields = ['avatar' => $avatar, 'photo' => $photos[0], 'thumb' => $photos[1], 'micro' => $photos[2], 'avatar-date' => DateTimeFormat::utcNow()];
1788                                 DBA::update('contact', $fields, ['id' => $cid]);
1789                         } elseif (empty($contact['avatar'])) {
1790                                 // Ensure that the avatar field is set
1791                                 DBA::update('contact', ['avatar' => $avatar], ['id' => $cid]);                          
1792                                 Logger::info('Failed profile import', ['id' => $cid, 'force' => $force, 'avatar' => $avatar, 'contact' => $contact]);
1793                         }
1794                 }
1795         }
1796
1797         /**
1798          * Helper function for "updateFromProbe". Updates personal and public contact
1799          *
1800          * @param integer $id      contact id
1801          * @param integer $uid     user id
1802          * @param string  $url     The profile URL of the contact
1803          * @param array   $fields  The fields that are updated
1804          *
1805          * @throws \Exception
1806          */
1807         private static function updateContact($id, $uid, $url, array $fields)
1808         {
1809                 if (!DBA::update('contact', $fields, ['id' => $id])) {
1810                         Logger::info('Couldn\'t update contact.', ['id' => $id, 'fields' => $fields]);
1811                         return;
1812                 }
1813
1814                 // Search for duplicated contacts and get rid of them
1815                 if (self::removeDuplicates(Strings::normaliseLink($url), $uid) || ($uid != 0)) {
1816                         return;
1817                 }
1818
1819                 // Archive or unarchive the contact. We only need to do this for the public contact.
1820                 // The archive/unarchive function will update the personal contacts by themselves.
1821                 $contact = DBA::selectFirst('contact', [], ['id' => $id]);
1822                 if (!DBA::isResult($contact)) {
1823                         Logger::info('Couldn\'t select contact for archival.', ['id' => $id]);
1824                         return;
1825                 }
1826
1827                 if (!empty($fields['success_update'])) {
1828                         self::unmarkForArchival($contact);
1829                 } elseif (!empty($fields['failure_update'])) {
1830                         self::markForArchival($contact);
1831                 }
1832
1833                 $condition = ['self' => false, 'nurl' => Strings::normaliseLink($url), 'network' => Protocol::FEDERATED];
1834
1835                 // These contacts are sharing with us, we don't poll them.
1836                 // This means that we don't set the update fields in "OnePoll.php".
1837                 $condition['rel'] = self::SHARING;
1838                 DBA::update('contact', $fields, $condition);
1839
1840                 unset($fields['last-update']);
1841                 unset($fields['success_update']);
1842                 unset($fields['failure_update']);
1843
1844                 if (empty($fields)) {
1845                         return;
1846                 }
1847
1848                 // We are polling these contacts, so we mustn't set the update fields here.
1849                 $condition['rel'] = [self::FOLLOWER, self::FRIEND];
1850                 DBA::update('contact', $fields, $condition);
1851         }
1852
1853         /**
1854          * Remove duplicated contacts
1855          *
1856          * @param string  $nurl  Normalised contact url
1857          * @param integer $uid   User id
1858          * @return boolean
1859          * @throws \Exception
1860          */
1861         public static function removeDuplicates(string $nurl, int $uid)
1862         {
1863                 $condition = ['nurl' => $nurl, 'uid' => $uid, 'deleted' => false, 'network' => Protocol::FEDERATED];
1864                 $count = DBA::count('contact', $condition);
1865                 if ($count <= 1) {
1866                         return false;
1867                 }
1868
1869                 $first_contact = DBA::selectFirst('contact', ['id', 'network'], $condition, ['order' => ['id']]);
1870                 if (!DBA::isResult($first_contact)) {
1871                         // Shouldn't happen - so we handle it
1872                         return false;
1873                 }
1874
1875                 $first = $first_contact['id'];
1876                 Logger::info('Found duplicates', ['count' => $count, 'first' => $first, 'uid' => $uid, 'nurl' => $nurl]);
1877                 if (($uid != 0 && ($first_contact['network'] == Protocol::DFRN))) {
1878                         // Don't handle non public DFRN duplicates by now (legacy DFRN is very special because of the key handling)
1879                         Logger::info('Not handling non public DFRN duplicate', ['uid' => $uid, 'nurl' => $nurl]);
1880                         return false;
1881                 }
1882
1883                 // Find all duplicates
1884                 $condition = ["`nurl` = ? AND `uid` = ? AND `id` != ? AND NOT `self` AND NOT `deleted`", $nurl, $uid, $first];
1885                 $duplicates = DBA::select('contact', ['id', 'network'], $condition);
1886                 while ($duplicate = DBA::fetch($duplicates)) {
1887                         if (!in_array($duplicate['network'], Protocol::FEDERATED)) {
1888                                 continue;
1889                         }
1890
1891                         Worker::add(PRIORITY_HIGH, 'MergeContact', $first, $duplicate['id'], $uid);
1892                 }
1893                 DBA::close($duplicates);
1894                 Logger::info('Duplicates handled', ['uid' => $uid, 'nurl' => $nurl]);
1895                 return true;
1896         }
1897
1898         /**
1899          * @param integer $id      contact id
1900          * @param string  $network Optional network we are probing for
1901          * @param boolean $force   Optional forcing of network probing (otherwise we use the cached data)
1902          * @return boolean
1903          * @throws HTTPException\InternalServerErrorException
1904          * @throws \ImagickException
1905          */
1906         public static function updateFromProbe(int $id, string $network = '', bool $force = false)
1907         {
1908                 /*
1909                   Warning: Never ever fetch the public key via Probe::uri and write it into the contacts.
1910                   This will reliably kill your communication with old Friendica contacts.
1911                  */
1912
1913                 // These fields aren't updated by this routine:
1914                 // 'xmpp', 'sensitive'
1915
1916                 $fields = ['uid', 'avatar', 'name', 'nick', 'location', 'keywords', 'about', 'subscribe',
1917                         'unsearchable', 'url', 'addr', 'batch', 'notify', 'poll', 'request', 'confirm', 'poco',
1918                         'network', 'alias', 'baseurl', 'gsid', 'forum', 'prv', 'contact-type', 'pubkey'];
1919                 $contact = DBA::selectFirst('contact', $fields, ['id' => $id]);
1920                 if (!DBA::isResult($contact)) {
1921                         return false;
1922                 }
1923
1924                 $uid = $contact['uid'];
1925                 unset($contact['uid']);
1926
1927                 $pubkey = $contact['pubkey'];
1928                 unset($contact['pubkey']);
1929
1930                 $contact['photo'] = $contact['avatar'];
1931                 unset($contact['avatar']);
1932
1933                 $ret = Probe::uri($contact['url'], $network, $uid, !$force);
1934
1935                 $updated = DateTimeFormat::utcNow();
1936
1937                 // We must not try to update relay contacts via probe. They are no real contacts.
1938                 // We check after the probing to be able to correct falsely detected contact types.
1939                 if (($contact['contact-type'] == self::TYPE_RELAY) &&
1940                         (!Strings::compareLink($ret['url'], $contact['url']) || in_array($ret['network'], [Protocol::FEED, Protocol::PHANTOM]))) {
1941                         self::updateContact($id, $uid, $contact['url'], ['failed' => false, 'last-update' => $updated, 'success_update' => $updated]);
1942                         Logger::info('Not updating relais', ['id' => $id, 'url' => $contact['url']]);
1943                         return true;
1944                 }
1945
1946                 // If Probe::uri fails the network code will be different ("feed" or "unkn")
1947                 if (in_array($ret['network'], [Protocol::FEED, Protocol::PHANTOM]) && ($ret['network'] != $contact['network'])) {
1948                         if ($force && ($uid == 0)) {
1949                                 self::updateContact($id, $uid, $ret['url'], ['failed' => true, 'last-update' => $updated, 'failure_update' => $updated]);
1950                         }
1951                         return false;
1952                 }
1953
1954                 if (Contact\Relation::isDiscoverable($ret['url'])) {
1955                         Worker::add(PRIORITY_LOW, 'ContactDiscovery', $ret['url']);
1956                 }
1957
1958                 if (isset($ret['hide']) && is_bool($ret['hide'])) {
1959                         $ret['unsearchable'] = $ret['hide'];
1960                 }
1961
1962                 if (isset($ret['account-type']) && is_int($ret['account-type'])) {
1963                         $ret['forum'] = false;
1964                         $ret['prv'] = false;
1965                         $ret['contact-type'] = $ret['account-type'];
1966                         if ($ret['contact-type'] == User::ACCOUNT_TYPE_COMMUNITY) {
1967                                 $apcontact = APContact::getByURL($ret['url'], false);
1968                                 if (isset($apcontact['manually-approve'])) {
1969                                         $ret['forum'] = (bool)!$apcontact['manually-approve'];
1970                                         $ret['prv'] = (bool)!$ret['forum'];
1971                                 }
1972                         }
1973                 }
1974
1975                 $new_pubkey = $ret['pubkey'];
1976
1977                 $update = false;
1978
1979                 // make sure to not overwrite existing values with blank entries except some technical fields
1980                 $keep = ['batch', 'notify', 'poll', 'request', 'confirm', 'poco', 'baseurl'];
1981                 foreach ($ret as $key => $val) {
1982                         if (!array_key_exists($key, $contact)) {
1983                                 unset($ret[$key]);
1984                         } elseif (($contact[$key] != '') && ($val === '') && !is_bool($ret[$key]) && !in_array($key, $keep)) {
1985                                 $ret[$key] = $contact[$key];
1986                         } elseif ($ret[$key] != $contact[$key]) {
1987                                 $update = true;
1988                         }
1989                 }
1990
1991                 if (!empty($ret['photo']) && ($ret['network'] != Protocol::FEED)) {
1992                         self::updateAvatar($id, $ret['photo'], $update || $force);
1993                 }
1994
1995                 if (!$update) {
1996                         if ($force) {
1997                                 self::updateContact($id, $uid, $ret['url'], ['failed' => false, 'last-update' => $updated, 'success_update' => $updated]);
1998                         }
1999
2000                         // Update the public contact
2001                         if ($uid != 0) {
2002                                 self::updateFromProbeByURL($ret['url']);
2003                         }
2004
2005                         return true;
2006                 }
2007
2008                 $ret['nurl'] = Strings::normaliseLink($ret['url']);
2009                 $ret['updated'] = $updated;
2010
2011                 // Only fill the pubkey if it had been empty before. We have to prevent identity theft.
2012                 if (empty($pubkey) && !empty($new_pubkey)) {
2013                         $ret['pubkey'] = $new_pubkey;
2014                 }
2015
2016                 if (($ret['addr'] != $contact['addr']) || (!empty($ret['alias']) && ($ret['alias'] != $contact['alias']))) {
2017                         $ret['uri-date'] = DateTimeFormat::utcNow();
2018                 }
2019
2020                 if (($ret['name'] != $contact['name']) || ($ret['nick'] != $contact['nick'])) {
2021                         $ret['name-date'] = $updated;
2022                 }
2023
2024                 if ($force && ($uid == 0)) {
2025                         $ret['last-update'] = $updated;
2026                         $ret['success_update'] = $updated;
2027                         $ret['failed'] = false;
2028                 }
2029
2030                 unset($ret['photo']);
2031
2032                 self::updateContact($id, $uid, $ret['url'], $ret);
2033
2034                 return true;
2035         }
2036
2037         public static function updateFromProbeByURL($url, $force = false)
2038         {
2039                 $id = self::getIdForURL($url);
2040
2041                 if (empty($id)) {
2042                         return $id;
2043                 }
2044
2045                 self::updateFromProbe($id, '', $force);
2046
2047                 return $id;
2048         }
2049
2050         /**
2051          * Detects if a given contact array belongs to a legacy DFRN connection
2052          *
2053          * @param array $contact
2054          * @return boolean
2055          */
2056         public static function isLegacyDFRNContact($contact)
2057         {
2058                 // Newer Friendica contacts are connected via AP, then these fields aren't set
2059                 return !empty($contact['dfrn-id']) || !empty($contact['issued-id']);
2060         }
2061
2062         /**
2063          * Detects the communication protocol for a given contact url.
2064          * This is used to detect Friendica contacts that we can communicate via AP.
2065          *
2066          * @param string $url contact url
2067          * @param string $network Network of that contact
2068          * @return string with protocol
2069          */
2070         public static function getProtocol($url, $network)
2071         {
2072                 if ($network != Protocol::DFRN) {
2073                         return $network;
2074                 }
2075
2076                 $apcontact = APContact::getByURL($url);
2077                 if (!empty($apcontact) && !empty($apcontact['generator'])) {
2078                         return Protocol::ACTIVITYPUB;
2079                 } else {
2080                         return $network;
2081                 }
2082         }
2083
2084         /**
2085          * Takes a $uid and a url/handle and adds a new contact
2086          *
2087          * Currently if the contact is DFRN, interactive needs to be true, to redirect to the
2088          * dfrn_request page.
2089          *
2090          * Otherwise this can be used to bulk add StatusNet contacts, Twitter contacts, etc.
2091          *
2092          * Returns an array
2093          * $return['success'] boolean true if successful
2094          * $return['message'] error text if success is false.
2095          *
2096          * Takes a $uid and a url/handle and adds a new contact
2097          *
2098          * @param array  $user        The user the contact should be created for
2099          * @param string $url         The profile URL of the contact
2100          * @param bool   $interactive
2101          * @param string $network
2102          * @return array
2103          * @throws HTTPException\InternalServerErrorException
2104          * @throws HTTPException\NotFoundException
2105          * @throws \ImagickException
2106          */
2107         public static function createFromProbe(array $user, $url, $interactive = false, $network = '')
2108         {
2109                 $result = ['cid' => -1, 'success' => false, 'message' => ''];
2110
2111                 // remove ajax junk, e.g. Twitter
2112                 $url = str_replace('/#!/', '/', $url);
2113
2114                 if (!Network::isUrlAllowed($url)) {
2115                         $result['message'] = DI::l10n()->t('Disallowed profile URL.');
2116                         return $result;
2117                 }
2118
2119                 if (Network::isUrlBlocked($url)) {
2120                         $result['message'] = DI::l10n()->t('Blocked domain');
2121                         return $result;
2122                 }
2123
2124                 if (!$url) {
2125                         $result['message'] = DI::l10n()->t('Connect URL missing.');
2126                         return $result;
2127                 }
2128
2129                 $arr = ['url' => $url, 'contact' => []];
2130
2131                 Hook::callAll('follow', $arr);
2132
2133                 if (empty($arr)) {
2134                         $result['message'] = DI::l10n()->t('The contact could not be added. Please check the relevant network credentials in your Settings -> Social Networks page.');
2135                         return $result;
2136                 }
2137
2138                 if (!empty($arr['contact']['name'])) {
2139                         $ret = $arr['contact'];
2140                 } else {
2141                         $ret = Probe::uri($url, $network, $user['uid'], false);
2142                 }
2143
2144                 if (($network != '') && ($ret['network'] != $network)) {
2145                         Logger::log('Expected network ' . $network . ' does not match actual network ' . $ret['network']);
2146                         return $result;
2147                 }
2148
2149                 // check if we already have a contact
2150                 // the poll url is more reliable than the profile url, as we may have
2151                 // indirect links or webfinger links
2152
2153                 $condition = ['uid' => $user['uid'], 'poll' => [$ret['poll'], Strings::normaliseLink($ret['poll'])], 'network' => $ret['network'], 'pending' => false];
2154                 $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
2155                 if (!DBA::isResult($contact)) {
2156                         $condition = ['uid' => $user['uid'], 'nurl' => Strings::normaliseLink($ret['url']), 'network' => $ret['network'], 'pending' => false];
2157                         $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
2158                 }
2159
2160                 $protocol = self::getProtocol($ret['url'], $ret['network']);
2161
2162                 if (($protocol === Protocol::DFRN) && !DBA::isResult($contact)) {
2163                         if ($interactive) {
2164                                 if (strlen(DI::baseUrl()->getUrlPath())) {
2165                                         $myaddr = bin2hex(DI::baseUrl() . '/profile/' . $user['nickname']);
2166                                 } else {
2167                                         $myaddr = bin2hex($user['nickname'] . '@' . DI::baseUrl()->getHostname());
2168                                 }
2169
2170                                 DI::baseUrl()->redirect($ret['request'] . "&addr=$myaddr");
2171
2172                                 // NOTREACHED
2173                         }
2174                 } elseif (DI::config()->get('system', 'dfrn_only') && ($ret['network'] != Protocol::DFRN)) {
2175                         $result['message'] = DI::l10n()->t('This site is not configured to allow communications with other networks.') . EOL;
2176                         $result['message'] .= DI::l10n()->t('No compatible communication protocols or feeds were discovered.') . EOL;
2177                         return $result;
2178                 }
2179
2180                 // This extra param just confuses things, remove it
2181                 if ($protocol === Protocol::DIASPORA) {
2182                         $ret['url'] = str_replace('?absolute=true', '', $ret['url']);
2183                 }
2184
2185                 // do we have enough information?
2186                 if (empty($ret['name']) || empty($ret['poll']) || (empty($ret['url']) && empty($ret['addr']))) {
2187                         $result['message'] .= DI::l10n()->t('The profile address specified does not provide adequate information.') . EOL;
2188                         if (empty($ret['poll'])) {
2189                                 $result['message'] .= DI::l10n()->t('No compatible communication protocols or feeds were discovered.') . EOL;
2190                         }
2191                         if (empty($ret['name'])) {
2192                                 $result['message'] .= DI::l10n()->t('An author or name was not found.') . EOL;
2193                         }
2194                         if (empty($ret['url'])) {
2195                                 $result['message'] .= DI::l10n()->t('No browser URL could be matched to this address.') . EOL;
2196                         }
2197                         if (strpos($ret['url'], '@') !== false) {
2198                                 $result['message'] .= DI::l10n()->t('Unable to match @-style Identity Address with a known protocol or email contact.') . EOL;
2199                                 $result['message'] .= DI::l10n()->t('Use mailto: in front of address to force email check.') . EOL;
2200                         }
2201                         return $result;
2202                 }
2203
2204                 if ($protocol === Protocol::OSTATUS && DI::config()->get('system', 'ostatus_disabled')) {
2205                         $result['message'] .= DI::l10n()->t('The profile address specified belongs to a network which has been disabled on this site.') . EOL;
2206                         $ret['notify'] = '';
2207                 }
2208
2209                 if (!$ret['notify']) {
2210                         $result['message'] .= DI::l10n()->t('Limited profile. This person will be unable to receive direct/personal notifications from you.') . EOL;
2211                 }
2212
2213                 $writeable = ((($protocol === Protocol::OSTATUS) && ($ret['notify'])) ? 1 : 0);
2214
2215                 $subhub = (($protocol === Protocol::OSTATUS) ? true : false);
2216
2217                 $hidden = (($protocol === Protocol::MAIL) ? 1 : 0);
2218
2219                 $pending = false;
2220                 if ($protocol == Protocol::ACTIVITYPUB) {
2221                         $apcontact = APContact::getByURL($ret['url'], false);
2222                         if (isset($apcontact['manually-approve'])) {
2223                                 $pending = (bool)$apcontact['manually-approve'];
2224                         }
2225                 }
2226
2227                 if (in_array($protocol, [Protocol::MAIL, Protocol::DIASPORA, Protocol::ACTIVITYPUB])) {
2228                         $writeable = 1;
2229                 }
2230
2231                 if (DBA::isResult($contact)) {
2232                         // update contact
2233                         $new_relation = (($contact['rel'] == self::FOLLOWER) ? self::FRIEND : self::SHARING);
2234
2235                         $fields = ['rel' => $new_relation, 'subhub' => $subhub, 'readonly' => false];
2236                         DBA::update('contact', $fields, ['id' => $contact['id']]);
2237                 } else {
2238                         $new_relation = (in_array($protocol, [Protocol::MAIL]) ? self::FRIEND : self::SHARING);
2239
2240                         // create contact record
2241                         self::insert([
2242                                 'uid'     => $user['uid'],
2243                                 'created' => DateTimeFormat::utcNow(),
2244                                 'url'     => $ret['url'],
2245                                 'nurl'    => Strings::normaliseLink($ret['url']),
2246                                 'addr'    => $ret['addr'],
2247                                 'alias'   => $ret['alias'],
2248                                 'batch'   => $ret['batch'],
2249                                 'notify'  => $ret['notify'],
2250                                 'poll'    => $ret['poll'],
2251                                 'poco'    => $ret['poco'],
2252                                 'name'    => $ret['name'],
2253                                 'nick'    => $ret['nick'],
2254                                 'network' => $ret['network'],
2255                                 'baseurl' => $ret['baseurl'],
2256                                 'gsid'    => $ret['gsid'] ?? null,
2257                                 'protocol' => $protocol,
2258                                 'pubkey'  => $ret['pubkey'],
2259                                 'rel'     => $new_relation,
2260                                 'priority'=> $ret['priority'],
2261                                 'writable'=> $writeable,
2262                                 'hidden'  => $hidden,
2263                                 'blocked' => 0,
2264                                 'readonly'=> 0,
2265                                 'pending' => $pending,
2266                                 'subhub'  => $subhub
2267                         ]);
2268                 }
2269
2270                 $contact = DBA::selectFirst('contact', [], ['url' => $ret['url'], 'network' => $ret['network'], 'uid' => $user['uid']]);
2271                 if (!DBA::isResult($contact)) {
2272                         $result['message'] .= DI::l10n()->t('Unable to retrieve contact information.') . EOL;
2273                         return $result;
2274                 }
2275
2276                 $contact_id = $contact['id'];
2277                 $result['cid'] = $contact_id;
2278
2279                 Group::addMember(User::getDefaultGroup($user['uid'], $contact["network"]), $contact_id);
2280
2281                 // Update the avatar
2282                 self::updateAvatar($contact_id, $ret['photo']);
2283
2284                 // pull feed and consume it, which should subscribe to the hub.
2285
2286                 Worker::add(PRIORITY_HIGH, "OnePoll", $contact_id, "force");
2287
2288                 $owner = User::getOwnerDataById($user['uid']);
2289
2290                 if (DBA::isResult($owner)) {
2291                         if (in_array($protocol, [Protocol::OSTATUS, Protocol::DFRN])) {
2292                                 // create a follow slap
2293                                 $item = [];
2294                                 $item['verb'] = Activity::FOLLOW;
2295                                 $item['gravity'] = GRAVITY_ACTIVITY;
2296                                 $item['follow'] = $contact["url"];
2297                                 $item['body'] = '';
2298                                 $item['title'] = '';
2299                                 $item['guid'] = '';
2300                                 $item['uri-id'] = 0;
2301                                 $item['attach'] = '';
2302
2303                                 $slap = OStatus::salmon($item, $owner);
2304
2305                                 if (!empty($contact['notify'])) {
2306                                         Salmon::slapper($owner, $contact['notify'], $slap);
2307                                 }
2308                         } elseif ($protocol == Protocol::DIASPORA) {
2309                                 $ret = Diaspora::sendShare($owner, $contact);
2310                                 Logger::log('share returns: ' . $ret);
2311                         } elseif ($protocol == Protocol::ACTIVITYPUB) {
2312                                 $activity_id = ActivityPub\Transmitter::activityIDFromContact($contact_id);
2313                                 if (empty($activity_id)) {
2314                                         // This really should never happen
2315                                         return false;
2316                                 }
2317
2318                                 $ret = ActivityPub\Transmitter::sendActivity('Follow', $contact['url'], $user['uid'], $activity_id);
2319                                 Logger::log('Follow returns: ' . $ret);
2320                         }
2321                 }
2322
2323                 $result['success'] = true;
2324                 return $result;
2325         }
2326
2327         /**
2328          * Updated contact's SSL policy
2329          *
2330          * @param array  $contact    Contact array
2331          * @param string $new_policy New policy, valid: self,full
2332          *
2333          * @return array Contact array with updated values
2334          * @throws \Exception
2335          */
2336         public static function updateSslPolicy(array $contact, $new_policy)
2337         {
2338                 $ssl_changed = false;
2339                 if ((intval($new_policy) == BaseURL::SSL_POLICY_SELFSIGN || $new_policy === 'self') && strstr($contact['url'], 'https:')) {
2340                         $ssl_changed = true;
2341                         $contact['url']     =   str_replace('https:', 'http:', $contact['url']);
2342                         $contact['request'] =   str_replace('https:', 'http:', $contact['request']);
2343                         $contact['notify']  =   str_replace('https:', 'http:', $contact['notify']);
2344                         $contact['poll']    =   str_replace('https:', 'http:', $contact['poll']);
2345                         $contact['confirm'] =   str_replace('https:', 'http:', $contact['confirm']);
2346                         $contact['poco']    =   str_replace('https:', 'http:', $contact['poco']);
2347                 }
2348
2349                 if ((intval($new_policy) == BaseURL::SSL_POLICY_FULL || $new_policy === 'full') && strstr($contact['url'], 'http:')) {
2350                         $ssl_changed = true;
2351                         $contact['url']     =   str_replace('http:', 'https:', $contact['url']);
2352                         $contact['request'] =   str_replace('http:', 'https:', $contact['request']);
2353                         $contact['notify']  =   str_replace('http:', 'https:', $contact['notify']);
2354                         $contact['poll']    =   str_replace('http:', 'https:', $contact['poll']);
2355                         $contact['confirm'] =   str_replace('http:', 'https:', $contact['confirm']);
2356                         $contact['poco']    =   str_replace('http:', 'https:', $contact['poco']);
2357                 }
2358
2359                 if ($ssl_changed) {
2360                         $fields = ['url' => $contact['url'], 'request' => $contact['request'],
2361                                         'notify' => $contact['notify'], 'poll' => $contact['poll'],
2362                                         'confirm' => $contact['confirm'], 'poco' => $contact['poco']];
2363                         DBA::update('contact', $fields, ['id' => $contact['id']]);
2364                 }
2365
2366                 return $contact;
2367         }
2368
2369         /**
2370          * @param array  $importer Owner (local user) data
2371          * @param array  $contact  Existing owner-specific contact data we want to expand the relationship with. Optional.
2372          * @param array  $datarray An item-like array with at least the 'author-id' and 'author-url' keys for the contact. Mandatory.
2373          * @param bool   $sharing  True: Contact is now sharing with Owner; False: Contact is now following Owner (default)
2374          * @param string $note     Introduction additional message
2375          * @return bool|null True: follow request is accepted; False: relationship is rejected; Null: relationship is pending
2376          * @throws HTTPException\InternalServerErrorException
2377          * @throws \ImagickException
2378          */
2379         public static function addRelationship(array $importer, array $contact, array $datarray, $sharing = false, $note = '')
2380         {
2381                 // Should always be set
2382                 if (empty($datarray['author-id'])) {
2383                         return false;
2384                 }
2385
2386                 $fields = ['url', 'name', 'nick', 'avatar', 'photo', 'network', 'blocked'];
2387                 $pub_contact = DBA::selectFirst('contact', $fields, ['id' => $datarray['author-id']]);
2388                 if (!DBA::isResult($pub_contact)) {
2389                         // Should never happen
2390                         return false;
2391                 }
2392
2393                 // Contact is blocked at node-level
2394                 if (self::isBlocked($datarray['author-id'])) {
2395                         return false;
2396                 }
2397
2398                 $url = ($datarray['author-link'] ?? '') ?: $pub_contact['url'];
2399                 $name = $pub_contact['name'];
2400                 $photo = ($pub_contact['avatar'] ?? '') ?: $pub_contact["photo"];
2401                 $nick = $pub_contact['nick'];
2402                 $network = $pub_contact['network'];
2403
2404                 // Ensure that we don't create a new contact when there already is one
2405                 $cid = self::getIdForURL($url, $importer['uid']);
2406                 if (!empty($cid)) {
2407                         $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
2408                 }
2409
2410                 if (!empty($contact)) {
2411                         if (!empty($contact['pending'])) {
2412                                 Logger::info('Pending contact request already exists.', ['url' => $url, 'uid' => $importer['uid']]);
2413                                 return null;
2414                         }
2415
2416                         // Contact is blocked at user-level
2417                         if (!empty($contact['id']) && !empty($importer['id']) &&
2418                                 Contact\User::isBlocked($contact['id'], $importer['id'])) {
2419                                 return false;
2420                         }
2421
2422                         // Make sure that the existing contact isn't archived
2423                         self::unmarkForArchival($contact);
2424
2425                         if (($contact['rel'] == self::SHARING)
2426                                 || ($sharing && $contact['rel'] == self::FOLLOWER)) {
2427                                 DBA::update('contact', ['rel' => self::FRIEND, 'writable' => true, 'pending' => false],
2428                                                 ['id' => $contact['id'], 'uid' => $importer['uid']]);
2429                         }
2430
2431                         // Ensure to always have the correct network type, independent from the connection request method
2432                         self::updateFromProbe($contact['id'], '', true);
2433
2434                         return true;
2435                 } else {
2436                         // send email notification to owner?
2437                         if (DBA::exists('contact', ['nurl' => Strings::normaliseLink($url), 'uid' => $importer['uid'], 'pending' => true])) {
2438                                 Logger::log('ignoring duplicated connection request from pending contact ' . $url);
2439                                 return null;
2440                         }
2441
2442                         // create contact record
2443                         DBA::insert('contact', [
2444                                 'uid'      => $importer['uid'],
2445                                 'created'  => DateTimeFormat::utcNow(),
2446                                 'url'      => $url,
2447                                 'nurl'     => Strings::normaliseLink($url),
2448                                 'name'     => $name,
2449                                 'nick'     => $nick,
2450                                 'network'  => $network,
2451                                 'rel'      => self::FOLLOWER,
2452                                 'blocked'  => 0,
2453                                 'readonly' => 0,
2454                                 'pending'  => 1,
2455                                 'writable' => 1,
2456                         ]);
2457
2458                         $contact_id = DBA::lastInsertId();
2459
2460                         // Ensure to always have the correct network type, independent from the connection request method
2461                         self::updateFromProbe($contact_id, '', true);
2462
2463                         self::updateAvatar($contact_id, $photo, true);
2464
2465                         $contact_record = DBA::selectFirst('contact', ['id', 'network', 'name', 'url', 'photo'], ['id' => $contact_id]);
2466
2467                         /// @TODO Encapsulate this into a function/method
2468                         $fields = ['uid', 'username', 'email', 'page-flags', 'notify-flags', 'language'];
2469                         $user = DBA::selectFirst('user', $fields, ['uid' => $importer['uid']]);
2470                         if (DBA::isResult($user) && !in_array($user['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_FREELOVE, User::PAGE_FLAGS_COMMUNITY])) {
2471                                 // create notification
2472                                 $hash = Strings::getRandomHex();
2473
2474                                 if (is_array($contact_record)) {
2475                                         DBA::insert('intro', ['uid' => $importer['uid'], 'contact-id' => $contact_record['id'],
2476                                                                 'blocked' => false, 'knowyou' => false, 'note' => $note,
2477                                                                 'hash' => $hash, 'datetime' => DateTimeFormat::utcNow()]);
2478                                 }
2479
2480                                 Group::addMember(User::getDefaultGroup($importer['uid'], $contact_record["network"]), $contact_record['id']);
2481
2482                                 if (($user['notify-flags'] & Type::INTRO) &&
2483                                         in_array($user['page-flags'], [User::PAGE_FLAGS_NORMAL])) {
2484
2485                                         notification([
2486                                                 'type'         => Type::INTRO,
2487                                                 'notify_flags' => $user['notify-flags'],
2488                                                 'language'     => $user['language'],
2489                                                 'to_name'      => $user['username'],
2490                                                 'to_email'     => $user['email'],
2491                                                 'uid'          => $user['uid'],
2492                                                 'link'         => DI::baseUrl() . '/notifications/intros',
2493                                                 'source_name'  => ((strlen(stripslashes($contact_record['name']))) ? stripslashes($contact_record['name']) : DI::l10n()->t('[Name Withheld]')),
2494                                                 'source_link'  => $contact_record['url'],
2495                                                 'source_photo' => $contact_record['photo'],
2496                                                 'verb'         => ($sharing ? Activity::FRIEND : Activity::FOLLOW),
2497                                                 'otype'        => 'intro'
2498                                         ]);
2499                                 }
2500                         } elseif (DBA::isResult($user) && in_array($user['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_FREELOVE, User::PAGE_FLAGS_COMMUNITY])) {
2501                                 if (($user['page-flags'] == User::PAGE_FLAGS_FREELOVE) && ($network != Protocol::DIASPORA)) {
2502                                         self::createFromProbe($importer, $url, false, $network);
2503                                 }
2504
2505                                 $condition = ['uid' => $importer['uid'], 'url' => $url, 'pending' => true];
2506                                 $fields = ['pending' => false];
2507                                 if ($user['page-flags'] == User::PAGE_FLAGS_FREELOVE) {
2508                                         $fields['rel'] = Contact::FRIEND;
2509                                 }
2510
2511                                 DBA::update('contact', $fields, $condition);
2512
2513                                 return true;
2514                         }
2515                 }
2516
2517                 return null;
2518         }
2519
2520         public static function removeFollower($importer, $contact, array $datarray = [], $item = "")
2521         {
2522                 if (($contact['rel'] == self::FRIEND) || ($contact['rel'] == self::SHARING)) {
2523                         DBA::update('contact', ['rel' => self::SHARING], ['id' => $contact['id']]);
2524                 } else {
2525                         Contact::remove($contact['id']);
2526                 }
2527         }
2528
2529         public static function removeSharer($importer, $contact, array $datarray = [], $item = "")
2530         {
2531                 if (($contact['rel'] == self::FRIEND) || ($contact['rel'] == self::FOLLOWER)) {
2532                         DBA::update('contact', ['rel' => self::FOLLOWER], ['id' => $contact['id']]);
2533                 } else {
2534                         Contact::remove($contact['id']);
2535                 }
2536         }
2537
2538         /**
2539          * Create a birthday event.
2540          *
2541          * Update the year and the birthday.
2542          */
2543         public static function updateBirthdays()
2544         {
2545                 $condition = [
2546                         '`bd` != ""
2547                         AND `bd` > "0001-01-01"
2548                         AND SUBSTRING(`bd`, 1, 4) != `bdyear`
2549                         AND (`contact`.`rel` = ? OR `contact`.`rel` = ?)
2550                         AND NOT `contact`.`pending`
2551                         AND NOT `contact`.`hidden`
2552                         AND NOT `contact`.`blocked`
2553                         AND NOT `contact`.`archive`
2554                         AND NOT `contact`.`deleted`',
2555                         Contact::SHARING,
2556                         Contact::FRIEND
2557                 ];
2558
2559                 $contacts = DBA::select('contact', ['id', 'uid', 'name', 'url', 'bd'], $condition);
2560
2561                 while ($contact = DBA::fetch($contacts)) {
2562                         Logger::log('update_contact_birthday: ' . $contact['bd']);
2563
2564                         $nextbd = DateTimeFormat::utcNow('Y') . substr($contact['bd'], 4);
2565
2566                         if (Event::createBirthday($contact, $nextbd)) {
2567                                 // update bdyear
2568                                 DBA::update(
2569                                         'contact',
2570                                         ['bdyear' => substr($nextbd, 0, 4), 'bd' => $nextbd],
2571                                         ['id' => $contact['id']]
2572                                 );
2573                         }
2574                 }
2575                 DBA::close($contacts);
2576         }
2577
2578         /**
2579          * Remove the unavailable contact ids from the provided list
2580          *
2581          * @param array $contact_ids Contact id list
2582          * @return array
2583          * @throws \Exception
2584          */
2585         public static function pruneUnavailable(array $contact_ids)
2586         {
2587                 if (empty($contact_ids)) {
2588                         return [];
2589                 }
2590
2591                 $contacts = Contact::selectToArray(['id'], [
2592                         'id'      => $contact_ids,
2593                         'blocked' => false,
2594                         'pending' => false,
2595                         'archive' => false,
2596                 ]);
2597
2598                 return array_column($contacts, 'id');
2599         }
2600
2601         /**
2602          * Returns a magic link to authenticate remote visitors
2603          *
2604          * @todo  check if the return is either a fully qualified URL or a relative path to Friendica basedir
2605          *
2606          * @param string $contact_url The address of the target contact profile
2607          * @param string $url         An url that we will be redirected to after the authentication
2608          *
2609          * @return string with "redir" link
2610          * @throws HTTPException\InternalServerErrorException
2611          * @throws \ImagickException
2612          */
2613         public static function magicLink($contact_url, $url = '')
2614         {
2615                 if (!Session::isAuthenticated()) {
2616                         return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
2617                 }
2618
2619                 $data = self::getProbeDataFromDatabase($contact_url);
2620                 if (empty($data)) {
2621                         return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
2622                 }
2623
2624                 // Prevents endless loop in case only a non-public contact exists for the contact URL
2625                 unset($data['uid']);
2626
2627                 return self::magicLinkByContact($data, $url ?: $contact_url);
2628         }
2629
2630         /**
2631          * Returns a magic link to authenticate remote visitors
2632          *
2633          * @param integer $cid The contact id of the target contact profile
2634          * @param string  $url An url that we will be redirected to after the authentication
2635          *
2636          * @return string with "redir" link
2637          * @throws HTTPException\InternalServerErrorException
2638          * @throws \ImagickException
2639          */
2640         public static function magicLinkbyId($cid, $url = '')
2641         {
2642                 $contact = DBA::selectFirst('contact', ['id', 'network', 'url', 'uid'], ['id' => $cid]);
2643
2644                 return self::magicLinkByContact($contact, $url);
2645         }
2646
2647         /**
2648          * Returns a magic link to authenticate remote visitors
2649          *
2650          * @param array  $contact The contact array with "uid", "network" and "url"
2651          * @param string $url     An url that we will be redirected to after the authentication
2652          *
2653          * @return string with "redir" link
2654          * @throws HTTPException\InternalServerErrorException
2655          * @throws \ImagickException
2656          */
2657         public static function magicLinkByContact($contact, $url = '')
2658         {
2659                 $destination = $url ?: $contact['url']; // Equivalent to ($url != '') ? $url : $contact['url'];
2660
2661                 if (!Session::isAuthenticated() || ($contact['network'] != Protocol::DFRN)) {
2662                         return $destination;
2663                 }
2664
2665                 // Only redirections to the same host do make sense
2666                 if (($url != '') && (parse_url($url, PHP_URL_HOST) != parse_url($contact['url'], PHP_URL_HOST))) {
2667                         return $url;
2668                 }
2669
2670                 if (!empty($contact['uid'])) {
2671                         return self::magicLink($contact['url'], $url);
2672                 }
2673
2674                 if (empty($contact['id'])) {
2675                         return $destination;
2676                 }
2677
2678                 $redirect = 'redir/' . $contact['id'];
2679
2680                 if (($url != '') && !Strings::compareLink($contact['url'], $url)) {
2681                         $redirect .= '?url=' . $url;
2682                 }
2683
2684                 return $redirect;
2685         }
2686
2687         /**
2688          * Remove a contact from all groups
2689          *
2690          * @param integer $contact_id
2691          *
2692          * @return boolean Success
2693          */
2694         public static function removeFromGroups($contact_id)
2695         {
2696                 return DBA::delete('group_member', ['contact-id' => $contact_id]);
2697         }
2698
2699         /**
2700          * Is the contact a forum?
2701          *
2702          * @param integer $contactid ID of the contact
2703          *
2704          * @return boolean "true" if it is a forum
2705          */
2706         public static function isForum($contactid)
2707         {
2708                 $fields = ['forum', 'prv'];
2709                 $condition = ['id' => $contactid];
2710                 $contact = DBA::selectFirst('contact', $fields, $condition);
2711                 if (!DBA::isResult($contact)) {
2712                         return false;
2713                 }
2714
2715                 // Is it a forum?
2716                 return ($contact['forum'] || $contact['prv']);
2717         }
2718
2719         /**
2720          * Can the remote contact receive private messages?
2721          *
2722          * @param array $contact
2723          * @return bool
2724          */
2725         public static function canReceivePrivateMessages(array $contact)
2726         {
2727                 $protocol = $contact['network'] ?? $contact['protocol'] ?? Protocol::PHANTOM;
2728                 $self = $contact['self'] ?? false;
2729
2730                 return in_array($protocol, [Protocol::DFRN, Protocol::DIASPORA, Protocol::ACTIVITYPUB]) && !$self;
2731         }
2732
2733         /**
2734          * Search contact table by nick or name
2735          *
2736          * @param string $search Name or nick
2737          * @param string $mode   Search mode (e.g. "community")
2738          *
2739          * @return array with search results
2740          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2741          */
2742         public static function searchByName($search, $mode = '')
2743         {
2744                 if (empty($search)) {
2745                         return [];
2746                 }
2747
2748                 // check supported networks
2749                 if (DI::config()->get('system', 'diaspora_enabled')) {
2750                         $diaspora = Protocol::DIASPORA;
2751                 } else {
2752                         $diaspora = Protocol::DFRN;
2753                 }
2754
2755                 if (!DI::config()->get('system', 'ostatus_disabled')) {
2756                         $ostatus = Protocol::OSTATUS;
2757                 } else {
2758                         $ostatus = Protocol::DFRN;
2759                 }
2760
2761                 // check if we search only communities or every contact
2762                 if ($mode === 'community') {
2763                         $extra_sql = sprintf(' AND `contact-type` = %d', Contact::TYPE_COMMUNITY);
2764                 } else {
2765                         $extra_sql = '';
2766                 }
2767
2768                 $search .= '%';
2769
2770                 $results = DBA::p("SELECT * FROM `contact`
2771                         WHERE NOT `unsearchable` AND `network` IN (?, ?, ?, ?) AND
2772                                 NOT `failed` AND `uid` = ? AND
2773                                 (`addr` LIKE ? OR `name` LIKE ? OR `nick` LIKE ?) $extra_sql
2774                                 ORDER BY `nurl` DESC LIMIT 1000",
2775                         Protocol::DFRN, Protocol::ACTIVITYPUB, $ostatus, $diaspora, 0, $search, $search, $search
2776                 );
2777
2778                 $contacts = DBA::toArray($results);
2779                 return $contacts;
2780         }
2781
2782         /**
2783          * Add public contacts from an array
2784          *
2785          * @param array $urls
2786          * @return array result "count", "added" and "updated"
2787          */
2788         public static function addByUrls(array $urls)
2789         {
2790                 $added = 0;
2791                 $updated = 0;
2792                 $count = 0;
2793
2794                 foreach ($urls as $url) {
2795                         $contact = Contact::getByURL($url, false, ['id']); 
2796                         if (empty($contact['id'])) {
2797                                 Worker::add(PRIORITY_LOW, 'AddContact', 0, $url);
2798                                 ++$added;
2799                         } else {
2800                                 Worker::add(PRIORITY_LOW, 'UpdateContact', $contact['id']);
2801                                 ++$updated;
2802                         }
2803                         ++$count;
2804                 }
2805
2806                 return ['count' => $count, 'added' => $added, 'updated' => $updated];
2807         }
2808
2809         /**
2810          * Set the last date that the contact had posted something
2811          *
2812          * This functionality is currently unused
2813          *
2814          * @param string $data  probing result
2815          * @param bool   $force force updating
2816          */
2817         private static function setLastUpdate(array $data, bool $force = false)
2818         {
2819                 $contact = self::getByURL($data['url'], false, []);
2820                 if (empty($contact)) {
2821                         return;
2822                 }
2823                 if (!$force && !GServer::updateNeeded($contact['created'], $contact['updated'], $contact['last_failure'], $contact['last_contact'])) {
2824                         Logger::info("Don't update profile", ['url' => $data['url'], 'updated' => $contact['updated']]);
2825                         return;
2826                 }
2827
2828                 if (self::updateFromNoScrape($data)) {
2829                         return;
2830                 }
2831
2832                 if (!empty($data['outbox'])) {
2833                         self::updateFromOutbox($data['outbox'], $data);
2834                 } elseif (!empty($data['poll']) && ($data['network'] == Protocol::ACTIVITYPUB)) {
2835                         self::updateFromOutbox($data['poll'], $data);
2836                 } elseif (!empty($data['poll'])) {
2837                         self::updateFromFeed($data);
2838                 }
2839         }
2840
2841         /**
2842          * Update a global contact via the "noscrape" endpoint
2843          *
2844          * @param string $data Probing result
2845          *
2846          * @return bool 'true' if update was successful or the server was unreachable
2847          */
2848         private static function updateFromNoScrape(array $data)
2849         {
2850                 // Check the 'noscrape' endpoint when it is a Friendica server
2851                 $gserver = DBA::selectFirst('gserver', ['noscrape'], ["`nurl` = ? AND `noscrape` != ''",
2852                 Strings::normaliseLink($data['baseurl'])]);
2853                 if (!DBA::isResult($gserver)) {
2854                         return false;
2855                 }
2856
2857                 $curlResult = DI::httpRequest()->get($gserver['noscrape'] . '/' . $data['nick']);
2858
2859                 if ($curlResult->isSuccess() && !empty($curlResult->getBody())) {
2860                         $noscrape = json_decode($curlResult->getBody(), true);
2861                         if (!empty($noscrape) && !empty($noscrape['updated'])) {
2862                                 $noscrape['updated'] = DateTimeFormat::utc($noscrape['updated'], DateTimeFormat::MYSQL);
2863                                 $fields = ['failed' => false, 'last_contact' => DateTimeFormat::utcNow(), 'updated' => $noscrape['updated']];
2864                                 DBA::update('contact', $fields, ['nurl' => Strings::normaliseLink($data['url'])]);
2865                                 return true;
2866                         }
2867                 } elseif ($curlResult->isTimeout()) {
2868                         // On a timeout return the existing value, but mark the contact as failure
2869                         $fields = ['failed' => true, 'last_failure' => DateTimeFormat::utcNow()];
2870                         DBA::update('contact', $fields, ['nurl' => Strings::normaliseLink($data['url'])]);
2871                         return true;
2872                 }
2873                 return false;
2874         }
2875
2876         /**
2877          * Update a global contact via an ActivityPub Outbox
2878          *
2879          * @param string $feed
2880          * @param array  $data Probing result
2881          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2882          */
2883         private static function updateFromOutbox(string $feed, array $data)
2884         {
2885                 $outbox = ActivityPub::fetchContent($feed);
2886                 if (empty($outbox)) {
2887                         return;
2888                 }
2889
2890                 if (!empty($outbox['orderedItems'])) {
2891                         $items = $outbox['orderedItems'];
2892                 } elseif (!empty($outbox['first']['orderedItems'])) {
2893                         $items = $outbox['first']['orderedItems'];
2894                 } elseif (!empty($outbox['first']['href']) && ($outbox['first']['href'] != $feed)) {
2895                         self::updateFromOutbox($outbox['first']['href'], $data);
2896                         return;
2897                 } elseif (!empty($outbox['first'])) {
2898                         if (is_string($outbox['first']) && ($outbox['first'] != $feed)) {
2899                                 self::updateFromOutbox($outbox['first'], $data);
2900                         } else {
2901                                 Logger::warning('Unexpected data', ['outbox' => $outbox]);
2902                         }
2903                         return;
2904                 } else {
2905                         $items = [];
2906                 }
2907
2908                 $last_updated = '';
2909                 foreach ($items as $activity) {
2910                         if (!empty($activity['published'])) {
2911                                 $published =  DateTimeFormat::utc($activity['published']);
2912                         } elseif (!empty($activity['object']['published'])) {
2913                                 $published =  DateTimeFormat::utc($activity['object']['published']);
2914                         } else {
2915                                 continue;
2916                         }
2917
2918                         if ($last_updated < $published) {
2919                                 $last_updated = $published;
2920                         }
2921                 }
2922
2923                 if (empty($last_updated)) {
2924                         return;
2925                 }
2926
2927                 $fields = ['failed' => false, 'last_contact' => DateTimeFormat::utcNow(), 'updated' => $last_updated];
2928                 DBA::update('contact', $fields, ['nurl' => Strings::normaliseLink($data['url'])]);
2929         }
2930
2931         /**
2932          * Update a global contact via an XML feed
2933          *
2934          * @param string $data Probing result
2935          */
2936         private static function updateFromFeed(array $data)
2937         {
2938                 // Search for the newest entry in the feed
2939                 $curlResult = DI::httpRequest()->get($data['poll']);
2940                 if (!$curlResult->isSuccess()) {
2941                         $fields = ['failed' => true, 'last_failure' => DateTimeFormat::utcNow()];
2942                         DBA::update('contact', $fields, ['nurl' => Strings::normaliseLink($data['url'])]);
2943
2944                         Logger::info("Profile wasn't reachable (no feed)", ['url' => $data['url']]);
2945                         return;
2946                 }
2947
2948                 $doc = new DOMDocument();
2949                 @$doc->loadXML($curlResult->getBody());
2950
2951                 $xpath = new DOMXPath($doc);
2952                 $xpath->registerNamespace('atom', 'http://www.w3.org/2005/Atom');
2953
2954                 $entries = $xpath->query('/atom:feed/atom:entry');
2955
2956                 $last_updated = '';
2957
2958                 foreach ($entries as $entry) {
2959                         $published_item = $xpath->query('atom:published/text()', $entry)->item(0);
2960                         $updated_item   = $xpath->query('atom:updated/text()'  , $entry)->item(0);
2961                         $published      = !empty($published_item->nodeValue) ? DateTimeFormat::utc($published_item->nodeValue) : null;
2962                         $updated        = !empty($updated_item->nodeValue) ? DateTimeFormat::utc($updated_item->nodeValue) : null;
2963
2964                         if (empty($published) || empty($updated)) {
2965                                 Logger::notice('Invalid entry for XPath.', ['entry' => $entry, 'url' => $data['url']]);
2966                                 continue;
2967                         }
2968
2969                         if ($last_updated < $published) {
2970                                 $last_updated = $published;
2971                         }
2972
2973                         if ($last_updated < $updated) {
2974                                 $last_updated = $updated;
2975                         }
2976                 }
2977
2978                 if (empty($last_updated)) {
2979                         return;
2980                 }
2981
2982                 $fields = ['failed' => false, 'last_contact' => DateTimeFormat::utcNow(), 'updated' => $last_updated];
2983                 DBA::update('contact', $fields, ['nurl' => Strings::normaliseLink($data['url'])]);
2984         }
2985
2986         /**
2987          * Returns a random, global contact of the current node
2988          *
2989          * @return string The profile URL
2990          * @throws Exception
2991          */
2992         public static function getRandomUrl()
2993         {
2994                 $r = DBA::selectFirst('contact', ['url'], [
2995                         "`uid` = ? AND `network` = ? AND NOT `failed` AND `last-item` > ?",
2996                         0, Protocol::DFRN, DateTimeFormat::utc('now - 1 month'),
2997                 ], ['order' => ['RAND()']]);
2998
2999                 if (DBA::isResult($r)) {
3000                         return $r['url'];
3001                 }
3002
3003                 return '';
3004         }
3005 }