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