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