]> git.mxchange.org Git - friendica.git/blob - src/Model/Contact.php
23e1f2cbff2b30b795b309e408a76fdb1c1e22ae
[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                                 /**
1903                                  * Picture credits
1904                                  * @author  Lostinlight <https://mastodon.xyz/@lightone>
1905                                  * @license CC0 https://creativecommons.org/share-your-work/public-domain/cc0/
1906                                  * @link    https://gitlab.com/lostinlight/per_aspera_ad_astra/-/blob/master/friendica-404/friendica-promo-bubbles.jpg
1907                                  */
1908                                 $header = DI::baseUrl() . '/images/friendica-banner.jpg';
1909                                 break;
1910                         case 'diaspora':
1911                                 /**
1912                                  * Picture credits
1913                                  * @author  John Liu <https://www.flickr.com/photos/8047705@N02/>
1914                                  * @license CC BY 2.0 https://creativecommons.org/licenses/by/2.0/
1915                                  * @link    https://www.flickr.com/photos/8047705@N02/5572197407
1916                                  */
1917                                 $header = DI::baseUrl() . '/images/diaspora-banner.jpg';
1918                                 break;
1919                         default:
1920                                 /**
1921                                  * Use a random picture.
1922                                  * The service provides random pictures from Unsplash.
1923                                  * @license https://unsplash.com/license
1924                                  */
1925                                 $header = 'https://picsum.photos/seed/' . hash('ripemd128', $contact['url']) . '/960/300';
1926                                 break;
1927                 }
1928
1929                 return $header;
1930         }
1931
1932         /**
1933          * Fetch the default avatar for the given contact and size
1934          *
1935          * @param array $contact  contact array
1936          * @param string $size    Size of the avatar picture
1937          * @return string avatar URL
1938          */
1939         public static function getDefaultAvatar(array $contact, string $size): string
1940         {
1941                 switch ($size) {
1942                         case Proxy::SIZE_MICRO:
1943                                 $avatar['size'] = 48;
1944                                 $default = self::DEFAULT_AVATAR_MICRO;
1945                                 break;
1946
1947                         case Proxy::SIZE_THUMB:
1948                                 $avatar['size'] = 80;
1949                                 $default = self::DEFAULT_AVATAR_THUMB;
1950                                 break;
1951
1952                         case Proxy::SIZE_SMALL:
1953                         default:
1954                                 $avatar['size'] = 300;
1955                                 $default = self::DEFAULT_AVATAR_PHOTO;
1956                                 break;
1957                 }
1958
1959                 if (!DI::config()->get('system', 'remote_avatar_lookup')) {
1960                         $platform = '';
1961                         $type     = Contact::TYPE_PERSON;
1962
1963                         if (!empty($contact['id'])) {
1964                                 $account = DBA::selectFirst('account-user-view', ['platform', 'contact-type'], ['id' => $contact['id']]);
1965                                 $platform = $account['platform'] ?? '';
1966                                 $type     = $account['contact-type'] ?? Contact::TYPE_PERSON;
1967                         }
1968
1969                         if (empty($platform) && !empty($contact['uri-id'])) {
1970                                 $account = DBA::selectFirst('account-user-view', ['platform', 'contact-type'], ['uri-id' => $contact['uri-id']]);
1971                                 $platform = $account['platform'] ?? '';
1972                                 $type     = $account['contact-type'] ?? Contact::TYPE_PERSON;
1973                         }
1974
1975                         switch ($platform) {
1976                                 case 'corgidon':
1977                                         /**
1978                                          * Picture credits
1979                                          * @license GNU Affero General Public License v3.0
1980                                          * @link    https://github.com/msdos621/corgidon/blob/main/public/avatars/original/missing.png
1981                                          */
1982                                         $default = '/images/default/corgidon.png';
1983                                         break;
1984
1985                                 case 'diaspora':
1986                                         /**
1987                                          * Picture credits
1988                                          * @license GNU Affero General Public License v3.0
1989                                          * @link    https://github.com/diaspora/diaspora/
1990                                          */
1991                                         $default = '/images/default/diaspora.png';
1992                                         break;
1993
1994                                 case 'gotosocial':
1995                                         /**
1996                                          * Picture credits
1997                                          * @license GNU Affero General Public License v3.0
1998                                          * @link    https://github.com/superseriousbusiness/gotosocial/blob/main/web/assets/default_avatars/GoToSocial_icon1.svg
1999                                          */
2000                                         $default = '/images/default/gotosocial.svg';
2001                                         break;
2002
2003                                 case 'hometown':
2004                                         /**
2005                                          * Picture credits
2006                                          * @license GNU Affero General Public License v3.0
2007                                          * @link    https://github.com/hometown-fork/hometown/blob/hometown-dev/public/avatars/original/missing.png
2008                                          */
2009                                         $default = '/images/default/hometown.png';
2010                                         break;
2011
2012                                 case 'koyuspace':
2013                                         /**
2014                                          * Picture credits
2015                                          * @license GNU Affero General Public License v3.0
2016                                          * @link    https://github.com/koyuspace/mastodon/blob/main/public/avatars/original/missing.png
2017                                          */
2018                                         $default = '/images/default/koyuspace.png';
2019                                         break;
2020
2021                                 case 'ecko':
2022                                 case 'qoto':
2023                                 case 'mastodon':
2024                                         /**
2025                                          * Picture credits
2026                                          * @license GNU Affero General Public License v3.0
2027                                          * @link    https://github.com/mastodon/mastodon/tree/main/public/avatars/original/missing.png
2028                                          */
2029                                         $default = '/images/default/mastodon.png';
2030                                         break;
2031
2032                                 case 'peertube':
2033                                         if ($type == Contact::TYPE_COMMUNITY) {
2034                                                 /**
2035                                                  * Picture credits
2036                                                  * @license GNU Affero General Public License v3.0
2037                                                  * @link    https://github.com/Chocobozzz/PeerTube/blob/develop/client/src/assets/images/default-avatar-video-channel.png
2038                                                  */
2039                                                 $default = '/images/default/peertube-channel.png';
2040                                         } else {
2041                                                 /**
2042                                                  * Picture credits
2043                                                  * @license GNU Affero General Public License v3.0
2044                                                  * @link    https://github.com/Chocobozzz/PeerTube/blob/develop/client/src/assets/images/default-avatar-account.png
2045                                                  */
2046                                                 $default = '/images/default/peertube-account.png';
2047                                         }
2048                                         break;
2049
2050                                 case 'pleroma':
2051                                         /**
2052                                          * Picture credits
2053                                          * @license GNU Affero General Public License v3.0
2054                                          * @link    https://git.pleroma.social/pleroma/pleroma/-/blob/develop/priv/static/images/avi.png
2055                                          */
2056                                         $default = '/images/default/pleroma.png';
2057                                         break;
2058
2059                                 case 'plume':
2060                                         /**
2061                                          * Picture credits
2062                                          * @license GNU Affero General Public License v3.0
2063                                          * @link    https://github.com/Plume-org/Plume/blob/main/assets/images/default-avatar.png
2064                                          */
2065                                         $default = '/images/default/plume.png';
2066                                         break;
2067                         }
2068                         return DI::baseUrl() . $default;
2069                 }
2070
2071                 if (!empty($contact['xmpp'])) {
2072                         $avatar['email'] = $contact['xmpp'];
2073                 } elseif (!empty($contact['addr'])) {
2074                         $avatar['email'] = $contact['addr'];
2075                 } elseif (!empty($contact['url'])) {
2076                         $avatar['email'] = $contact['url'];
2077                 } else {
2078                         return DI::baseUrl() . $default;
2079                 }
2080
2081                 $avatar['url'] = '';
2082                 $avatar['success'] = false;
2083
2084                 Hook::callAll('avatar_lookup', $avatar);
2085
2086                 if ($avatar['success'] && !empty($avatar['url'])) {
2087                         return $avatar['url'];
2088                 }
2089
2090                 return DI::baseUrl() . $default;
2091         }
2092
2093         /**
2094          * Get avatar link for given contact id
2095          *
2096          * @param integer $cid     contact id
2097          * @param string  $size    One of the Proxy::SIZE_* constants
2098          * @param string  $updated Contact update date
2099          * @param bool    $static  If "true" a parameter is added to convert the avatar to a static one
2100          * @return string avatar link
2101          */
2102         public static function getAvatarUrlForId(int $cid, string $size = '', string $updated = '', string $guid = '', bool $static = false): string
2103         {
2104                 // We have to fetch the "updated" variable when it wasn't provided
2105                 // The parameter can be provided to improve performance
2106                 if (empty($updated)) {
2107                         $account = DBA::selectFirst('account-user-view', ['updated', 'guid'], ['id' => $cid]);
2108                         $updated = $account['updated'] ?? '';
2109                         $guid = $account['guid'] ?? '';
2110                 }
2111
2112                 $guid = urlencode($guid);
2113
2114                 $url = DI::baseUrl() . '/photo/contact/';
2115                 switch ($size) {
2116                         case Proxy::SIZE_MICRO:
2117                                 $url .= Proxy::PIXEL_MICRO . '/';
2118                                 break;
2119                         case Proxy::SIZE_THUMB:
2120                                 $url .= Proxy::PIXEL_THUMB . '/';
2121                                 break;
2122                         case Proxy::SIZE_SMALL:
2123                                 $url .= Proxy::PIXEL_SMALL . '/';
2124                                 break;
2125                         case Proxy::SIZE_MEDIUM:
2126                                 $url .= Proxy::PIXEL_MEDIUM . '/';
2127                                 break;
2128                         case Proxy::SIZE_LARGE:
2129                                 $url .= Proxy::PIXEL_LARGE . '/';
2130                                 break;
2131                 }
2132                 $query_params = [];
2133                 if ($updated) {
2134                         $query_params['ts'] = strtotime($updated);
2135                 }
2136                 if ($static) {
2137                         $query_params['static'] = true;
2138                 }
2139
2140                 return $url . ($guid ?: $cid) . (!empty($query_params) ? '?' . http_build_query($query_params) : '');
2141         }
2142
2143         /**
2144          * Get avatar link for given contact URL
2145          *
2146          * @param string  $url  contact url
2147          * @param integer $uid  user id
2148          * @param string  $size One of the Proxy::SIZE_* constants
2149          * @return string avatar link
2150          */
2151         public static function getAvatarUrlForUrl(string $url, int $uid, string $size = ''): string
2152         {
2153                 $condition = [
2154                         "`nurl` = ? AND ((`uid` = ? AND `network` IN (?, ?)) OR `uid` = ?)",
2155                         Strings::normaliseLink($url), $uid, Protocol::FEED, Protocol::MAIL, 0
2156                 ];
2157                 $contact = self::selectFirst(['id', 'updated'], $condition, ['order' => ['uid' => true]]);
2158                 return self::getAvatarUrlForId($contact['id'] ?? 0, $size, $contact['updated'] ?? '');
2159         }
2160
2161         /**
2162          * Get header link for given contact id
2163          *
2164          * @param integer $cid     contact id
2165          * @param string  $size    One of the Proxy::SIZE_* constants
2166          * @param string  $updated Contact update date
2167          * @param bool    $static  If "true" a parameter is added to convert the header to a static one
2168          * @return string header link
2169          */
2170         public static function getHeaderUrlForId(int $cid, string $size = '', string $updated = '', string $guid = '', bool $static = false): string
2171         {
2172                 // We have to fetch the "updated" variable when it wasn't provided
2173                 // The parameter can be provided to improve performance
2174                 if (empty($updated) || empty($guid)) {
2175                         $account = DBA::selectFirst('account-user-view', ['updated', 'guid'], ['id' => $cid]);
2176                         $updated = $account['updated'] ?? '';
2177                         $guid = $account['guid'] ?? '';
2178                 }
2179
2180                 $guid = urlencode($guid);
2181
2182                 $url = DI::baseUrl() . '/photo/header/';
2183                 switch ($size) {
2184                         case Proxy::SIZE_MICRO:
2185                                 $url .= Proxy::PIXEL_MICRO . '/';
2186                                 break;
2187                         case Proxy::SIZE_THUMB:
2188                                 $url .= Proxy::PIXEL_THUMB . '/';
2189                                 break;
2190                         case Proxy::SIZE_SMALL:
2191                                 $url .= Proxy::PIXEL_SMALL . '/';
2192                                 break;
2193                         case Proxy::SIZE_MEDIUM:
2194                                 $url .= Proxy::PIXEL_MEDIUM . '/';
2195                                 break;
2196                         case Proxy::SIZE_LARGE:
2197                                 $url .= Proxy::PIXEL_LARGE . '/';
2198                                 break;
2199                 }
2200
2201                 $query_params = [];
2202                 if ($updated) {
2203                         $query_params['ts'] = strtotime($updated);
2204                 }
2205                 if ($static) {
2206                         $query_params['static'] = true;
2207                 }
2208
2209                 return $url . ($guid ?: $cid) . (!empty($query_params) ? '?' . http_build_query($query_params) : '');
2210         }
2211
2212         /**
2213          * Updates the avatar links in a contact only if needed
2214          *
2215          * @param int    $cid          Contact id
2216          * @param string $avatar       Link to avatar picture
2217          * @param bool   $force        force picture update
2218          * @param bool   $create_cache Enforces the creation of cached avatar fields
2219          *
2220          * @return void
2221          * @throws HTTPException\InternalServerErrorException
2222          * @throws HTTPException\NotFoundException
2223          * @throws \ImagickException
2224          */
2225         public static function updateAvatar(int $cid, string $avatar, bool $force = false, bool $create_cache = false)
2226         {
2227                 $contact = DBA::selectFirst(
2228                         'contact',
2229                         ['uid', 'avatar', 'photo', 'thumb', 'micro', 'blurhash', 'xmpp', 'addr', 'nurl', 'url', 'network', 'uri-id'],
2230                         ['id' => $cid, 'self' => false]
2231                 );
2232                 if (!DBA::isResult($contact)) {
2233                         return;
2234                 }
2235
2236                 if (!Network::isValidHttpUrl($avatar)) {
2237                         Logger::warning('Invalid avatar', ['cid' => $cid, 'avatar' => $avatar]);
2238                         $avatar = '';
2239                 }
2240
2241                 $uid = $contact['uid'];
2242
2243                 // Only update the cached photo links of public contacts when they already are cached
2244                 if (($uid == 0) && !$force && empty($contact['thumb']) && empty($contact['micro']) && !$create_cache) {
2245                         if (($contact['avatar'] != $avatar) || empty($contact['blurhash'])) {
2246                                 $update_fields = ['avatar' => $avatar];
2247                                 if (!Network::isLocalLink($avatar)) {
2248                                         try {
2249                                                 $fetchResult = HTTPSignature::fetchRaw($avatar, 0, [HttpClientOptions::ACCEPT_CONTENT => [HttpClientAccept::IMAGE]]);
2250
2251                                                 $img_str = $fetchResult->getBody();
2252                                                 if (!empty($img_str)) {
2253                                                         $image = new Image($img_str, Images::getMimeTypeByData($img_str));
2254                                                         if ($image->isValid()) {
2255                                                                 $update_fields['blurhash'] = $image->getBlurHash();
2256                                                         } else {
2257                                                                 return;
2258                                                         }
2259                                                 }
2260                                         } catch (\Exception $exception) {
2261                                                 Logger::notice('Error fetching avatar', ['avatar' => $avatar, 'exception' => $exception]);
2262                                                 return;
2263                                         }
2264                                 } elseif (!empty($contact['blurhash'])) {
2265                                         $update_fields['blurhash'] = null;
2266                                 } else {
2267                                         return;
2268                                 }
2269
2270                                 self::update($update_fields, ['id' => $cid]);
2271                                 Logger::info('Only update the avatar', ['id' => $cid, 'avatar' => $avatar, 'contact' => $contact]);
2272                         }
2273                         return;
2274                 }
2275
2276                 // User contacts use are updated through the public contacts
2277                 if (($uid != 0) && !in_array($contact['network'], [Protocol::FEED, Protocol::MAIL])) {
2278                         $pcid = self::getIdForURL($contact['url'], 0, false);
2279                         if (!empty($pcid)) {
2280                                 Logger::debug('Update the private contact via the public contact', ['id' => $cid, 'uid' => $uid, 'public' => $pcid]);
2281                                 self::updateAvatar($pcid, $avatar, $force, true);
2282                                 return;
2283                         }
2284                 }
2285
2286                 $default_avatar = empty($avatar) || strpos($avatar, self::DEFAULT_AVATAR_PHOTO);
2287
2288                 if ($default_avatar) {
2289                         $avatar = self::getDefaultAvatar($contact, Proxy::SIZE_SMALL);
2290                 }
2291
2292                 $cache_avatar = DI::config()->get('system', 'cache_contact_avatar');
2293
2294                 // Local contact avatars don't need to be cached
2295                 if ($cache_avatar && Network::isLocalLink($contact['url'])) {
2296                         $cache_avatar = !DBA::exists('contact', ['nurl' => $contact['nurl'], 'self' => true]);
2297                 }
2298
2299                 if (in_array($contact['network'], [Protocol::FEED, Protocol::MAIL]) || $cache_avatar) {
2300                         if (Avatar::deleteCache($contact)) {
2301                                 $force = true;
2302                         }
2303
2304                         if ($default_avatar && Proxy::isLocalImage($avatar)) {
2305                                 $fields = [
2306                                         'avatar' => $avatar, 'avatar-date' => DateTimeFormat::utcNow(),
2307                                         'photo' => $avatar,
2308                                         'thumb' => self::getDefaultAvatar($contact, Proxy::SIZE_THUMB),
2309                                         'micro' => self::getDefaultAvatar($contact, Proxy::SIZE_MICRO)
2310                                 ];
2311                                 Logger::debug('Use default avatar', ['id' => $cid, 'uid' => $uid]);
2312                         }
2313
2314                         // Use the data from the self account
2315                         if (empty($fields)) {
2316                                 $local_uid = User::getIdForURL($contact['url']);
2317                                 if (!empty($local_uid)) {
2318                                         $fields = self::selectFirst(['avatar', 'avatar-date', 'photo', 'thumb', 'micro'], ['self' => true, 'uid' => $local_uid]);
2319                                         Logger::debug('Use owner data', ['id' => $cid, 'uid' => $uid, 'owner-uid' => $local_uid]);
2320                                 }
2321                         }
2322
2323                         if (empty($fields)) {
2324                                 $update = ($contact['avatar'] != $avatar) || $force;
2325
2326                                 if (!$update) {
2327                                         $data = [
2328                                                 $contact['photo'] ?? '',
2329                                                 $contact['thumb'] ?? '',
2330                                                 $contact['micro'] ?? '',
2331                                         ];
2332
2333                                         foreach ($data as $image_uri) {
2334                                                 $image_rid = Photo::ridFromURI($image_uri);
2335                                                 if ($image_rid && !Photo::exists(['resource-id' => $image_rid, 'uid' => $uid])) {
2336                                                         Logger::debug('Regenerating avatar', ['contact uid' => $uid, 'cid' => $cid, 'missing photo' => $image_rid, 'avatar' => $contact['avatar']]);
2337                                                         $update = true;
2338                                                 }
2339                                         }
2340                                 }
2341
2342                                 if ($update) {
2343                                         $photos = Photo::importProfilePhoto($avatar, $uid, $cid, true);
2344                                         if ($photos) {
2345                                                 $fields = ['avatar' => $avatar, 'photo' => $photos[0], 'thumb' => $photos[1], 'micro' => $photos[2], 'blurhash' => $photos[3], 'avatar-date' => DateTimeFormat::utcNow()];
2346                                                 $update = !empty($fields);
2347                                                 Logger::debug('Created new cached avatars', ['id' => $cid, 'uid' => $uid, 'owner-uid' => $local_uid]);
2348                                         } else {
2349                                                 $update = false;
2350                                         }
2351                                 }
2352                         } else {
2353                                 $update = ($fields['photo'] . $fields['thumb'] . $fields['micro'] != $contact['photo'] . $contact['thumb'] . $contact['micro']) || $force;
2354                         }
2355                 } else {
2356                         Photo::delete(['uid' => $uid, 'contact-id' => $cid, 'photo-type' => Photo::CONTACT_AVATAR]);
2357                         $fields = Avatar::fetchAvatarContact($contact, $avatar, $force);
2358                         $update = ($avatar . $fields['photo'] . $fields['thumb'] . $fields['micro'] != $contact['avatar'] . $contact['photo'] . $contact['thumb'] . $contact['micro']) || $force;
2359                 }
2360
2361                 if (!$update) {
2362                         return;
2363                 }
2364
2365                 $cids = [];
2366                 $uids = [];
2367                 if (($uid == 0) && !in_array($contact['network'], [Protocol::FEED, Protocol::MAIL])) {
2368                         // Collect all user contacts of the given public contact
2369                         $personal_contacts = DBA::select(
2370                                 'contact',
2371                                 ['id', 'uid'],
2372                                 ["`nurl` = ? AND `id` != ? AND NOT `self`", $contact['nurl'], $cid]
2373                         );
2374                         while ($personal_contact = DBA::fetch($personal_contacts)) {
2375                                 $cids[] = $personal_contact['id'];
2376                                 $uids[] = $personal_contact['uid'];
2377                         }
2378                         DBA::close($personal_contacts);
2379
2380                         if (!empty($cids)) {
2381                                 // Delete possibly existing cached user contact avatars
2382                                 Photo::delete(['uid' => $uids, 'contact-id' => $cids, 'photo-type' => Photo::CONTACT_AVATAR]);
2383                         }
2384                 }
2385
2386                 $cids[] = $cid;
2387                 $uids[] = $uid;
2388                 Logger::info('Updating cached contact avatars', ['cid' => $cids, 'uid' => $uids, 'fields' => $fields]);
2389                 self::update($fields, ['id' => $cids]);
2390         }
2391
2392         public static function deleteContactByUrl(string $url)
2393         {
2394                 // Update contact data for all users
2395                 $condition = ['self' => false, 'nurl' => Strings::normaliseLink($url)];
2396                 $contacts = DBA::select('contact', ['id', 'uid'], $condition);
2397                 while ($contact = DBA::fetch($contacts)) {
2398                         Logger::info('Deleting contact', ['id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $url]);
2399                         self::remove($contact['id']);
2400                 }
2401         }
2402
2403         /**
2404          * Helper function for "updateFromProbe". Updates personal and public contact
2405          *
2406          * @param integer $id     contact id
2407          * @param integer $uid    user id
2408          * @param integer $uri_id Uri-Id
2409          * @param string  $url    The profile URL of the contact
2410          * @param array   $fields The fields that are updated
2411          *
2412          * @throws \Exception
2413          */
2414         private static function updateContact(int $id, int $uid, int $uri_id, string $url, array $fields)
2415         {
2416                 if (!self::update($fields, ['id' => $id])) {
2417                         Logger::info('Couldn\'t update contact.', ['id' => $id, 'fields' => $fields]);
2418                         return;
2419                 }
2420
2421                 self::setAccountUser($id, $uid, $uri_id, $url);
2422
2423                 // Archive or unarchive the contact.
2424                 $contact = DBA::selectFirst('contact', [], ['id' => $id]);
2425                 if (!DBA::isResult($contact)) {
2426                         Logger::info('Couldn\'t select contact for archival.', ['id' => $id]);
2427                         return;
2428                 }
2429
2430                 if (isset($fields['failed'])) {
2431                         if ($fields['failed']) {
2432                                 self::markForArchival($contact);
2433                         } else {
2434                                 self::unmarkForArchival($contact);
2435                         }
2436                 }
2437
2438                 if ($contact['uid'] != 0) {
2439                         return;
2440                 }
2441
2442                 // Update contact data for all users
2443                 $condition = ['self' => false, 'nurl' => Strings::normaliseLink($url)];
2444
2445                 $condition['network'] = [Protocol::DFRN, Protocol::DIASPORA, Protocol::ACTIVITYPUB];
2446
2447                 if (!in_array($contact['network'], Protocol::NATIVE_SUPPORT) && Protocol::supportsProbe($contact['network'])) {
2448                         $condition['network'][] = $contact['network'];
2449                 }
2450
2451                 self::update($fields, $condition);
2452
2453                 // We mustn't set the update fields for OStatus contacts since they are updated in OnePoll
2454                 $condition['network'] = Protocol::OSTATUS;
2455
2456                 // If the contact failed, propagate the update fields to all contacts
2457                 if (empty($fields['failed'])) {
2458                         unset($fields['last-update']);
2459                         unset($fields['success_update']);
2460                         unset($fields['failure_update']);
2461                 }
2462
2463                 if (empty($fields)) {
2464                         return;
2465                 }
2466
2467                 self::update($fields, $condition);
2468         }
2469
2470         /**
2471          * Create or update an "account-user" entry
2472          *
2473          * @param integer $id
2474          * @param integer $uid
2475          * @param integer $uri_id
2476          * @param string $url
2477          * @return void
2478          */
2479         public static function setAccountUser(int $id, int $uid, int $uri_id, string $url)
2480         {
2481                 if (empty($uri_id)) {
2482                         return;
2483                 }
2484
2485                 $account_user = DBA::selectFirst('account-user', ['id', 'uid', 'uri-id'], ['id' => $id]);
2486                 if (!empty($account_user['uri-id']) && ($account_user['uri-id'] != $uri_id)) {
2487                         if ($account_user['uid'] == $uid) {
2488                                 $ret = DBA::update('account-user', ['uri-id' => $uri_id], ['id' => $id]);
2489                                 Logger::notice('Updated account-user uri-id', ['ret' => $ret, 'account-user' => $account_user, 'cid' => $id, 'uid' => $uid, 'uri-id' => $uri_id, 'url' => $url]);
2490                         } else {
2491                                 // This should never happen
2492                                 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]);
2493                         }
2494                 }
2495
2496                 $account_user = DBA::selectFirst('account-user', ['id', 'uid', 'uri-id'], ['uid' => $uid, 'uri-id' => $uri_id]);
2497                 if (!empty($account_user['id'])) {
2498                         if ($account_user['id'] == $id) {
2499                                 Logger::debug('account-user already exists', ['id' => $id, 'uid' => $uid, 'uri-id' => $uri_id, 'url' => $url]);
2500                                 return;
2501                         } elseif (!DBA::exists('contact', ['id' => $account_user['id'], 'deleted' => false])) {
2502                                 $ret = DBA::update('account-user', ['id' => $id], ['uid' => $uid, 'uri-id' => $uri_id]);
2503                                 Logger::notice('Updated account-user', ['ret' => $ret, 'account-user' => $account_user, 'cid' => $id, 'uid' => $uid, 'uri-id' => $uri_id, 'url' => $url]);
2504                                 return;
2505                         }
2506                         Logger::warning('account-user exists for a different contact id', ['account_user' => $account_user, 'id' => $id, 'uid' => $uid, 'uri-id' => $uri_id, 'url' => $url]);
2507                         Worker::add(Worker::PRIORITY_HIGH, 'MergeContact', $account_user['id'], $id, $uid);
2508                 } elseif (DBA::insert('account-user', ['id' => $id, 'uri-id' => $uri_id, 'uid' => $uid], Database::INSERT_IGNORE)) {
2509                         Logger::notice('account-user was added', ['id' => $id, 'uid' => $uid, 'uri-id' => $uri_id, 'url' => $url]);
2510                 } else {
2511                         Logger::warning('account-user was not added', ['id' => $id, 'uid' => $uid, 'uri-id' => $uri_id, 'url' => $url]);
2512                 }
2513         }
2514
2515         /**
2516          * Remove duplicated contacts
2517          *
2518          * @param string  $nurl  Normalised contact url
2519          * @param integer $uid   User id
2520          * @return boolean
2521          * @throws \Exception
2522          */
2523         public static function removeDuplicates(string $nurl, int $uid)
2524         {
2525                 $condition = ['nurl' => $nurl, 'uid' => $uid, 'self' => false, 'deleted' => false, 'network' => Protocol::FEDERATED];
2526                 $count = DBA::count('contact', $condition);
2527                 if ($count <= 1) {
2528                         return false;
2529                 }
2530
2531                 $first_contact = DBA::selectFirst('contact', ['id', 'network'], $condition, ['order' => ['id']]);
2532                 if (!DBA::isResult($first_contact)) {
2533                         // Shouldn't happen - so we handle it
2534                         return false;
2535                 }
2536
2537                 $first = $first_contact['id'];
2538                 Logger::info('Found duplicates', ['count' => $count, 'first' => $first, 'uid' => $uid, 'nurl' => $nurl]);
2539
2540                 // Find all duplicates
2541                 $condition = ["`nurl` = ? AND `uid` = ? AND `id` != ? AND NOT `self` AND NOT `deleted`", $nurl, $uid, $first];
2542                 $duplicates = DBA::select('contact', ['id', 'network'], $condition);
2543                 while ($duplicate = DBA::fetch($duplicates)) {
2544                         if (!in_array($duplicate['network'], Protocol::FEDERATED)) {
2545                                 continue;
2546                         }
2547
2548                         Worker::add(Worker::PRIORITY_HIGH, 'MergeContact', $first, $duplicate['id'], $uid);
2549                 }
2550                 DBA::close($duplicates);
2551                 Logger::info('Duplicates handled', ['uid' => $uid, 'nurl' => $nurl, 'callstack' => System::callstack(20)]);
2552                 return true;
2553         }
2554
2555         /**
2556          * Perform a contact update if the contact is outdated
2557          *
2558          * @param integer $id contact id
2559          * @return bool
2560          */
2561         public static function updateByIdIfNeeded(int $id): bool
2562         {
2563                 $contact = self::selectFirst(['url'], ["`id` = ? AND `next-update` < ?", $id, DateTimeFormat::utcNow()]);
2564                 if (empty($contact['url'])) {
2565                         return false;
2566                 }
2567
2568                 if (self::isLocal($contact['url'])) {
2569                         return true;
2570                 }
2571
2572                 $stamp = (float)microtime(true);
2573                 self::updateFromProbe($id);
2574                 Logger::debug('Contact data is updated.', ['duration' => round((float)microtime(true) - $stamp, 3), 'id' => $id, 'url' => $contact['url'], 'callstack' => System::callstack(20)]);
2575                 return true;
2576         }
2577
2578         /**
2579          * Perform a contact update if the contact is outdated
2580          *
2581          * @param string $url contact url
2582          * @return bool
2583          */
2584         public static function updateByUrlIfNeeded(string $url): bool
2585         {
2586                 $id = self::getIdForURL($url, 0, false);
2587                 if (!empty($id)) {
2588                         return self::updateByIdIfNeeded($id);
2589                 }
2590                 return (bool)self::getIdForURL($url);
2591         }
2592
2593         /**
2594          * Updates contact record by provided id and optional network
2595          *
2596          * @param integer $id      contact id
2597          * @param string  $network Optional network we are probing for
2598          * @return boolean
2599          * @throws HTTPException\InternalServerErrorException
2600          * @throws \ImagickException
2601          */
2602         public static function updateFromProbe(int $id, string $network = ''): bool
2603         {
2604                 $contact = DBA::selectFirst('contact', ['uid', 'url'], ['id' => $id]);
2605                 if (!DBA::isResult($contact)) {
2606                         return false;
2607                 }
2608
2609                 $data = Probe::uri($contact['url'], $network, $contact['uid']);
2610
2611                 if ($data['network'] == Protocol::DIASPORA) {
2612                         try {
2613                                 DI::dsprContact()->updateFromProbeArray($data);
2614                         } catch (HTTPException\NotFoundException $e) {
2615                                 Logger::notice($e->getMessage(), ['id' => $id, 'network' => $network, 'contact' => $contact, 'data' => $data]);
2616                         } catch (\InvalidArgumentException $e) {
2617                                 Logger::notice($e->getMessage(), ['id' => $id, 'network' => $network, 'contact' => $contact, 'data' => $data]);
2618                         }
2619                 } elseif (!empty($data['networks'][Protocol::DIASPORA])) {
2620                         try {
2621                                 DI::dsprContact()->updateFromProbeArray($data['networks'][Protocol::DIASPORA]);
2622                         } catch (HTTPException\NotFoundException $e) {
2623                                 Logger::notice($e->getMessage(), ['id' => $id, 'network' => $network, 'contact' => $contact, 'data' => $data]);
2624                         } catch (\InvalidArgumentException $e) {
2625                                 Logger::notice($e->getMessage(), ['id' => $id, 'network' => $network, 'contact' => $contact, 'data' => $data]);
2626                         }
2627                 }
2628
2629                 return self::updateFromProbeArray($id, $data);
2630         }
2631
2632         /**
2633          * Checks if the given contact has got local data
2634          *
2635          * @param int   $id
2636          * @param array $contact
2637          *
2638          * @return boolean
2639          */
2640         private static function hasLocalData(int $id, array $contact): bool
2641         {
2642                 if (!empty($contact['uri-id']) && DBA::exists('contact', ["`uri-id` = ? AND `uid` != ?", $contact['uri-id'], 0])) {
2643                         // User contacts with the same uri-id exist
2644                         return true;
2645                 } elseif (DBA::exists('contact', ["`nurl` = ? AND `uid` != ?", Strings::normaliseLink($contact['url']), 0])) {
2646                         // User contacts with the same nurl exists (compatibility mode for systems with missing uri-id values)
2647                         return true;
2648                 }
2649                 if (DBA::exists('post-tag', ['cid' => $id])) {
2650                         // Is tagged in a post
2651                         return true;
2652                 }
2653                 if (DBA::exists('user-contact', ['cid' => $id])) {
2654                         // Has got user-contact data
2655                         return true;
2656                 }
2657                 if (Post::exists(['author-id' => $id])) {
2658                         // Posts with this author exist
2659                         return true;
2660                 }
2661                 if (Post::exists(['owner-id' => $id])) {
2662                         // Posts with this owner exist
2663                         return true;
2664                 }
2665                 if (Post::exists(['causer-id' => $id])) {
2666                         // Posts with this causer exist
2667                         return true;
2668                 }
2669                 // We don't have got this contact locally
2670                 return false;
2671         }
2672
2673         /**
2674          * Updates contact record by provided id and probed data
2675          *
2676          * @param integer $id      contact id
2677          * @param array   $ret     Probed data
2678          * @return boolean
2679          * @throws HTTPException\InternalServerErrorException
2680          * @throws \ImagickException
2681          */
2682         private static function updateFromProbeArray(int $id, array $ret): bool
2683         {
2684                 /*
2685                   Warning: Never ever fetch the public key via Probe::uri and write it into the contacts.
2686                   This will reliably kill your communication with old Friendica contacts.
2687                  */
2688
2689                 // These fields aren't updated by this routine:
2690                 // 'sensitive'
2691
2692                 $fields = [
2693                         'uid', 'uri-id', 'avatar', 'header', 'name', 'nick', 'location', 'keywords', 'about', 'subscribe',
2694                         'manually-approve', 'unsearchable', 'url', 'addr', 'batch', 'notify', 'poll', 'request', 'confirm', 'poco',
2695                         'network', 'alias', 'baseurl', 'gsid', 'forum', 'prv', 'contact-type', 'pubkey', 'last-item', 'xmpp', 'matrix',
2696                         'created', 'last-update'
2697                 ];
2698                 $contact = DBA::selectFirst('contact', $fields, ['id' => $id]);
2699                 if (!DBA::isResult($contact)) {
2700                         return false;
2701                 }
2702
2703                 if (self::isLocal($ret['url'])) {
2704                         if ($contact['uid'] == 0) {
2705                                 Logger::info('Local contacts are not updated here.');
2706                         } else {
2707                                 self::updateFromPublicContact($id, $contact);
2708                         }
2709                         return true;
2710                 }
2711
2712                 if (!empty($ret['account-type']) && $ret['account-type'] == User::ACCOUNT_TYPE_DELETED) {
2713                         Logger::info('Deleted account', ['id' => $id, 'url' => $ret['url'], 'ret' => $ret]);
2714                         self::remove($id);
2715
2716                         // Delete all contacts with the same URL
2717                         self::deleteContactByUrl($ret['url']);
2718                         return true;
2719                 }
2720
2721                 $has_local_data = self::hasLocalData($id, $contact);
2722
2723                 $uid = $contact['uid'];
2724                 unset($contact['uid']);
2725
2726                 $uriid = $contact['uri-id'];
2727                 unset($contact['uri-id']);
2728
2729                 $pubkey = $contact['pubkey'];
2730                 unset($contact['pubkey']);
2731
2732                 $created = $contact['created'];
2733                 unset($contact['created']);
2734
2735                 $last_update = $contact['last-update'];
2736                 unset($contact['last-update']);
2737
2738                 $contact['photo'] = $contact['avatar'];
2739                 unset($contact['avatar']);
2740
2741                 $updated = DateTimeFormat::utcNow();
2742
2743                 if (!Protocol::supportsProbe($ret['network']) && !Protocol::supportsProbe($contact['network'])) {
2744                         // Periodical checks are only done on federated contacts
2745                         $failed_next_update  = null;
2746                         $success_next_update = null;
2747                 } elseif ($has_local_data) {
2748                         $failed_next_update  = GServer::getNextUpdateDate(false, $created, $last_update, !in_array($contact['network'], Protocol::FEDERATED));
2749                         $success_next_update = GServer::getNextUpdateDate(true, $created, $last_update, !in_array($contact['network'], Protocol::FEDERATED));
2750                 } elseif (in_array($ret['network'], array_merge(Protocol::NATIVE_SUPPORT, [Protocol::ZOT, Protocol::PHANTOM]))) {
2751                         $failed_next_update  = DateTimeFormat::utc('now +6 month');
2752                         $success_next_update = DateTimeFormat::utc('now +1 month');
2753                 } else {
2754                         // We don't check connector networks very often to not run into API rate limits
2755                         $failed_next_update  = DateTimeFormat::utc('now +12 month');
2756                         $success_next_update = DateTimeFormat::utc('now +12 month');
2757                 }
2758
2759                 if (Strings::normaliseLink($contact['url']) != Strings::normaliseLink($ret['url'])) {
2760                         Logger::notice('New URL differs from old URL', ['id' => $id, 'uid' => $uid, 'old' => $contact['url'], 'new' => $ret['url']]);
2761                         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]);
2762                         return false;
2763                 }
2764
2765                 // We must not try to update relay contacts via probe. They are no real contacts.
2766                 // We check after the probing to be able to correct falsely detected contact types.
2767                 if (($contact['contact-type'] == self::TYPE_RELAY) &&
2768                         (!Strings::compareLink($ret['url'], $contact['url']) || in_array($ret['network'], [Protocol::FEED, Protocol::PHANTOM]))
2769                 ) {
2770                         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]);
2771                         Logger::info('Not updating relais', ['id' => $id, 'url' => $contact['url']]);
2772                         return true;
2773                 }
2774
2775                 // If Probe::uri fails the network code will be different ("feed" or "unkn")
2776                 if (($ret['network'] == Protocol::PHANTOM) || (($ret['network'] == Protocol::FEED) && ($ret['network'] != $contact['network']))) {
2777                         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]);
2778                         return false;
2779                 }
2780
2781                 if (Strings::normaliseLink($ret['url']) != Strings::normaliseLink($contact['url'])) {
2782                         $cid = self::getIdForURL($ret['url'], 0, false);
2783                         if (!empty($cid) && ($cid != $id)) {
2784                                 Logger::notice('URL of contact changed.', ['id' => $id, 'new_id' => $cid, 'old' => $contact['url'], 'new' => $ret['url']]);
2785                                 return self::updateFromProbeArray($cid, $ret);
2786                         }
2787                 }
2788
2789                 if (isset($ret['hide']) && is_bool($ret['hide'])) {
2790                         $ret['unsearchable'] = $ret['hide'];
2791                 }
2792
2793                 if (isset($ret['account-type']) && is_int($ret['account-type'])) {
2794                         $ret['forum'] = false;
2795                         $ret['prv'] = false;
2796                         $ret['contact-type'] = $ret['account-type'];
2797                         if (($ret['contact-type'] == User::ACCOUNT_TYPE_COMMUNITY) && isset($ret['manually-approve'])) {
2798                                 $ret['forum'] = (bool)!$ret['manually-approve'];
2799                                 $ret['prv'] = (bool)!$ret['forum'];
2800                         }
2801                 }
2802
2803                 $new_pubkey = $ret['pubkey'] ?? '';
2804
2805                 if ($uid == 0 && DI::config()->get('system', 'fetch_featured_posts')) {
2806                         if ($ret['network'] == Protocol::ACTIVITYPUB) {
2807                                 $apcontact = APContact::getByURL($ret['url'], false);
2808                                 if (!empty($apcontact['featured'])) {
2809                                         Worker::add(Worker::PRIORITY_LOW, 'FetchFeaturedPosts', $ret['url']);
2810                                 }
2811                         }
2812
2813                         $ret['last-item'] = Probe::getLastUpdate($ret);
2814                         Logger::info('Fetched last item', ['id' => $id, 'probed_url' => $ret['url'], 'last-item' => $ret['last-item'], 'callstack' => System::callstack(20)]);
2815                 }
2816
2817                 $update = false;
2818                 $guid = ($ret['guid'] ?? '') ?: Item::guidFromUri($ret['url'], $ret['baseurl'] ?? $ret['alias'] ?? '');
2819
2820                 // make sure to not overwrite existing values with blank entries except some technical fields
2821                 $keep = ['batch', 'notify', 'poll', 'request', 'confirm', 'poco', 'baseurl'];
2822                 foreach ($ret as $key => $val) {
2823                         if (!array_key_exists($key, $contact)) {
2824                                 unset($ret[$key]);
2825                         } elseif (($contact[$key] != '') && ($val === '') && !is_bool($ret[$key]) && !in_array($key, $keep)) {
2826                                 $ret[$key] = $contact[$key];
2827                         } elseif ($ret[$key] != $contact[$key]) {
2828                                 $update = true;
2829                         }
2830                 }
2831
2832                 if (!empty($ret['last-item']) && ($contact['last-item'] < $ret['last-item'])) {
2833                         $update = true;
2834                 } else {
2835                         unset($ret['last-item']);
2836                 }
2837
2838                 if (empty($uriid)) {
2839                         $update = true;
2840                 }
2841
2842                 if (!empty($ret['photo']) && ($ret['network'] != Protocol::FEED)) {
2843                         self::updateAvatar($id, $ret['photo'], $update);
2844                 }
2845
2846                 if (!$update) {
2847                         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]);
2848
2849                         if (Contact\Relation::isDiscoverable($ret['url'])) {
2850                                 Worker::add(Worker::PRIORITY_LOW, 'ContactDiscovery', $ret['url']);
2851                         }
2852
2853                         // Update the public contact
2854                         if ($uid != 0) {
2855                                 $contact = self::getByURL($ret['url'], false, ['id']);
2856                                 if (!empty($contact['id'])) {
2857                                         self::updateFromProbeArray($contact['id'], $ret);
2858                                 }
2859                         }
2860
2861                         return true;
2862                 }
2863
2864                 $ret['uri-id']      = ItemURI::insert(['uri' => $ret['url'], 'guid' => $guid]);
2865                 $ret['nurl']        = Strings::normaliseLink($ret['url']);
2866                 $ret['updated']     = $updated;
2867                 $ret['failed']      = false;
2868                 $ret['next-update'] = $success_next_update;
2869                 $ret['local-data']  = $has_local_data;
2870
2871                 // Only fill the pubkey if it had been empty before. We have to prevent identity theft.
2872                 if (empty($pubkey) && !empty($new_pubkey)) {
2873                         $ret['pubkey'] = $new_pubkey;
2874                 }
2875
2876                 if ((!empty($ret['addr']) && ($ret['addr'] != $contact['addr'])) || (!empty($ret['alias']) && ($ret['alias'] != $contact['alias']))) {
2877                         $ret['uri-date'] = $updated;
2878                 }
2879
2880                 if ((!empty($ret['name']) && ($ret['name'] != $contact['name'])) || (!empty($ret['nick']) && ($ret['nick'] != $contact['nick']))) {
2881                         $ret['name-date'] = $updated;
2882                 }
2883
2884                 if (($uid == 0) || in_array($ret['network'], [Protocol::DFRN, Protocol::DIASPORA, Protocol::ACTIVITYPUB])) {
2885                         $ret['last-update'] = $updated;
2886                         $ret['success_update'] = $updated;
2887                 }
2888
2889                 unset($ret['photo']);
2890
2891                 self::updateContact($id, $uid, $ret['uri-id'], $ret['url'], $ret);
2892
2893                 if (Contact\Relation::isDiscoverable($ret['url'])) {
2894                         Worker::add(Worker::PRIORITY_LOW, 'ContactDiscovery', $ret['url']);
2895                 }
2896
2897                 return true;
2898         }
2899
2900         private static function updateFromPublicContact(int $id, array $contact)
2901         {
2902                 $public = self::getByURL($contact['url'], false);
2903
2904                 $fields = [];
2905
2906                 foreach ($contact as $field => $value) {
2907                         if ($field == 'uid') {
2908                                 continue;
2909                         }
2910                         if ($public[$field] != $value) {
2911                                 $fields[$field] = $public[$field];
2912                         }
2913                 }
2914                 if (!empty($fields)) {
2915                         self::update($fields, ['id' => $id, 'self' => false]);
2916                         Logger::info('Updating local contact', ['id' => $id]);
2917                 }
2918         }
2919
2920         /**
2921          * Updates contact record by provided URL
2922          *
2923          * @param integer $url contact url
2924          * @return integer Contact id
2925          * @throws HTTPException\InternalServerErrorException
2926          * @throws \ImagickException
2927          */
2928         public static function updateFromProbeByURL(string $url): int
2929         {
2930                 $id = self::getIdForURL($url);
2931
2932                 if (empty($id)) {
2933                         return $id;
2934                 }
2935
2936                 self::updateFromProbe($id);
2937
2938                 return $id;
2939         }
2940
2941         /**
2942          * Detects the communication protocol for a given contact url.
2943          * This is used to detect Friendica contacts that we can communicate via AP.
2944          *
2945          * @param string $url contact url
2946          * @param string $network Network of that contact
2947          * @return string with protocol
2948          */
2949         public static function getProtocol(string $url, string $network): string
2950         {
2951                 if ($network != Protocol::DFRN) {
2952                         return $network;
2953                 }
2954
2955                 $apcontact = APContact::getByURL($url);
2956                 if (!empty($apcontact) && !empty($apcontact['generator'])) {
2957                         return Protocol::ACTIVITYPUB;
2958                 } else {
2959                         return $network;
2960                 }
2961         }
2962
2963         /**
2964          * Takes a $uid and a url/handle and adds a new contact
2965          *
2966          * Currently if the contact is DFRN, interactive needs to be true, to redirect to the
2967          * dfrn_request page.
2968          *
2969          * Otherwise this can be used to bulk add StatusNet contacts, Twitter contacts, etc.
2970          *
2971          * Returns an array
2972          * $return['success'] boolean true if successful
2973          * $return['message'] error text if success is false.
2974          *
2975          * Takes a $uid and a url/handle and adds a new contact
2976          *
2977          * @param int    $uid         The user id the contact should be created for
2978          * @param string $url         The profile URL of the contact
2979          * @param string $network
2980          * @return array
2981          * @throws HTTPException\InternalServerErrorException
2982          * @throws HTTPException\NotFoundException
2983          * @throws \ImagickException
2984          */
2985         public static function createFromProbeForUser(int $uid, string $url, string $network = ''): array
2986         {
2987                 $result = ['cid' => -1, 'success' => false, 'message' => ''];
2988
2989                 // remove ajax junk, e.g. Twitter
2990                 $url = str_replace('/#!/', '/', $url);
2991
2992                 if (!Network::isUrlAllowed($url)) {
2993                         $result['message'] = DI::l10n()->t('Disallowed profile URL.');
2994                         return $result;
2995                 }
2996
2997                 if (Network::isUrlBlocked($url)) {
2998                         $result['message'] = DI::l10n()->t('Blocked domain');
2999                         return $result;
3000                 }
3001
3002                 if (!$url) {
3003                         $result['message'] = DI::l10n()->t('Connect URL missing.');
3004                         return $result;
3005                 }
3006
3007                 $arr = ['url' => $url, 'uid' => $uid, 'contact' => []];
3008
3009                 Hook::callAll('follow', $arr);
3010
3011                 if (empty($arr)) {
3012                         $result['message'] = DI::l10n()->t('The contact could not be added. Please check the relevant network credentials in your Settings -> Social Networks page.');
3013                         return $result;
3014                 }
3015
3016                 if (!empty($arr['contact']['name'])) {
3017                         $probed = false;
3018                         $ret = $arr['contact'];
3019                 } else {
3020                         $probed = true;
3021                         $ret = Probe::uri($url, $network, $uid);
3022
3023                         // Ensure that the public contact exists
3024                         if ($ret['network'] != Protocol::PHANTOM) {
3025                                 self::getIdForURL($url);
3026                         }
3027                 }
3028
3029                 if (($network != '') && ($ret['network'] != $network)) {
3030                         $result['message'] = DI::l10n()->t('Expected network %s does not match actual network %s', $network, $ret['network']);
3031                         return $result;
3032                 }
3033
3034                 // check if we already have a contact
3035                 $condition = ['uid' => $uid, 'nurl' => Strings::normaliseLink($ret['url']), 'deleted' => false];
3036                 $contact = DBA::selectFirst('contact', ['id', 'rel', 'url', 'pending', 'hub-verify'], $condition);
3037
3038                 $protocol = self::getProtocol($ret['url'], $ret['network']);
3039
3040                 // This extra param just confuses things, remove it
3041                 if ($protocol === Protocol::DIASPORA) {
3042                         $ret['url'] = str_replace('?absolute=true', '', $ret['url']);
3043                 }
3044
3045                 // do we have enough information?
3046                 if (empty($protocol) || ($protocol == Protocol::PHANTOM) || (empty($ret['url']) && empty($ret['addr']))) {
3047                         $result['message'] .= DI::l10n()->t('The profile address specified does not provide adequate information.') . '<br />';
3048                         if (empty($ret['poll'])) {
3049                                 $result['message'] .= DI::l10n()->t('No compatible communication protocols or feeds were discovered.') . '<br />';
3050                         }
3051                         if (empty($ret['name'])) {
3052                                 $result['message'] .= DI::l10n()->t('An author or name was not found.') . '<br />';
3053                         }
3054                         if (empty($ret['url'])) {
3055                                 $result['message'] .= DI::l10n()->t('No browser URL could be matched to this address.') . '<br />';
3056                         }
3057                         if (strpos($ret['url'], '@') !== false) {
3058                                 $result['message'] .= DI::l10n()->t('Unable to match @-style Identity Address with a known protocol or email contact.') . '<br />';
3059                                 $result['message'] .= DI::l10n()->t('Use mailto: in front of address to force email check.') . '<br />';
3060                         }
3061                         return $result;
3062                 }
3063
3064                 if ($protocol === Protocol::OSTATUS && DI::config()->get('system', 'ostatus_disabled')) {
3065                         $result['message'] .= DI::l10n()->t('The profile address specified belongs to a network which has been disabled on this site.') . '<br />';
3066                         $ret['notify'] = '';
3067                 }
3068
3069                 if (!$ret['notify']) {
3070                         $result['message'] .= DI::l10n()->t('Limited profile. This person will be unable to receive direct/personal notifications from you.') . '<br />';
3071                 }
3072
3073                 $writeable = ((($protocol === Protocol::OSTATUS) && ($ret['notify'])) ? 1 : 0);
3074
3075                 $subhub = (($protocol === Protocol::OSTATUS) ? true : false);
3076
3077                 $hidden = (($protocol === Protocol::MAIL) ? 1 : 0);
3078
3079                 $pending = false;
3080                 if (($protocol == Protocol::ACTIVITYPUB) && isset($ret['manually-approve'])) {
3081                         $pending = (bool)$ret['manually-approve'];
3082                 }
3083
3084                 if (in_array($protocol, [Protocol::MAIL, Protocol::DIASPORA, Protocol::ACTIVITYPUB])) {
3085                         $writeable = 1;
3086                 }
3087
3088                 if (DBA::isResult($contact)) {
3089                         // update contact
3090                         $new_relation = (in_array($contact['rel'], [self::FOLLOWER, self::FRIEND]) ? self::FRIEND : self::SHARING);
3091
3092                         $fields = ['rel' => $new_relation, 'subhub' => $subhub, 'readonly' => false, 'network' => $ret['network']];
3093
3094                         if ($contact['pending'] && !empty($contact['hub-verify'])) {
3095                                 ActivityPub\Transmitter::sendContactAccept($contact['url'], $contact['hub-verify'], $uid);
3096                                 $fields['pending'] = false;
3097                         }
3098
3099                         self::update($fields, ['id' => $contact['id']]);
3100                 } else {
3101                         $new_relation = (in_array($protocol, [Protocol::MAIL]) ? self::FRIEND : self::SHARING);
3102
3103                         // create contact record
3104                         self::insert([
3105                                 'uid'          => $uid,
3106                                 'created'      => DateTimeFormat::utcNow(),
3107                                 'url'          => $ret['url'],
3108                                 'nurl'         => Strings::normaliseLink($ret['url']),
3109                                 'addr'         => $ret['addr'],
3110                                 'alias'        => $ret['alias'],
3111                                 'batch'        => $ret['batch'],
3112                                 'notify'       => $ret['notify'],
3113                                 'poll'         => $ret['poll'],
3114                                 'poco'         => $ret['poco'],
3115                                 'name'         => $ret['name'],
3116                                 'nick'         => $ret['nick'],
3117                                 'network'      => $ret['network'],
3118                                 'baseurl'      => $ret['baseurl'],
3119                                 'gsid'         => $ret['gsid'] ?? null,
3120                                 'contact-type' => $ret['account-type'] ?? self::TYPE_PERSON,
3121                                 'protocol'     => $protocol,
3122                                 'pubkey'       => $ret['pubkey'],
3123                                 'rel'          => $new_relation,
3124                                 'priority'     => $ret['priority'],
3125                                 'writable'     => $writeable,
3126                                 'hidden'       => $hidden,
3127                                 'blocked'      => 0,
3128                                 'readonly'     => 0,
3129                                 'pending'      => $pending,
3130                                 'subhub'       => $subhub
3131                         ]);
3132                 }
3133
3134                 $contact = DBA::selectFirst('contact', [], ['url' => $ret['url'], 'network' => $ret['network'], 'uid' => $uid]);
3135                 if (!DBA::isResult($contact)) {
3136                         $result['message'] .= DI::l10n()->t('Unable to retrieve contact information.') . '<br />';
3137                         return $result;
3138                 }
3139
3140                 $contact_id = $contact['id'];
3141                 $result['cid'] = $contact_id;
3142
3143                 if ($contact['contact-type'] == self::TYPE_COMMUNITY) {
3144                         Circle::addMember(User::getDefaultGroupCircle($uid), $contact_id);
3145                 } else {
3146                         Circle::addMember(User::getDefaultCircle($uid), $contact_id);
3147                 }
3148
3149                 // Update the avatar
3150                 self::updateAvatar($contact_id, $ret['photo']);
3151
3152                 // pull feed and consume it, which should subscribe to the hub.
3153                 if ($contact['network'] == Protocol::OSTATUS) {
3154                         Worker::add(Worker::PRIORITY_HIGH, 'OnePoll', $contact_id, 'force');
3155                 }
3156
3157                 if ($probed) {
3158                         self::updateFromProbeArray($contact_id, $ret);
3159                 } else {
3160                         try {
3161                                 UpdateContact::add(Worker::PRIORITY_HIGH, $contact['id']);
3162                         } catch (\InvalidArgumentException $e) {
3163                                 Logger::notice($e->getMessage(), ['contact' => $contact]);
3164                         }
3165                 }
3166
3167                 $result['success'] = Protocol::follow($uid, $contact, $protocol);
3168
3169                 return $result;
3170         }
3171
3172         /**
3173          * @param array  $importer Owner (local user) data
3174          * @param array  $contact  Existing owner-specific contact data we want to expand the relationship with. Optional.
3175          * @param array  $datarray An item-like array with at least the 'author-id' and 'author-url' keys for the contact. Mandatory.
3176          * @param bool   $sharing  True: Contact is now sharing with Owner; False: Contact is now following Owner (default)
3177          * @param string $note     Introduction additional message
3178          * @return bool|null True: follow request is accepted; False: relationship is rejected; Null: relationship is pending
3179          * @throws HTTPException\InternalServerErrorException
3180          * @throws \ImagickException
3181          */
3182         public static function addRelationship(array $importer, array $contact, array $datarray, bool $sharing = false, string $note = '')
3183         {
3184                 // Should always be set
3185                 if (empty($datarray['author-id'])) {
3186                         return false;
3187                 }
3188
3189                 $fields = ['id', 'url', 'name', 'nick', 'avatar', 'photo', 'network', 'blocked'];
3190                 $pub_contact = DBA::selectFirst('contact', $fields, ['id' => $datarray['author-id']]);
3191                 if (!DBA::isResult($pub_contact)) {
3192                         // Should never happen
3193                         return false;
3194                 }
3195
3196                 // Contact is blocked at node-level
3197                 if (self::isBlocked($datarray['author-id'])) {
3198                         return false;
3199                 }
3200
3201                 $url = ($datarray['author-link'] ?? '') ?: $pub_contact['url'];
3202                 $name = $pub_contact['name'];
3203                 $photo = ($pub_contact['avatar'] ?? '') ?: $pub_contact["photo"];
3204                 $nick = $pub_contact['nick'];
3205                 $network = $pub_contact['network'];
3206
3207                 // Ensure that we don't create a new contact when there already is one
3208                 $cid = self::getIdForURL($url, $importer['uid']);
3209                 if (!empty($cid)) {
3210                         $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
3211                 }
3212
3213                 self::clearFollowerFollowingEndpointCache($importer['uid']);
3214
3215                 if (!empty($contact)) {
3216                         if (!empty($contact['pending'])) {
3217                                 Logger::info('Pending contact request already exists.', ['url' => $url, 'uid' => $importer['uid']]);
3218                                 return null;
3219                         }
3220
3221                         // Contact is blocked at user-level
3222                         if (
3223                                 !empty($contact['id']) && !empty($importer['id']) &&
3224                                 Contact\User::isBlocked($contact['id'], $importer['id'])
3225                         ) {
3226                                 return false;
3227                         }
3228
3229                         // Make sure that the existing contact isn't archived
3230                         self::unmarkForArchival($contact);
3231
3232                         if (($contact['rel'] == self::SHARING)
3233                                 || ($sharing && $contact['rel'] == self::FOLLOWER)
3234                         ) {
3235                                 self::update(
3236                                         ['rel' => self::FRIEND, 'writable' => true, 'pending' => false],
3237                                         ['id' => $contact['id'], 'uid' => $importer['uid']]
3238                                 );
3239                         }
3240
3241                         // Ensure to always have the correct network type, independent from the connection request method
3242                         self::updateFromProbe($contact['id']);
3243
3244                         Post\UserNotification::insertNotification($pub_contact['id'], Activity::FOLLOW, $importer['uid']);
3245
3246                         return true;
3247                 } else {
3248                         // send email notification to owner?
3249                         if (DBA::exists('contact', ['nurl' => Strings::normaliseLink($url), 'uid' => $importer['uid'], 'pending' => true])) {
3250                                 Logger::notice('ignoring duplicated connection request from pending contact ' . $url);
3251                                 return null;
3252                         }
3253
3254                         // create contact record
3255                         $contact_id = self::insert([
3256                                 'uid'      => $importer['uid'],
3257                                 'created'  => DateTimeFormat::utcNow(),
3258                                 'url'      => $url,
3259                                 'nurl'     => Strings::normaliseLink($url),
3260                                 'name'     => $name,
3261                                 'nick'     => $nick,
3262                                 'network'  => $network,
3263                                 'rel'      => self::FOLLOWER,
3264                                 'blocked'  => 0,
3265                                 'readonly' => 0,
3266                                 'pending'  => 1,
3267                                 'writable' => 1,
3268                         ]);
3269
3270                         // Ensure to always have the correct network type, independent from the connection request method
3271                         self::updateFromProbe($contact_id);
3272
3273                         self::updateAvatar($contact_id, $photo, true);
3274
3275                         Post\UserNotification::insertNotification($pub_contact['id'], Activity::FOLLOW, $importer['uid']);
3276
3277                         $contact_record = DBA::selectFirst('contact', ['id', 'network', 'name', 'url', 'photo', 'contact-type'], ['id' => $contact_id]);
3278
3279                         /// @TODO Encapsulate this into a function/method
3280                         $fields = ['uid', 'username', 'email', 'page-flags', 'notify-flags', 'language'];
3281                         $user = DBA::selectFirst('user', $fields, ['uid' => $importer['uid']]);
3282                         if (DBA::isResult($user) && !in_array($user['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_FREELOVE, User::PAGE_FLAGS_COMMUNITY])) {
3283                                 // create notification
3284                                 if (is_array($contact_record)) {
3285                                         $intro = DI::introFactory()->createNew(
3286                                                 $importer['uid'],
3287                                                 $contact_record['id'],
3288                                                 $note
3289                                         );
3290                                         DI::intro()->save($intro);
3291                                 }
3292
3293                                 if ($contact_record['contact-type'] == self::TYPE_COMMUNITY) {
3294                                         Circle::addMember(User::getDefaultGroupCircle($importer['uid']), $contact_record['id']);
3295                                 } else {
3296                                         Circle::addMember(User::getDefaultCircle($importer['uid']), $contact_record['id']);
3297                                 }
3298
3299                                 if (($user['notify-flags'] & Notification\Type::INTRO) && $user['page-flags'] == User::PAGE_FLAGS_NORMAL) {
3300                                         DI::notify()->createFromArray([
3301                                                 'type'  => Notification\Type::INTRO,
3302                                                 'otype' => Notification\ObjectType::INTRO,
3303                                                 'verb'  => ($sharing ? Activity::FRIEND : Activity::FOLLOW),
3304                                                 'uid'   => $user['uid'],
3305                                                 'cid'   => $contact_record['id'],
3306                                                 'link'  => DI::baseUrl() . '/notifications/intros',
3307                                         ]);
3308                                 }
3309                         } elseif (DBA::isResult($user) && in_array($user['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_FREELOVE, User::PAGE_FLAGS_COMMUNITY])) {
3310                                 if (($user['page-flags'] == User::PAGE_FLAGS_FREELOVE) && ($network != Protocol::DIASPORA)) {
3311                                         self::createFromProbeForUser($importer['uid'], $url, $network);
3312                                 }
3313
3314                                 $condition = ['uid' => $importer['uid'], 'url' => $url, 'pending' => true];
3315                                 $fields = ['pending' => false];
3316                                 if ($user['page-flags'] == User::PAGE_FLAGS_FREELOVE) {
3317                                         $fields['rel'] = self::FRIEND;
3318                                 }
3319
3320                                 self::update($fields, $condition);
3321
3322                                 return true;
3323                         }
3324                 }
3325
3326                 return null;
3327         }
3328
3329         /**
3330          * Update the local relationship when a local user loses a follower
3331          *
3332          * @param array $contact User-specific contact (uid != 0) array
3333          * @return void
3334          * @throws HTTPException\InternalServerErrorException
3335          * @throws \ImagickException
3336          */
3337         public static function removeFollower(array $contact)
3338         {
3339                 if (in_array($contact['rel'] ?? [], [self::FRIEND, self::SHARING])) {
3340                         self::update(['rel' => self::SHARING], ['id' => $contact['id']]);
3341                 } elseif (!empty($contact['id'])) {
3342                         self::remove($contact['id']);
3343                 } else {
3344                         DI::logger()->info('Couldn\'t remove follower because of invalid contact array', ['contact' => $contact, 'callstack' => System::callstack()]);
3345                         return;
3346                 }
3347
3348                 Worker::add(Worker::PRIORITY_LOW, 'ContactDiscoveryForUser', $contact['uid']);
3349
3350                 self::clearFollowerFollowingEndpointCache($contact['uid']);
3351
3352                 $cdata = self::getPublicAndUserContactID($contact['id'], $contact['uid']);
3353                 if (!empty($cdata['public'])) {
3354                         DI::notification()->deleteForUserByVerb($contact['uid'], Activity::FOLLOW, ['actor-id' => $cdata['public']]);
3355                 }
3356         }
3357
3358         /**
3359          * Update the local relationship when a local user unfollow a contact.
3360          * Removes the contact for sharing-only protocols (feed and mail).
3361          *
3362          * @param array $contact User-specific contact (uid != 0) array
3363          * @throws HTTPException\InternalServerErrorException
3364          */
3365         public static function removeSharer(array $contact)
3366         {
3367                 self::clearFollowerFollowingEndpointCache($contact['uid']);
3368
3369                 if ($contact['rel'] == self::SHARING || in_array($contact['network'], [Protocol::FEED, Protocol::MAIL])) {
3370                         self::remove($contact['id']);
3371                 } else {
3372                         self::update(['rel' => self::FOLLOWER, 'pending' => false], ['id' => $contact['id']]);
3373                 }
3374
3375                 Worker::add(Worker::PRIORITY_LOW, 'ContactDiscoveryForUser', $contact['uid']);
3376         }
3377
3378         /**
3379          * Create a birthday event.
3380          *
3381          * Update the year and the birthday.
3382          */
3383         public static function updateBirthdays()
3384         {
3385                 $condition = [
3386                         '`bd` > ?
3387                         AND (`contact`.`rel` = ? OR `contact`.`rel` = ?)
3388                         AND NOT `contact`.`pending`
3389                         AND NOT `contact`.`hidden`
3390                         AND NOT `contact`.`blocked`
3391                         AND NOT `contact`.`archive`
3392                         AND NOT `contact`.`deleted`',
3393                         DBA::NULL_DATE,
3394                         self::SHARING,
3395                         self::FRIEND
3396                 ];
3397
3398                 $contacts = DBA::select('contact', ['id', 'uid', 'name', 'url', 'bd'], $condition);
3399
3400                 while ($contact = DBA::fetch($contacts)) {
3401                         Logger::notice('update_contact_birthday: ' . $contact['bd']);
3402
3403                         $nextbd = DateTimeFormat::utcNow('Y') . substr($contact['bd'], 4);
3404
3405                         if (Event::createBirthday($contact, $nextbd)) {
3406                                 // update bdyear
3407                                 DBA::update(
3408                                         'contact',
3409                                         ['bdyear' => substr($nextbd, 0, 4), 'bd' => $nextbd],
3410                                         ['id' => $contact['id']]
3411                                 );
3412                         }
3413                 }
3414                 DBA::close($contacts);
3415         }
3416
3417         /**
3418          * Remove the unavailable contact ids from the provided list
3419          *
3420          * @param array $contact_ids Contact id list
3421          * @return array
3422          * @throws \Exception
3423          */
3424         public static function pruneUnavailable(array $contact_ids): array
3425         {
3426                 if (empty($contact_ids)) {
3427                         return [];
3428                 }
3429
3430                 $contacts = self::selectToArray(['id'], [
3431                         'id'      => $contact_ids,
3432                         'blocked' => false,
3433                         'pending' => false,
3434                         'archive' => false,
3435                 ]);
3436
3437                 return array_column($contacts, 'id');
3438         }
3439
3440         /**
3441          * Returns a magic link to authenticate remote visitors
3442          *
3443          * @todo  check if the return is either a fully qualified URL or a relative path to Friendica basedir
3444          *
3445          * @param string $contact_url The address of the target contact profile
3446          * @param string $url         An url that we will be redirected to after the authentication
3447          *
3448          * @return string with "redir" link
3449          * @throws HTTPException\InternalServerErrorException
3450          * @throws \ImagickException
3451          */
3452         public static function magicLink(string $contact_url, string $url = ''): string
3453         {
3454                 if (!DI::userSession()->isAuthenticated()) {
3455                         return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
3456                 }
3457
3458                 $contact = self::getByURL($contact_url, false);
3459                 if (empty($contact)) {
3460                         return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
3461                 }
3462
3463                 // Prevents endless loop in case only a non-public contact exists for the contact URL
3464                 unset($contact['uid']);
3465
3466                 return self::magicLinkByContact($contact, $url ?: $contact_url);
3467         }
3468
3469         /**
3470          * Returns a magic link to authenticate remote visitors
3471          *
3472          * @param integer $cid The contact id of the target contact profile
3473          * @param string  $url An url that we will be redirected to after the authentication
3474          *
3475          * @return string with "redir" link
3476          * @throws HTTPException\InternalServerErrorException
3477          * @throws \ImagickException
3478          */
3479         public static function magicLinkById(int $cid, string $url = ''): string
3480         {
3481                 $contact = DBA::selectFirst('contact', ['id', 'network', 'url', 'alias', 'uid'], ['id' => $cid]);
3482
3483                 return self::magicLinkByContact($contact, $url);
3484         }
3485
3486         /**
3487          * Returns a magic link to authenticate remote visitors
3488          *
3489          * @param array  $contact The contact array with "uid", "network" and "url"
3490          * @param string $url     An url that we will be redirected to after the authentication
3491          *
3492          * @return string with "redir" link
3493          * @throws HTTPException\InternalServerErrorException
3494          * @throws \ImagickException
3495          */
3496         public static function magicLinkByContact(array $contact, string $url = ''): string
3497         {
3498                 $destination = $url ?: (!Network::isValidHttpUrl($contact['url']) && !empty($contact['alias']) && Network::isValidHttpUrl($contact['alias']) ? $contact['alias'] : $contact['url']);
3499
3500                 if (!DI::userSession()->isAuthenticated()) {
3501                         return $destination;
3502                 }
3503
3504                 // Only redirections to the same host do make sense
3505                 if (($url != '') && (parse_url($url, PHP_URL_HOST) != parse_url($contact['url'], PHP_URL_HOST))) {
3506                         return $url;
3507                 }
3508
3509                 if (DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'system', 'stay_local') && ($url == '')) {
3510                         return 'contact/' . $contact['id'] . '/conversations';
3511                 }
3512
3513                 if (!empty($contact['network']) && $contact['network'] != Protocol::DFRN) {
3514                         return $destination;
3515                 }
3516
3517                 if (empty($contact['id'])) {
3518                         return $destination;
3519                 }
3520
3521                 $redirect = 'contact/redir/' . $contact['id'];
3522
3523                 if (($url != '') && !Strings::compareLink($contact['url'], $url)) {
3524                         $redirect .= '?url=' . $url;
3525                 }
3526
3527                 return $redirect;
3528         }
3529
3530         /**
3531          * Is the contact a group?
3532          *
3533          * @param integer $contactid ID of the contact
3534          *
3535          * @return boolean "true" if it is a group
3536          */
3537         public static function isGroup(int $contactid): bool
3538         {
3539                 $fields = ['contact-type'];
3540                 $condition = ['id' => $contactid];
3541                 $contact = DBA::selectFirst('contact', $fields, $condition);
3542                 if (!DBA::isResult($contact)) {
3543                         return false;
3544                 }
3545
3546                 // Is it a group?
3547                 return ($contact['contact-type'] == self::TYPE_COMMUNITY);
3548         }
3549
3550         /**
3551          * Can the remote contact receive private messages?
3552          *
3553          * @param array $contact
3554          * @return bool
3555          */
3556         public static function canReceivePrivateMessages(array $contact): bool
3557         {
3558                 $protocol = $contact['network'] ?? $contact['protocol'] ?? Protocol::PHANTOM;
3559                 $self = $contact['self'] ?? false;
3560
3561                 return in_array($protocol, [Protocol::DFRN, Protocol::DIASPORA, Protocol::ACTIVITYPUB]) && !$self;
3562         }
3563
3564         /**
3565          * Search contact table by nick or name
3566          *
3567          * @param string $search       Name or nick
3568          * @param string $mode         Search mode (e.g. "community")
3569          * @param bool   $show_blocked Show users from blocked servers. Default is false
3570          * @param int    $uid          User ID
3571          * @param int    $limit        Maximum amount of returned values
3572          * @param int    $offset       Limit offset
3573          *
3574          * @return array with search results
3575          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3576          */
3577         public static function searchByName(string $search, string $mode = '', bool $show_blocked = false, int $uid = 0, int $limit = 0, int $offset = 0): array
3578         {
3579                 if (empty($search)) {
3580                         return [];
3581                 }
3582
3583                 // check supported networks
3584                 $networks = [Protocol::DFRN, Protocol::ACTIVITYPUB];
3585                 if (DI::config()->get('system', 'diaspora_enabled')) {
3586                         $networks[] = Protocol::DIASPORA;
3587                 }
3588
3589                 if (!DI::config()->get('system', 'ostatus_disabled')) {
3590                         $networks[] = Protocol::OSTATUS;
3591                 }
3592
3593                 $condition = [
3594                         'network'        => $networks,
3595                         'server-failed'  => false,
3596                         'failed'         => false,
3597                         'deleted'        => false,
3598                         'unsearchable'   => false,
3599                         'uid'            => $uid
3600                 ];
3601
3602                 if (!$show_blocked) {
3603                         $condition['server-blocked'] = true;
3604                 }
3605
3606                 if ($uid == 0) {
3607                         $condition['blocked'] = false;
3608                 } else {
3609                         $condition['rel'] = [Contact::SHARING, Contact::FRIEND];
3610                 }
3611
3612                 // check if we search only communities or every contact
3613                 if ($mode === 'community') {
3614                         $condition['contact-type'] = self::TYPE_COMMUNITY;
3615                 }
3616
3617                 $search .= '%';
3618
3619                 $params = [];
3620
3621                 if (!empty($limit) && !empty($offset)) {
3622                         $params['limit'] = [$offset, $limit];
3623                 } elseif (!empty($limit)) {
3624                         $params['limit'] = $limit;
3625                 }
3626
3627                 $condition = DBA::mergeConditions(
3628                         $condition,
3629                         ["(`addr` LIKE ? OR `name` LIKE ? OR `nick` LIKE ?)", $search, $search, $search]
3630                 );
3631
3632                 return DBA::selectToArray('account-user-view', [], $condition, $params);
3633         }
3634
3635         /**
3636          * Add public contacts from an array
3637          *
3638          * @param array $urls
3639          * @return array result "count", "added" and "updated"
3640          */
3641         public static function addByUrls(array $urls): array
3642         {
3643                 $added = 0;
3644                 $updated = 0;
3645                 $unchanged = 0;
3646                 $count = 0;
3647
3648                 foreach ($urls as $url) {
3649                         if (empty($url) || !is_string($url)) {
3650                                 continue;
3651                         }
3652                         $contact = self::getByURL($url, false, ['id', 'network', 'next-update']);
3653                         if (empty($contact['id']) && Network::isValidHttpUrl($url)) {
3654                                 Worker::add(Worker::PRIORITY_LOW, 'AddContact', 0, $url);
3655                                 ++$added;
3656                         } elseif (!empty($contact['network']) && Protocol::supportsProbe($contact['network']) && ($contact['next-update'] < DateTimeFormat::utcNow())) {
3657                                 try {
3658                                         UpdateContact::add(['priority' => Worker::PRIORITY_LOW, 'dont_fork' => true], $contact['id']);
3659                                         ++$updated;
3660                                 } catch (\InvalidArgumentException $e) {
3661                                         Logger::notice($e->getMessage(), ['contact' => $contact]);
3662                                 }
3663                         } else {
3664                                 ++$unchanged;
3665                         }
3666                         ++$count;
3667                 }
3668
3669                 return ['count' => $count, 'added' => $added, 'updated' => $updated, 'unchanged' => $unchanged];
3670         }
3671
3672         /**
3673          * Returns a random, global contact array of the current node
3674          *
3675          * @return array The profile array
3676          * @throws Exception
3677          */
3678         public static function getRandomContact(): array
3679         {
3680                 $contact = DBA::selectFirst('contact', ['id', 'network', 'url', 'alias', 'uid'], [
3681                         "`uid` = ? AND `network` = ? AND NOT `failed` AND `last-item` > ?",
3682                         0, Protocol::DFRN, DateTimeFormat::utc('now - 1 month'),
3683                 ], ['order' => ['RAND()']]);
3684
3685                 if (DBA::isResult($contact)) {
3686                         return $contact;
3687                 }
3688
3689                 return [];
3690         }
3691
3692         /**
3693          * Checks, if contacts with the given condition exists
3694          *
3695          * @param array $condition
3696          *
3697          * @return bool
3698          * @throws \Exception
3699          */
3700         public static function exists(array $condition): bool
3701         {
3702                 return DBA::exists('contact', $condition);
3703         }
3704 }