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