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