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