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