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