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