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