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