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