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