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