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