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