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