]> git.mxchange.org Git - friendica.git/blob - src/Model/Contact.php
172540dd1f67402f32751eeb7f6bd8e54e470994
[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                         $platform = '';
1821
1822                         if (!empty($contact['id'])) {
1823                                 $account = DBA::selectFirst('account-user-view', ['platform'], ['id' => $contact['id']]);
1824                                 $platform = $account['platform'] ?? '';
1825                         }
1826         
1827                         if (empty($platform) && !empty($contact['uri-id'])) {
1828                                 $account = DBA::selectFirst('account-user-view', ['platform'], ['uri-id' => $contact['uri-id']]);
1829                                 $platform = $account['platform'] ?? '';
1830                         }
1831
1832                         switch ($platform) {
1833                                 case 'mastodon':
1834                                         // @see https://github.com/mastodon/mastodon/tree/main/public/avatars/original/missing.png
1835                                         $default = '/images/default/mastodon.png';
1836                                         break;
1837         
1838                                 case 'pleroma':
1839                                         // @see https://git.pleroma.social/pleroma/pleroma/-/blob/develop/priv/static/images/avi.png
1840                                         $default = '/images/default/pleroma.png';
1841                                         break;
1842
1843                                 case 'diaspora':
1844                                         // @see https://github.com/diaspora/diaspora/
1845                                         $default = '/images/default/diaspora.png';
1846                                         break;
1847
1848                                 case 'peertube':
1849                                         // @see https://github.com/Chocobozzz/PeerTube/blob/develop/client/src/assets/images/default-avatar-video-channel.png
1850                                         $default = '/images/default/peertube.png';
1851                                         break;
1852                         }
1853                         return DI::baseUrl() . $default;
1854                 }
1855
1856                 if (!empty($contact['xmpp'])) {
1857                         $avatar['email'] = $contact['xmpp'];
1858                 } elseif (!empty($contact['addr'])) {
1859                         $avatar['email'] = $contact['addr'];
1860                 } elseif (!empty($contact['url'])) {
1861                         $avatar['email'] = $contact['url'];
1862                 } else {
1863                         return DI::baseUrl() . $default;
1864                 }
1865
1866                 $avatar['url'] = '';
1867                 $avatar['success'] = false;
1868
1869                 Hook::callAll('avatar_lookup', $avatar);
1870
1871                 if ($avatar['success'] && !empty($avatar['url'])) {
1872                         return $avatar['url'];
1873                 }
1874
1875                 return DI::baseUrl() . $default;
1876         }
1877
1878         /**
1879          * Get avatar link for given contact id
1880          *
1881          * @param integer $cid     contact id
1882          * @param string  $size    One of the Proxy::SIZE_* constants
1883          * @param string  $updated Contact update date
1884          * @return string avatar link
1885          */
1886         public static function getAvatarUrlForId(int $cid, string $size = '', string $updated = '', string $guid = ''):string
1887         {
1888                 // We have to fetch the "updated" variable when it wasn't provided
1889                 // The parameter can be provided to improve performance
1890                 if (empty($updated)) {
1891                         $account = DBA::selectFirst('account-user-view', ['updated', 'guid'], ['id' => $cid]);
1892                         $updated = $account['updated'] ?? '';
1893                         $guid = $account['guid'] ?? '';
1894                 }
1895
1896                 $guid = urlencode($guid);
1897
1898                 $url = DI::baseUrl() . '/photo/contact/';
1899                 switch ($size) {
1900                         case Proxy::SIZE_MICRO:
1901                                 $url .= Proxy::PIXEL_MICRO . '/';
1902                                 break;
1903                         case Proxy::SIZE_THUMB:
1904                                 $url .= Proxy::PIXEL_THUMB . '/';
1905                                 break;
1906                         case Proxy::SIZE_SMALL:
1907                                 $url .= Proxy::PIXEL_SMALL . '/';
1908                                 break;
1909                         case Proxy::SIZE_MEDIUM:
1910                                 $url .= Proxy::PIXEL_MEDIUM . '/';
1911                                 break;
1912                         case Proxy::SIZE_LARGE:
1913                                 $url .= Proxy::PIXEL_LARGE . '/';
1914                                 break;
1915                 }
1916                 return $url . ($guid ?: $cid) . ($updated ? '?ts=' . strtotime($updated) : '');
1917         }
1918
1919         /**
1920          * Get avatar link for given contact URL
1921          *
1922          * @param string  $url  contact url
1923          * @param integer $uid  user id
1924          * @param string  $size One of the Proxy::SIZE_* constants
1925          * @return string avatar link
1926          */
1927         public static function getAvatarUrlForUrl(string $url, int $uid, string $size = ''):string
1928         {
1929                 $condition = ["`nurl` = ? AND ((`uid` = ? AND `network` IN (?, ?)) OR `uid` = ?)",
1930                         Strings::normaliseLink($url), $uid, Protocol::FEED, Protocol::MAIL, 0];
1931                 $contact = self::selectFirst(['id', 'updated'], $condition, ['order' => ['uid' => true]]);
1932                 return self::getAvatarUrlForId($contact['id'] ?? 0, $size, $contact['updated'] ?? '');
1933         }
1934
1935         /**
1936          * Get header link for given contact id
1937          *
1938          * @param integer $cid     contact id
1939          * @param string  $size    One of the Proxy::SIZE_* constants
1940          * @param string  $updated Contact update date
1941          * @return string header link
1942          */
1943         public static function getHeaderUrlForId(int $cid, string $size = '', string $updated = '', string $guid = ''):string
1944         {
1945                 // We have to fetch the "updated" variable when it wasn't provided
1946                 // The parameter can be provided to improve performance
1947                 if (empty($updated) || empty($guid)) {
1948                         $account = DBA::selectFirst('account-user-view', ['updated', 'guid'], ['id' => $cid]);
1949                         $updated = $account['updated'] ?? '';
1950                         $guid = $account['guid'] ?? '';
1951                 }
1952
1953                 $guid = urlencode($guid);
1954
1955                 $url = DI::baseUrl() . '/photo/header/';
1956                 switch ($size) {
1957                         case Proxy::SIZE_MICRO:
1958                                 $url .= Proxy::PIXEL_MICRO . '/';
1959                                 break;
1960                         case Proxy::SIZE_THUMB:
1961                                 $url .= Proxy::PIXEL_THUMB . '/';
1962                                 break;
1963                         case Proxy::SIZE_SMALL:
1964                                 $url .= Proxy::PIXEL_SMALL . '/';
1965                                 break;
1966                         case Proxy::SIZE_MEDIUM:
1967                                 $url .= Proxy::PIXEL_MEDIUM . '/';
1968                                 break;
1969                         case Proxy::SIZE_LARGE:
1970                                 $url .= Proxy::PIXEL_LARGE . '/';
1971                                 break;
1972                 }
1973
1974                 return $url . ($guid ?: $cid) . ($updated ? '?ts=' . strtotime($updated) : '');
1975         }
1976
1977         /**
1978          * Updates the avatar links in a contact only if needed
1979          *
1980          * @param int    $cid          Contact id
1981          * @param string $avatar       Link to avatar picture
1982          * @param bool   $force        force picture update
1983          * @param bool   $create_cache Enforces the creation of cached avatar fields
1984          *
1985          * @return void
1986          * @throws HTTPException\InternalServerErrorException
1987          * @throws HTTPException\NotFoundException
1988          * @throws \ImagickException
1989          */
1990         public static function updateAvatar(int $cid, string $avatar, bool $force = false, bool $create_cache = false)
1991         {
1992                 $contact = DBA::selectFirst('contact', ['uid', 'avatar', 'photo', 'thumb', 'micro', 'xmpp', 'addr', 'nurl', 'url', 'network', 'uri-id'],
1993                         ['id' => $cid, 'self' => false]);
1994                 if (!DBA::isResult($contact)) {
1995                         return;
1996                 }
1997
1998                 $uid = $contact['uid'];
1999
2000                 // Only update the cached photo links of public contacts when they already are cached
2001                 if (($uid == 0) && !$force && empty($contact['thumb']) && empty($contact['micro']) && !$create_cache) {
2002                         if ($contact['avatar'] != $avatar) {
2003                                 self::update(['avatar' => $avatar], ['id' => $cid]);
2004                                 Logger::info('Only update the avatar', ['id' => $cid, 'avatar' => $avatar, 'contact' => $contact]);
2005                         }
2006                         return;
2007                 }
2008
2009                 // User contacts use are updated through the public contacts
2010                 if (($uid != 0) && !in_array($contact['network'], [Protocol::FEED, Protocol::MAIL])) {
2011                         $pcid = self::getIdForURL($contact['url'], 0, false);
2012                         if (!empty($pcid)) {
2013                                 Logger::debug('Update the private contact via the public contact', ['id' => $cid, 'uid' => $uid, 'public' => $pcid]);
2014                                 self::updateAvatar($pcid, $avatar, $force, true);
2015                                 return;
2016                         }
2017                 }
2018
2019                 $default_avatar = empty($avatar) || strpos($avatar, self::DEFAULT_AVATAR_PHOTO);
2020
2021                 if ($default_avatar) {
2022                         $avatar = self::getDefaultAvatar($contact, Proxy::SIZE_SMALL);
2023                 }
2024
2025                 $cache_avatar = DI::config()->get('system', 'cache_contact_avatar');
2026
2027                 // Local contact avatars don't need to be cached
2028                 if ($cache_avatar && Network::isLocalLink($contact['url'])) {
2029                         $cache_avatar = !DBA::exists('contact', ['nurl' => $contact['nurl'], 'self' => true]);
2030                 }
2031
2032                 if (in_array($contact['network'], [Protocol::FEED, Protocol::MAIL]) || $cache_avatar) {
2033                         Avatar::deleteCache($contact);
2034
2035                         if ($default_avatar && Proxy::isLocalImage($avatar)) {
2036                                 $fields = ['avatar' => $avatar, 'avatar-date' => DateTimeFormat::utcNow(),
2037                                         'photo' => $avatar,
2038                                         'thumb' => self::getDefaultAvatar($contact, Proxy::SIZE_THUMB),
2039                                         'micro' => self::getDefaultAvatar($contact, Proxy::SIZE_MICRO)];
2040                                 Logger::debug('Use default avatar', ['id' => $cid, 'uid' => $uid]);
2041                         }
2042
2043                         // Use the data from the self account
2044                         if (empty($fields)) {
2045                                 $local_uid = User::getIdForURL($contact['url']);
2046                                 if (!empty($local_uid)) {
2047                                         $fields = self::selectFirst(['avatar', 'avatar-date', 'photo', 'thumb', 'micro'], ['self' => true, 'uid' => $local_uid]);
2048                                         Logger::debug('Use owner data', ['id' => $cid, 'uid' => $uid, 'owner-uid' => $local_uid]);
2049                                 }
2050                         }
2051
2052                         if (empty($fields)) {
2053                                 $update = ($contact['avatar'] != $avatar) || $force;
2054
2055                                 if (!$update) {
2056                                         $data = [
2057                                                 $contact['photo'] ?? '',
2058                                                 $contact['thumb'] ?? '',
2059                                                 $contact['micro'] ?? '',
2060                                         ];
2061
2062                                         foreach ($data as $image_uri) {
2063                                                 $image_rid = Photo::ridFromURI($image_uri);
2064                                                 if ($image_rid && !Photo::exists(['resource-id' => $image_rid, 'uid' => $uid])) {
2065                                                         Logger::debug('Regenerating avatar', ['contact uid' => $uid, 'cid' => $cid, 'missing photo' => $image_rid, 'avatar' => $contact['avatar']]);
2066                                                         $update = true;
2067                                                 }
2068                                         }
2069                                 }
2070
2071                                 if ($update) {
2072                                         $photos = Photo::importProfilePhoto($avatar, $uid, $cid, true);
2073                                         if ($photos) {
2074                                                 $fields = ['avatar' => $avatar, 'photo' => $photos[0], 'thumb' => $photos[1], 'micro' => $photos[2], 'avatar-date' => DateTimeFormat::utcNow()];
2075                                                 $update = !empty($fields);
2076                                                 Logger::debug('Created new cached avatars', ['id' => $cid, 'uid' => $uid, 'owner-uid' => $local_uid]);
2077                                         } else {
2078                                                 $update = false;
2079                                         }
2080                                 }
2081                         } else {
2082                                 $update = ($fields['photo'] . $fields['thumb'] . $fields['micro'] != $contact['photo'] . $contact['thumb'] . $contact['micro']) || $force;
2083                         }
2084                 } else {
2085                         Photo::delete(['uid' => $uid, 'contact-id' => $cid, 'photo-type' => Photo::CONTACT_AVATAR]);
2086                         $fields = Avatar::fetchAvatarContact($contact, $avatar, $force);
2087                         $update = ($avatar . $fields['photo'] . $fields['thumb'] . $fields['micro'] != $contact['avatar'] . $contact['photo'] . $contact['thumb'] . $contact['micro']) || $force;
2088                 }
2089
2090                 if (!$update) {
2091                         return;
2092                 }
2093
2094                 $cids = [];
2095                 $uids = [];
2096                 if (($uid == 0) && !in_array($contact['network'], [Protocol::FEED, Protocol::MAIL])) {
2097                         // Collect all user contacts of the given public contact
2098                         $personal_contacts = DBA::select('contact', ['id', 'uid'],
2099                                 ["`nurl` = ? AND `id` != ? AND NOT `self`", $contact['nurl'], $cid]);
2100                         while ($personal_contact = DBA::fetch($personal_contacts)) {
2101                                 $cids[] = $personal_contact['id'];
2102                                 $uids[] = $personal_contact['uid'];
2103                         }
2104                         DBA::close($personal_contacts);
2105
2106                         if (!empty($cids)) {
2107                                 // Delete possibly existing cached user contact avatars
2108                                 Photo::delete(['uid' => $uids, 'contact-id' => $cids, 'photo-type' => Photo::CONTACT_AVATAR]);
2109                         }
2110                 }
2111
2112                 $cids[] = $cid;
2113                 $uids[] = $uid;
2114                 Logger::info('Updating cached contact avatars', ['cid' => $cids, 'uid' => $uids, 'fields' => $fields]);
2115                 self::update($fields, ['id' => $cids]);
2116         }
2117
2118         public static function deleteContactByUrl(string $url)
2119         {
2120                 // Update contact data for all users
2121                 $condition = ['self' => false, 'nurl' => Strings::normaliseLink($url)];
2122                 $contacts = DBA::select('contact', ['id', 'uid'], $condition);
2123                 while ($contact = DBA::fetch($contacts)) {
2124                         Logger::info('Deleting contact', ['id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $url]);
2125                         self::remove($contact['id']);
2126                 }
2127         }
2128
2129         /**
2130          * Helper function for "updateFromProbe". Updates personal and public contact
2131          *
2132          * @param integer $id      contact id
2133          * @param integer $uid     user id
2134          * @param string  $old_url The previous profile URL of the contact
2135          * @param string  $new_url The profile URL of the contact
2136          * @param array   $fields  The fields that are updated
2137          *
2138          * @throws \Exception
2139          */
2140         private static function updateContact(int $id, int $uid, string $old_url, string $new_url, array $fields)
2141         {
2142                 if (!self::update($fields, ['id' => $id])) {
2143                         Logger::info('Couldn\'t update contact.', ['id' => $id, 'fields' => $fields]);
2144                         return;
2145                 }
2146
2147                 // Search for duplicated contacts and get rid of them
2148                 if (self::removeDuplicates(Strings::normaliseLink($new_url), $uid)) {
2149                         return;
2150                 }
2151
2152                 // Archive or unarchive the contact.
2153                 $contact = DBA::selectFirst('contact', [], ['id' => $id]);
2154                 if (!DBA::isResult($contact)) {
2155                         Logger::info('Couldn\'t select contact for archival.', ['id' => $id]);
2156                         return;
2157                 }
2158
2159                 if (isset($fields['failed'])) {
2160                         if ($fields['failed']) {
2161                                 self::markForArchival($contact);
2162                         } else {
2163                                 self::unmarkForArchival($contact);
2164                         }
2165                 }
2166
2167                 if ($contact['uid'] != 0) {
2168                         return;
2169                 }
2170
2171                 // Update contact data for all users
2172                 $condition = ['self' => false, 'nurl' => Strings::normaliseLink($old_url)];
2173
2174                 $condition['network'] = [Protocol::DFRN, Protocol::DIASPORA, Protocol::ACTIVITYPUB];
2175                 self::update($fields, $condition);
2176
2177                 // We mustn't set the update fields for OStatus contacts since they are updated in OnePoll
2178                 $condition['network'] = Protocol::OSTATUS;
2179
2180                 // If the contact failed, propagate the update fields to all contacts
2181                 if (empty($fields['failed'])) {
2182                         unset($fields['last-update']);
2183                         unset($fields['success_update']);
2184                         unset($fields['failure_update']);
2185                 }
2186
2187                 if (empty($fields)) {
2188                         return;
2189                 }
2190
2191                 self::update($fields, $condition);
2192         }
2193
2194         /**
2195          * Remove duplicated contacts
2196          *
2197          * @param string  $nurl  Normalised contact url
2198          * @param integer $uid   User id
2199          * @return boolean
2200          * @throws \Exception
2201          */
2202         public static function removeDuplicates(string $nurl, int $uid)
2203         {
2204                 $condition = ['nurl' => $nurl, 'uid' => $uid, 'self' => false, 'deleted' => false, 'network' => Protocol::FEDERATED];
2205                 $count = DBA::count('contact', $condition);
2206                 if ($count <= 1) {
2207                         return false;
2208                 }
2209
2210                 $first_contact = DBA::selectFirst('contact', ['id', 'network'], $condition, ['order' => ['id']]);
2211                 if (!DBA::isResult($first_contact)) {
2212                         // Shouldn't happen - so we handle it
2213                         return false;
2214                 }
2215
2216                 $first = $first_contact['id'];
2217                 Logger::info('Found duplicates', ['count' => $count, 'first' => $first, 'uid' => $uid, 'nurl' => $nurl]);
2218                 if (($uid != 0 && ($first_contact['network'] == Protocol::DFRN))) {
2219                         // Don't handle non public DFRN duplicates by now (legacy DFRN is very special because of the key handling)
2220                         Logger::info('Not handling non public DFRN duplicate', ['uid' => $uid, 'nurl' => $nurl]);
2221                         return false;
2222                 }
2223
2224                 // Find all duplicates
2225                 $condition = ["`nurl` = ? AND `uid` = ? AND `id` != ? AND NOT `self` AND NOT `deleted`", $nurl, $uid, $first];
2226                 $duplicates = DBA::select('contact', ['id', 'network'], $condition);
2227                 while ($duplicate = DBA::fetch($duplicates)) {
2228                         if (!in_array($duplicate['network'], Protocol::FEDERATED)) {
2229                                 continue;
2230                         }
2231
2232                         Worker::add(PRIORITY_HIGH, 'MergeContact', $first, $duplicate['id'], $uid);
2233                 }
2234                 DBA::close($duplicates);
2235                 Logger::info('Duplicates handled', ['uid' => $uid, 'nurl' => $nurl, 'callstack' => System::callstack(20)]);
2236                 return true;
2237         }
2238
2239         /**
2240          * @param integer $id      contact id
2241          * @param string  $network Optional network we are probing for
2242          * @return boolean
2243          * @throws HTTPException\InternalServerErrorException
2244          * @throws \ImagickException
2245          */
2246         public static function updateFromProbe(int $id, string $network = '')
2247         {
2248                 $contact = DBA::selectFirst('contact', ['uid', 'url'], ['id' => $id]);
2249                 if (!DBA::isResult($contact)) {
2250                         return false;
2251                 }
2252
2253                 $ret = Probe::uri($contact['url'], $network, $contact['uid']);
2254
2255                 if ($ret['network'] == Protocol::DIASPORA) {
2256                         FContact::updateFromProbeArray($ret);
2257                 }
2258
2259                 return self::updateFromProbeArray($id, $ret);
2260         }
2261
2262         /**
2263          * @param integer $id      contact id
2264          * @param array   $ret     Probed data
2265          * @return boolean
2266          * @throws HTTPException\InternalServerErrorException
2267          * @throws \ImagickException
2268          */
2269         private static function updateFromProbeArray(int $id, array $ret)
2270         {
2271                 /*
2272                   Warning: Never ever fetch the public key via Probe::uri and write it into the contacts.
2273                   This will reliably kill your communication with old Friendica contacts.
2274                  */
2275
2276                 // These fields aren't updated by this routine:
2277                 // 'sensitive'
2278
2279                 $fields = ['uid', 'uri-id', 'avatar', 'header', 'name', 'nick', 'location', 'keywords', 'about', 'subscribe',
2280                         'manually-approve', 'unsearchable', 'url', 'addr', 'batch', 'notify', 'poll', 'request', 'confirm', 'poco',
2281                         'network', 'alias', 'baseurl', 'gsid', 'forum', 'prv', 'contact-type', 'pubkey', 'last-item', 'xmpp', 'matrix'];
2282                 $contact = DBA::selectFirst('contact', $fields, ['id' => $id]);
2283                 if (!DBA::isResult($contact)) {
2284                         return false;
2285                 }
2286
2287                 if (self::isLocal($ret['url'])) {
2288                         if ($contact['uid'] == 0) {
2289                                 Logger::info('Local contacts are not updated here.');
2290                         } else {
2291                                 self::updateFromPublicContact($id, $contact);
2292                         }
2293                         return true;
2294                 }
2295
2296                 if (!empty($ret['account-type']) && $ret['account-type'] == User::ACCOUNT_TYPE_DELETED) {
2297                         Logger::info('Deleted account', ['id' => $id, 'url' => $ret['url'], 'ret' => $ret]);
2298                         self::remove($id);
2299
2300                         // Delete all contacts with the same URL
2301                         self::deleteContactByUrl($ret['url']);
2302                         return true;
2303                 }
2304
2305                 $uid = $contact['uid'];
2306                 unset($contact['uid']);
2307
2308                 $uriid = $contact['uri-id'];
2309                 unset($contact['uri-id']);
2310
2311                 $pubkey = $contact['pubkey'];
2312                 unset($contact['pubkey']);
2313
2314                 $contact['photo'] = $contact['avatar'];
2315                 unset($contact['avatar']);
2316
2317                 $updated = DateTimeFormat::utcNow();
2318
2319                 if (Strings::normaliseLink($contact['url']) != Strings::normaliseLink($ret['url'])) {
2320                         Logger::notice('New URL differs from old URL', ['id' => $id, 'uid' => $uid, 'old' => $contact['url'], 'new' => $ret['url']]);
2321                         self::updateContact($id, $uid, $contact['url'], $ret['url'], ['failed' => true, 'last-update' => $updated, 'failure_update' => $updated]);
2322                         return false;
2323                 }
2324
2325                 // We must not try to update relay contacts via probe. They are no real contacts.
2326                 // We check after the probing to be able to correct falsely detected contact types.
2327                 if (($contact['contact-type'] == self::TYPE_RELAY) &&
2328                         (!Strings::compareLink($ret['url'], $contact['url']) || in_array($ret['network'], [Protocol::FEED, Protocol::PHANTOM]))) {
2329                         self::updateContact($id, $uid, $contact['url'], $contact['url'], ['failed' => false, 'last-update' => $updated, 'success_update' => $updated]);
2330                         Logger::info('Not updating relais', ['id' => $id, 'url' => $contact['url']]);
2331                         return true;
2332                 }
2333
2334                 // If Probe::uri fails the network code will be different ("feed" or "unkn")
2335                 if (($ret['network'] == Protocol::PHANTOM) || (($ret['network'] == Protocol::FEED) && ($ret['network'] != $contact['network']))) {
2336                         self::updateContact($id, $uid, $contact['url'], $ret['url'], ['failed' => true, 'last-update' => $updated, 'failure_update' => $updated]);
2337                         return false;
2338                 }
2339
2340                 if (Strings::normaliseLink($ret['url']) != Strings::normaliseLink($contact['url'])) {
2341                         $cid = self::getIdForURL($ret['url'], 0, false);
2342                         if (!empty($cid) && ($cid != $id)) {
2343                                 Logger::notice('URL of contact changed.', ['id' => $id, 'new_id' => $cid, 'old' => $contact['url'], 'new' => $ret['url']]);
2344                                 return self::updateFromProbeArray($cid, $ret);
2345                         }
2346                 }
2347
2348                 if (isset($ret['hide']) && is_bool($ret['hide'])) {
2349                         $ret['unsearchable'] = $ret['hide'];
2350                 }
2351
2352                 if (isset($ret['account-type']) && is_int($ret['account-type'])) {
2353                         $ret['forum'] = false;
2354                         $ret['prv'] = false;
2355                         $ret['contact-type'] = $ret['account-type'];
2356                         if (($ret['contact-type'] == User::ACCOUNT_TYPE_COMMUNITY) && isset($ret['manually-approve'])) {
2357                                 $ret['forum'] = (bool)!$ret['manually-approve'];
2358                                 $ret['prv'] = (bool)!$ret['forum'];
2359                         }
2360                 }
2361
2362                 $new_pubkey = $ret['pubkey'] ?? '';
2363
2364                 if ($uid == 0) {
2365                         if ($ret['network'] == Protocol::ACTIVITYPUB) {
2366                                 $apcontact = APContact::getByURL($ret['url'], false);
2367                                 if (!empty($apcontact['featured'])) {
2368                                         Worker::add(PRIORITY_LOW, 'FetchFeaturedPosts', $ret['url']);
2369                                 }
2370                         }
2371
2372                         $ret['last-item'] = Probe::getLastUpdate($ret);
2373                         Logger::info('Fetched last item', ['id' => $id, 'probed_url' => $ret['url'], 'last-item' => $ret['last-item'], 'callstack' => System::callstack(20)]);
2374                 }
2375
2376                 $update = false;
2377                 $guid = ($ret['guid'] ?? '') ?: Item::guidFromUri($ret['url'], parse_url($ret['url'], PHP_URL_HOST));
2378
2379                 // make sure to not overwrite existing values with blank entries except some technical fields
2380                 $keep = ['batch', 'notify', 'poll', 'request', 'confirm', 'poco', 'baseurl'];
2381                 foreach ($ret as $key => $val) {
2382                         if (!array_key_exists($key, $contact)) {
2383                                 unset($ret[$key]);
2384                         } elseif (($contact[$key] != '') && ($val === '') && !is_bool($ret[$key]) && !in_array($key, $keep)) {
2385                                 $ret[$key] = $contact[$key];
2386                         } elseif ($ret[$key] != $contact[$key]) {
2387                                 $update = true;
2388                         }
2389                 }
2390
2391                 if (!empty($ret['last-item']) && ($contact['last-item'] < $ret['last-item'])) {
2392                         $update = true;
2393                 } else {
2394                         unset($ret['last-item']);
2395                 }
2396
2397                 if (empty($uriid)) {
2398                         $update = true;
2399                 }
2400
2401                 if (!empty($ret['photo']) && ($ret['network'] != Protocol::FEED)) {
2402                         self::updateAvatar($id, $ret['photo'], $update);
2403                 }
2404
2405                 $uriid = ItemURI::insert(['uri' => $ret['url'], 'guid' => $guid]);
2406
2407                 if (!$update) {
2408                         self::updateContact($id, $uid, $contact['url'], $ret['url'], ['failed' => false, 'last-update' => $updated, 'success_update' => $updated]);
2409
2410                         if (Contact\Relation::isDiscoverable($ret['url'])) {
2411                                 Worker::add(PRIORITY_LOW, 'ContactDiscovery', $ret['url']);
2412                         }
2413
2414                         // Update the public contact
2415                         if ($uid != 0) {
2416                                 $contact = self::getByURL($ret['url'], false, ['id']);
2417                                 if (!empty($contact['id'])) {
2418                                         self::updateFromProbeArray($contact['id'], $ret);
2419                                 }
2420                         }
2421
2422                         return true;
2423                 }
2424
2425                 $ret['uri-id']  = $uriid;
2426                 $ret['nurl']    = Strings::normaliseLink($ret['url']);
2427                 $ret['updated'] = $updated;
2428                 $ret['failed']  = false;
2429
2430                 // Only fill the pubkey if it had been empty before. We have to prevent identity theft.
2431                 if (empty($pubkey) && !empty($new_pubkey)) {
2432                         $ret['pubkey'] = $new_pubkey;
2433                 }
2434
2435                 if ((!empty($ret['addr']) && ($ret['addr'] != $contact['addr'])) || (!empty($ret['alias']) && ($ret['alias'] != $contact['alias']))) {
2436                         $ret['uri-date'] = $updated;
2437                 }
2438
2439                 if ((!empty($ret['name']) && ($ret['name'] != $contact['name'])) || (!empty($ret['nick']) && ($ret['nick'] != $contact['nick']))) {
2440                         $ret['name-date'] = $updated;
2441                 }
2442
2443                 if (($uid == 0) || in_array($ret['network'], [Protocol::DFRN, Protocol::DIASPORA, Protocol::ACTIVITYPUB])) {
2444                         $ret['last-update'] = $updated;
2445                         $ret['success_update'] = $updated;
2446                 }
2447
2448                 unset($ret['photo']);
2449
2450                 self::updateContact($id, $uid, $contact['url'], $ret['url'], $ret);
2451
2452                 if (Contact\Relation::isDiscoverable($ret['url'])) {
2453                         Worker::add(PRIORITY_LOW, 'ContactDiscovery', $ret['url']);
2454                 }
2455
2456                 return true;
2457         }
2458
2459         private static function updateFromPublicContact(int $id, array $contact)
2460         {
2461                 $public = self::getByURL($contact['url'], false);
2462
2463                 $fields = [];
2464
2465                 foreach ($contact as $field => $value) {
2466                         if ($field == 'uid') {
2467                                 continue;
2468                         }
2469                         if ($public[$field] != $value) {
2470                                 $fields[$field] = $public[$field];
2471                         }
2472                 }
2473                 if (!empty($fields)) {
2474                         self::update($fields, ['id' => $id, 'self' => false]);
2475                         Logger::info('Updating local contact', ['id' => $id]);
2476                 }
2477         }
2478
2479         /**
2480          * @param integer $url contact url
2481          * @return integer Contact id
2482          * @throws HTTPException\InternalServerErrorException
2483          * @throws \ImagickException
2484          */
2485         public static function updateFromProbeByURL($url)
2486         {
2487                 $id = self::getIdForURL($url);
2488
2489                 if (empty($id)) {
2490                         return $id;
2491                 }
2492
2493                 self::updateFromProbe($id);
2494
2495                 return $id;
2496         }
2497
2498         /**
2499          * Detects the communication protocol for a given contact url.
2500          * This is used to detect Friendica contacts that we can communicate via AP.
2501          *
2502          * @param string $url contact url
2503          * @param string $network Network of that contact
2504          * @return string with protocol
2505          */
2506         public static function getProtocol($url, $network)
2507         {
2508                 if ($network != Protocol::DFRN) {
2509                         return $network;
2510                 }
2511
2512                 $apcontact = APContact::getByURL($url);
2513                 if (!empty($apcontact) && !empty($apcontact['generator'])) {
2514                         return Protocol::ACTIVITYPUB;
2515                 } else {
2516                         return $network;
2517                 }
2518         }
2519
2520         /**
2521          * Takes a $uid and a url/handle and adds a new contact
2522          *
2523          * Currently if the contact is DFRN, interactive needs to be true, to redirect to the
2524          * dfrn_request page.
2525          *
2526          * Otherwise this can be used to bulk add StatusNet contacts, Twitter contacts, etc.
2527          *
2528          * Returns an array
2529          * $return['success'] boolean true if successful
2530          * $return['message'] error text if success is false.
2531          *
2532          * Takes a $uid and a url/handle and adds a new contact
2533          *
2534          * @param int    $uid         The user id the contact should be created for
2535          * @param string $url         The profile URL of the contact
2536          * @param string $network
2537          * @return array
2538          * @throws HTTPException\InternalServerErrorException
2539          * @throws HTTPException\NotFoundException
2540          * @throws \ImagickException
2541          */
2542         public static function createFromProbeForUser(int $uid, $url, $network = '')
2543         {
2544                 $result = ['cid' => -1, 'success' => false, 'message' => ''];
2545
2546                 // remove ajax junk, e.g. Twitter
2547                 $url = str_replace('/#!/', '/', $url);
2548
2549                 if (!Network::isUrlAllowed($url)) {
2550                         $result['message'] = DI::l10n()->t('Disallowed profile URL.');
2551                         return $result;
2552                 }
2553
2554                 if (Network::isUrlBlocked($url)) {
2555                         $result['message'] = DI::l10n()->t('Blocked domain');
2556                         return $result;
2557                 }
2558
2559                 if (!$url) {
2560                         $result['message'] = DI::l10n()->t('Connect URL missing.');
2561                         return $result;
2562                 }
2563
2564                 $arr = ['url' => $url, 'contact' => []];
2565
2566                 Hook::callAll('follow', $arr);
2567
2568                 if (empty($arr)) {
2569                         $result['message'] = DI::l10n()->t('The contact could not be added. Please check the relevant network credentials in your Settings -> Social Networks page.');
2570                         return $result;
2571                 }
2572
2573                 if (!empty($arr['contact']['name'])) {
2574                         $probed = false;
2575                         $ret = $arr['contact'];
2576                 } else {
2577                         $probed = true;
2578                         $ret = Probe::uri($url, $network, $uid);
2579
2580                         // Ensure that the public contact exists
2581                         if ($ret['network'] != Protocol::PHANTOM) {
2582                                 self::getIdForURL($url);
2583                         }
2584                 }
2585
2586                 if (($network != '') && ($ret['network'] != $network)) {
2587                         Logger::notice('Expected network ' . $network . ' does not match actual network ' . $ret['network']);
2588                         return $result;
2589                 }
2590
2591                 // check if we already have a contact
2592                 // the poll url is more reliable than the profile url, as we may have
2593                 // indirect links or webfinger links
2594
2595                 $condition = ['uid' => $uid, 'poll' => [$ret['poll'], Strings::normaliseLink($ret['poll'])], 'network' => $ret['network'], 'pending' => false];
2596                 $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
2597                 if (!DBA::isResult($contact)) {
2598                         $condition = ['uid' => $uid, 'nurl' => Strings::normaliseLink($ret['url']), 'network' => $ret['network'], 'pending' => false];
2599                         $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
2600                 }
2601
2602                 $protocol = self::getProtocol($ret['url'], $ret['network']);
2603
2604                 // This extra param just confuses things, remove it
2605                 if ($protocol === Protocol::DIASPORA) {
2606                         $ret['url'] = str_replace('?absolute=true', '', $ret['url']);
2607                 }
2608
2609                 // do we have enough information?
2610                 if (empty($protocol) || ($protocol == Protocol::PHANTOM) || (empty($ret['url']) && empty($ret['addr']))) {
2611                         $result['message'] .= DI::l10n()->t('The profile address specified does not provide adequate information.') . EOL;
2612                         if (empty($ret['poll'])) {
2613                                 $result['message'] .= DI::l10n()->t('No compatible communication protocols or feeds were discovered.') . EOL;
2614                         }
2615                         if (empty($ret['name'])) {
2616                                 $result['message'] .= DI::l10n()->t('An author or name was not found.') . EOL;
2617                         }
2618                         if (empty($ret['url'])) {
2619                                 $result['message'] .= DI::l10n()->t('No browser URL could be matched to this address.') . EOL;
2620                         }
2621                         if (strpos($ret['url'], '@') !== false) {
2622                                 $result['message'] .= DI::l10n()->t('Unable to match @-style Identity Address with a known protocol or email contact.') . EOL;
2623                                 $result['message'] .= DI::l10n()->t('Use mailto: in front of address to force email check.') . EOL;
2624                         }
2625                         return $result;
2626                 }
2627
2628                 if ($protocol === Protocol::OSTATUS && DI::config()->get('system', 'ostatus_disabled')) {
2629                         $result['message'] .= DI::l10n()->t('The profile address specified belongs to a network which has been disabled on this site.') . EOL;
2630                         $ret['notify'] = '';
2631                 }
2632
2633                 if (!$ret['notify']) {
2634                         $result['message'] .= DI::l10n()->t('Limited profile. This person will be unable to receive direct/personal notifications from you.') . EOL;
2635                 }
2636
2637                 $writeable = ((($protocol === Protocol::OSTATUS) && ($ret['notify'])) ? 1 : 0);
2638
2639                 $subhub = (($protocol === Protocol::OSTATUS) ? true : false);
2640
2641                 $hidden = (($protocol === Protocol::MAIL) ? 1 : 0);
2642
2643                 $pending = false;
2644                 if (($protocol == Protocol::ACTIVITYPUB) && isset($ret['manually-approve'])) {
2645                         $pending = (bool)$ret['manually-approve'];
2646                 }
2647
2648                 if (in_array($protocol, [Protocol::MAIL, Protocol::DIASPORA, Protocol::ACTIVITYPUB])) {
2649                         $writeable = 1;
2650                 }
2651
2652                 if (DBA::isResult($contact)) {
2653                         // update contact
2654                         $new_relation = (in_array($contact['rel'], [self::FOLLOWER, self::FRIEND]) ? self::FRIEND : self::SHARING);
2655
2656                         $fields = ['rel' => $new_relation, 'subhub' => $subhub, 'readonly' => false];
2657                         self::update($fields, ['id' => $contact['id']]);
2658                 } else {
2659                         $new_relation = (in_array($protocol, [Protocol::MAIL]) ? self::FRIEND : self::SHARING);
2660
2661                         // create contact record
2662                         self::insert([
2663                                 'uid'     => $uid,
2664                                 'created' => DateTimeFormat::utcNow(),
2665                                 'url'     => $ret['url'],
2666                                 'nurl'    => Strings::normaliseLink($ret['url']),
2667                                 'addr'    => $ret['addr'],
2668                                 'alias'   => $ret['alias'],
2669                                 'batch'   => $ret['batch'],
2670                                 'notify'  => $ret['notify'],
2671                                 'poll'    => $ret['poll'],
2672                                 'poco'    => $ret['poco'],
2673                                 'name'    => $ret['name'],
2674                                 'nick'    => $ret['nick'],
2675                                 'network' => $ret['network'],
2676                                 'baseurl' => $ret['baseurl'],
2677                                 'gsid'    => $ret['gsid'] ?? null,
2678                                 'protocol' => $protocol,
2679                                 'pubkey'  => $ret['pubkey'],
2680                                 'rel'     => $new_relation,
2681                                 'priority'=> $ret['priority'],
2682                                 'writable'=> $writeable,
2683                                 'hidden'  => $hidden,
2684                                 'blocked' => 0,
2685                                 'readonly'=> 0,
2686                                 'pending' => $pending,
2687                                 'subhub'  => $subhub
2688                         ]);
2689                 }
2690
2691                 $contact = DBA::selectFirst('contact', [], ['url' => $ret['url'], 'network' => $ret['network'], 'uid' => $uid]);
2692                 if (!DBA::isResult($contact)) {
2693                         $result['message'] .= DI::l10n()->t('Unable to retrieve contact information.') . EOL;
2694                         return $result;
2695                 }
2696
2697                 $contact_id = $contact['id'];
2698                 $result['cid'] = $contact_id;
2699
2700                 Group::addMember(User::getDefaultGroup($uid), $contact_id);
2701
2702                 // Update the avatar
2703                 self::updateAvatar($contact_id, $ret['photo']);
2704
2705                 // pull feed and consume it, which should subscribe to the hub.
2706                 if ($contact['network'] == Protocol::OSTATUS) {
2707                         Worker::add(PRIORITY_HIGH, 'OnePoll', $contact_id, 'force');
2708                 }
2709
2710                 if ($probed) {
2711                         self::updateFromProbeArray($contact_id, $ret);
2712                 } else {
2713                         Worker::add(PRIORITY_HIGH, 'UpdateContact', $contact_id);
2714                 }
2715
2716                 $result['success'] = Protocol::follow($uid, $contact, $protocol);
2717
2718                 return $result;
2719         }
2720
2721         /**
2722          * @param array  $importer Owner (local user) data
2723          * @param array  $contact  Existing owner-specific contact data we want to expand the relationship with. Optional.
2724          * @param array  $datarray An item-like array with at least the 'author-id' and 'author-url' keys for the contact. Mandatory.
2725          * @param bool   $sharing  True: Contact is now sharing with Owner; False: Contact is now following Owner (default)
2726          * @param string $note     Introduction additional message
2727          * @return bool|null True: follow request is accepted; False: relationship is rejected; Null: relationship is pending
2728          * @throws HTTPException\InternalServerErrorException
2729          * @throws \ImagickException
2730          */
2731         public static function addRelationship(array $importer, array $contact, array $datarray, $sharing = false, $note = '')
2732         {
2733                 // Should always be set
2734                 if (empty($datarray['author-id'])) {
2735                         return false;
2736                 }
2737
2738                 $fields = ['id', 'url', 'name', 'nick', 'avatar', 'photo', 'network', 'blocked'];
2739                 $pub_contact = DBA::selectFirst('contact', $fields, ['id' => $datarray['author-id']]);
2740                 if (!DBA::isResult($pub_contact)) {
2741                         // Should never happen
2742                         return false;
2743                 }
2744
2745                 // Contact is blocked at node-level
2746                 if (self::isBlocked($datarray['author-id'])) {
2747                         return false;
2748                 }
2749
2750                 $url = ($datarray['author-link'] ?? '') ?: $pub_contact['url'];
2751                 $name = $pub_contact['name'];
2752                 $photo = ($pub_contact['avatar'] ?? '') ?: $pub_contact["photo"];
2753                 $nick = $pub_contact['nick'];
2754                 $network = $pub_contact['network'];
2755
2756                 // Ensure that we don't create a new contact when there already is one
2757                 $cid = self::getIdForURL($url, $importer['uid']);
2758                 if (!empty($cid)) {
2759                         $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
2760                 }
2761
2762                 self::clearFollowerFollowingEndpointCache($importer['uid']);
2763
2764                 if (!empty($contact)) {
2765                         if (!empty($contact['pending'])) {
2766                                 Logger::info('Pending contact request already exists.', ['url' => $url, 'uid' => $importer['uid']]);
2767                                 return null;
2768                         }
2769
2770                         // Contact is blocked at user-level
2771                         if (!empty($contact['id']) && !empty($importer['id']) &&
2772                                 Contact\User::isBlocked($contact['id'], $importer['id'])) {
2773                                 return false;
2774                         }
2775
2776                         // Make sure that the existing contact isn't archived
2777                         self::unmarkForArchival($contact);
2778
2779                         if (($contact['rel'] == self::SHARING)
2780                                 || ($sharing && $contact['rel'] == self::FOLLOWER)) {
2781                                 self::update(['rel' => self::FRIEND, 'writable' => true, 'pending' => false],
2782                                                 ['id' => $contact['id'], 'uid' => $importer['uid']]);
2783                         }
2784
2785                         // Ensure to always have the correct network type, independent from the connection request method
2786                         self::updateFromProbe($contact['id']);
2787
2788                         Post\UserNotification::insertNotification($pub_contact['id'], Activity::FOLLOW, $importer['uid']);
2789
2790                         return true;
2791                 } else {
2792                         // send email notification to owner?
2793                         if (DBA::exists('contact', ['nurl' => Strings::normaliseLink($url), 'uid' => $importer['uid'], 'pending' => true])) {
2794                                 Logger::notice('ignoring duplicated connection request from pending contact ' . $url);
2795                                 return null;
2796                         }
2797
2798                         // create contact record
2799                         $contact_id = self::insert([
2800                                 'uid'      => $importer['uid'],
2801                                 'created'  => DateTimeFormat::utcNow(),
2802                                 'url'      => $url,
2803                                 'nurl'     => Strings::normaliseLink($url),
2804                                 'name'     => $name,
2805                                 'nick'     => $nick,
2806                                 'network'  => $network,
2807                                 'rel'      => self::FOLLOWER,
2808                                 'blocked'  => 0,
2809                                 'readonly' => 0,
2810                                 'pending'  => 1,
2811                                 'writable' => 1,
2812                         ]);
2813
2814                         // Ensure to always have the correct network type, independent from the connection request method
2815                         self::updateFromProbe($contact_id);
2816
2817                         self::updateAvatar($contact_id, $photo, true);
2818
2819                         Post\UserNotification::insertNotification($pub_contact['id'], Activity::FOLLOW, $importer['uid']);
2820
2821                         $contact_record = DBA::selectFirst('contact', ['id', 'network', 'name', 'url', 'photo'], ['id' => $contact_id]);
2822
2823                         /// @TODO Encapsulate this into a function/method
2824                         $fields = ['uid', 'username', 'email', 'page-flags', 'notify-flags', 'language'];
2825                         $user = DBA::selectFirst('user', $fields, ['uid' => $importer['uid']]);
2826                         if (DBA::isResult($user) && !in_array($user['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_FREELOVE, User::PAGE_FLAGS_COMMUNITY])) {
2827                                 // create notification
2828                                 if (is_array($contact_record)) {
2829                                         $intro = DI::introFactory()->createNew(
2830                                                 $importer['uid'],
2831                                                 $contact_record['id'],
2832                                                 $note
2833                                         );
2834                                         DI::intro()->save($intro);
2835                                 }
2836
2837                                 Group::addMember(User::getDefaultGroup($importer['uid']), $contact_record['id']);
2838
2839                                 if (($user['notify-flags'] & Notification\Type::INTRO) && $user['page-flags'] == User::PAGE_FLAGS_NORMAL) {
2840                                         DI::notify()->createFromArray([
2841                                                 'type'  => Notification\Type::INTRO,
2842                                                 'otype' => Notification\ObjectType::INTRO,
2843                                                 'verb'  => ($sharing ? Activity::FRIEND : Activity::FOLLOW),
2844                                                 'uid'   => $user['uid'],
2845                                                 'cid'   => $contact_record['id'],
2846                                                 'link'  => DI::baseUrl() . '/notifications/intros',
2847                                         ]);
2848                                 }
2849                         } elseif (DBA::isResult($user) && in_array($user['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_FREELOVE, User::PAGE_FLAGS_COMMUNITY])) {
2850                                 if (($user['page-flags'] == User::PAGE_FLAGS_FREELOVE) && ($network != Protocol::DIASPORA)) {
2851                                         self::createFromProbeForUser($importer['uid'], $url, $network);
2852                                 }
2853
2854                                 $condition = ['uid' => $importer['uid'], 'url' => $url, 'pending' => true];
2855                                 $fields = ['pending' => false];
2856                                 if ($user['page-flags'] == User::PAGE_FLAGS_FREELOVE) {
2857                                         $fields['rel'] = self::FRIEND;
2858                                 }
2859
2860                                 self::update($fields, $condition);
2861
2862                                 return true;
2863                         }
2864                 }
2865
2866                 return null;
2867         }
2868
2869         /**
2870          * Update the local relationship when a local user loses a follower
2871          *
2872          * @param array $contact User-specific contact (uid != 0) array
2873          * @throws HTTPException\InternalServerErrorException
2874          * @throws \ImagickException
2875          */
2876         public static function removeFollower(array $contact)
2877         {
2878                 if (in_array($contact['rel'] ?? [], [self::FRIEND, self::SHARING])) {
2879                         self::update(['rel' => self::SHARING], ['id' => $contact['id']]);
2880                 } elseif (!empty($contact['id'])) {
2881                         self::remove($contact['id']);
2882                 } else {
2883                         DI::logger()->info('Couldn\'t remove follower because of invalid contact array', ['contact' => $contact, 'callstack' => System::callstack()]);
2884                         return;
2885                 }
2886
2887                 self::clearFollowerFollowingEndpointCache($contact['uid']);
2888
2889                 $cdata = self::getPublicAndUserContactID($contact['id'], $contact['uid']);
2890
2891                 DI::notification()->deleteForUserByVerb($contact['uid'], Activity::FOLLOW, ['actor-id' => $cdata['public']]);
2892         }
2893
2894         /**
2895          * Update the local relationship when a local user unfollow a contact.
2896          * Removes the contact for sharing-only protocols (feed and mail).
2897          *
2898          * @param array $contact User-specific contact (uid != 0) array
2899          * @throws HTTPException\InternalServerErrorException
2900          */
2901         public static function removeSharer(array $contact)
2902         {
2903                 self::clearFollowerFollowingEndpointCache($contact['uid']);
2904
2905                 if ($contact['rel'] == self::SHARING || in_array($contact['network'], [Protocol::FEED, Protocol::MAIL])) {
2906                         self::remove($contact['id']);
2907                 } else {
2908                         self::update(['rel' => self::FOLLOWER], ['id' => $contact['id']]);
2909                 }
2910         }
2911
2912         /**
2913          * Create a birthday event.
2914          *
2915          * Update the year and the birthday.
2916          */
2917         public static function updateBirthdays()
2918         {
2919                 $condition = [
2920                         '`bd` > ?
2921                         AND (`contact`.`rel` = ? OR `contact`.`rel` = ?)
2922                         AND NOT `contact`.`pending`
2923                         AND NOT `contact`.`hidden`
2924                         AND NOT `contact`.`blocked`
2925                         AND NOT `contact`.`archive`
2926                         AND NOT `contact`.`deleted`',
2927                         DBA::NULL_DATE,
2928                         self::SHARING,
2929                         self::FRIEND
2930                 ];
2931
2932                 $contacts = DBA::select('contact', ['id', 'uid', 'name', 'url', 'bd'], $condition);
2933
2934                 while ($contact = DBA::fetch($contacts)) {
2935                         Logger::notice('update_contact_birthday: ' . $contact['bd']);
2936
2937                         $nextbd = DateTimeFormat::utcNow('Y') . substr($contact['bd'], 4);
2938
2939                         if (Event::createBirthday($contact, $nextbd)) {
2940                                 // update bdyear
2941                                 DBA::update(
2942                                         'contact',
2943                                         ['bdyear' => substr($nextbd, 0, 4), 'bd' => $nextbd],
2944                                         ['id' => $contact['id']]
2945                                 );
2946                         }
2947                 }
2948                 DBA::close($contacts);
2949         }
2950
2951         /**
2952          * Remove the unavailable contact ids from the provided list
2953          *
2954          * @param array $contact_ids Contact id list
2955          * @return array
2956          * @throws \Exception
2957          */
2958         public static function pruneUnavailable(array $contact_ids)
2959         {
2960                 if (empty($contact_ids)) {
2961                         return [];
2962                 }
2963
2964                 $contacts = self::selectToArray(['id'], [
2965                         'id'      => $contact_ids,
2966                         'blocked' => false,
2967                         'pending' => false,
2968                         'archive' => false,
2969                 ]);
2970
2971                 return array_column($contacts, 'id');
2972         }
2973
2974         /**
2975          * Returns a magic link to authenticate remote visitors
2976          *
2977          * @todo  check if the return is either a fully qualified URL or a relative path to Friendica basedir
2978          *
2979          * @param string $contact_url The address of the target contact profile
2980          * @param string $url         An url that we will be redirected to after the authentication
2981          *
2982          * @return string with "redir" link
2983          * @throws HTTPException\InternalServerErrorException
2984          * @throws \ImagickException
2985          */
2986         public static function magicLink($contact_url, $url = '')
2987         {
2988                 if (!Session::isAuthenticated()) {
2989                         return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
2990                 }
2991
2992                 $contact = self::getByURL($contact_url, false);
2993                 if (empty($contact)) {
2994                         return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
2995                 }
2996
2997                 // Prevents endless loop in case only a non-public contact exists for the contact URL
2998                 unset($contact['uid']);
2999
3000                 return self::magicLinkByContact($contact, $url ?: $contact_url);
3001         }
3002
3003         /**
3004          * Returns a magic link to authenticate remote visitors
3005          *
3006          * @param integer $cid The contact id of the target contact profile
3007          * @param string  $url An url that we will be redirected to after the authentication
3008          *
3009          * @return string with "redir" link
3010          * @throws HTTPException\InternalServerErrorException
3011          * @throws \ImagickException
3012          */
3013         public static function magicLinkById($cid, $url = '')
3014         {
3015                 $contact = DBA::selectFirst('contact', ['id', 'network', 'url', 'uid'], ['id' => $cid]);
3016
3017                 return self::magicLinkByContact($contact, $url);
3018         }
3019
3020         /**
3021          * Returns a magic link to authenticate remote visitors
3022          *
3023          * @param array  $contact The contact array with "uid", "network" and "url"
3024          * @param string $url     An url that we will be redirected to after the authentication
3025          *
3026          * @return string with "redir" link
3027          * @throws HTTPException\InternalServerErrorException
3028          * @throws \ImagickException
3029          */
3030         public static function magicLinkByContact($contact, $url = '')
3031         {
3032                 $destination = $url ?: $contact['url']; // Equivalent to ($url != '') ? $url : $contact['url'];
3033
3034                 if (!Session::isAuthenticated()) {
3035                         return $destination;
3036                 }
3037
3038                 // Only redirections to the same host do make sense
3039                 if (($url != '') && (parse_url($url, PHP_URL_HOST) != parse_url($contact['url'], PHP_URL_HOST))) {
3040                         return $url;
3041                 }
3042
3043                 if (DI::pConfig()->get(local_user(), 'system', 'stay_local') && ($url == '')) {
3044                         return 'contact/' . $contact['id'] . '/conversations';
3045                 }
3046
3047                 if (!empty($contact['network']) && $contact['network'] != Protocol::DFRN) {
3048                         return $destination;
3049                 }
3050
3051                 if (empty($contact['id'])) {
3052                         return $destination;
3053                 }
3054
3055                 $redirect = 'redir/' . $contact['id'];
3056
3057                 if (($url != '') && !Strings::compareLink($contact['url'], $url)) {
3058                         $redirect .= '?url=' . $url;
3059                 }
3060
3061                 return $redirect;
3062         }
3063
3064         /**
3065          * Is the contact a forum?
3066          *
3067          * @param integer $contactid ID of the contact
3068          *
3069          * @return boolean "true" if it is a forum
3070          */
3071         public static function isForum($contactid)
3072         {
3073                 $fields = ['contact-type'];
3074                 $condition = ['id' => $contactid];
3075                 $contact = DBA::selectFirst('contact', $fields, $condition);
3076                 if (!DBA::isResult($contact)) {
3077                         return false;
3078                 }
3079
3080                 // Is it a forum?
3081                 return ($contact['contact-type'] == self::TYPE_COMMUNITY);
3082         }
3083
3084         /**
3085          * Can the remote contact receive private messages?
3086          *
3087          * @param array $contact
3088          * @return bool
3089          */
3090         public static function canReceivePrivateMessages(array $contact)
3091         {
3092                 $protocol = $contact['network'] ?? $contact['protocol'] ?? Protocol::PHANTOM;
3093                 $self = $contact['self'] ?? false;
3094
3095                 return in_array($protocol, [Protocol::DFRN, Protocol::DIASPORA, Protocol::ACTIVITYPUB]) && !$self;
3096         }
3097
3098         /**
3099          * Search contact table by nick or name
3100          *
3101          * @param string $search Name or nick
3102          * @param string $mode   Search mode (e.g. "community")
3103          * @param int    $uid    User ID
3104          *
3105          * @return array with search results
3106          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3107          */
3108         public static function searchByName(string $search, string $mode = '', int $uid = 0)
3109         {
3110                 if (empty($search)) {
3111                         return [];
3112                 }
3113
3114                 // check supported networks
3115                 $networks = [Protocol::DFRN, Protocol::ACTIVITYPUB];
3116                 if (DI::config()->get('system', 'diaspora_enabled')) {
3117                         $networks[] = Protocol::DIASPORA;
3118                 }
3119
3120                 if (!DI::config()->get('system', 'ostatus_disabled')) {
3121                         $networks[] = Protocol::OSTATUS;
3122                 }
3123
3124                 $condition = ['network' => $networks, 'failed' => false, 'deleted' => false, 'uid' => $uid];
3125
3126                 if ($uid == 0) {
3127                         $condition['blocked'] = false;
3128                 }
3129
3130                 // check if we search only communities or every contact
3131                 if ($mode === 'community') {
3132                         $condition['contact-type'] = self::TYPE_COMMUNITY;
3133                 }
3134
3135                 $search .= '%';
3136
3137                 $condition = DBA::mergeConditions($condition,
3138                         ["(NOT `unsearchable` OR `nurl` IN (SELECT `nurl` FROM `owner-view` WHERE `publish` OR `net-publish`))
3139                         AND (`addr` LIKE ? OR `name` LIKE ? OR `nick` LIKE ?)", $search, $search, $search]);
3140
3141                 $contacts = self::selectToArray([], $condition);
3142                 return $contacts;
3143         }
3144
3145         /**
3146          * Add public contacts from an array
3147          *
3148          * @param array $urls
3149          * @return array result "count", "added" and "updated"
3150          */
3151         public static function addByUrls(array $urls)
3152         {
3153                 $added = 0;
3154                 $updated = 0;
3155                 $unchanged = 0;
3156                 $count = 0;
3157
3158                 foreach ($urls as $url) {
3159                         if (empty($url) || !is_string($url)) {
3160                                 continue;
3161                         }
3162                         $contact = self::getByURL($url, false, ['id', 'updated']);
3163                         if (empty($contact['id'])) {
3164                                 Worker::add(PRIORITY_LOW, 'AddContact', 0, $url);
3165                                 ++$added;
3166                         } elseif ($contact['updated'] < DateTimeFormat::utc('now -7 days')) {
3167                                 Worker::add(PRIORITY_LOW, 'UpdateContact', $contact['id']);
3168                                 ++$updated;
3169                         } else {
3170                                 ++$unchanged;
3171                         }
3172                         ++$count;
3173                 }
3174
3175                 return ['count' => $count, 'added' => $added, 'updated' => $updated, 'unchanged' => $unchanged];
3176         }
3177
3178         /**
3179          * Returns a random, global contact array of the current node
3180          *
3181          * @return array The profile array
3182          * @throws Exception
3183          */
3184         public static function getRandomContact()
3185         {
3186                 $contact = DBA::selectFirst('contact', ['id', 'network', 'url', 'uid'], [
3187                         "`uid` = ? AND `network` = ? AND NOT `failed` AND `last-item` > ?",
3188                         0, Protocol::DFRN, DateTimeFormat::utc('now - 1 month'),
3189                 ], ['order' => ['RAND()']]);
3190
3191                 if (DBA::isResult($contact)) {
3192                         return $contact;
3193                 }
3194
3195                 return [];
3196         }
3197 }