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