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