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