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