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