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