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