]> git.mxchange.org Git - friendica.git/blob - src/Model/APContact.php
Merge pull request #12843 from annando/fetchraw-attachments
[friendica.git] / src / Model / APContact.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2023, the Friendica project
4  *
5  * @license GNU AGPL version 3 or any later version
6  *
7  * This program is free software: you can redistribute it and/or modify
8  * it under the terms of the GNU Affero General Public License as
9  * published by the Free Software Foundation, either version 3 of the
10  * License, or (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU Affero General Public License for more details.
16  *
17  * You should have received a copy of the GNU Affero General Public License
18  * along with this program.  If not, see <https://www.gnu.org/licenses/>.
19  *
20  */
21
22 namespace Friendica\Model;
23
24 use Friendica\Content\Text\HTML;
25 use Friendica\Core\Cache\Enum\Duration;
26 use Friendica\Core\Logger;
27 use Friendica\Core\Protocol;
28 use Friendica\Core\System;
29 use Friendica\Database\DBA;
30 use Friendica\DI;
31 use Friendica\Model\Item;
32 use Friendica\Network\HTTPClient\Client\HttpClientAccept;
33 use Friendica\Network\HTTPException;
34 use Friendica\Network\Probe;
35 use Friendica\Protocol\ActivityNamespace;
36 use Friendica\Protocol\ActivityPub;
37 use Friendica\Protocol\ActivityPub\Transmitter;
38 use Friendica\Util\Crypto;
39 use Friendica\Util\DateTimeFormat;
40 use Friendica\Util\HTTPSignature;
41 use Friendica\Util\JsonLD;
42 use Friendica\Util\Network;
43 use GuzzleHttp\Psr7\Uri;
44
45 class APContact
46 {
47         /**
48          * Fetch webfinger data
49          *
50          * @param string $addr Address
51          * @return array webfinger data
52          */
53         private static function fetchWebfingerData(string $addr): array
54         {
55                 $addr_parts = explode('@', $addr);
56                 if (count($addr_parts) != 2) {
57                         return [];
58                 }
59
60                 if (Contact::isLocal($addr) && ($local_uid = User::getIdForURL($addr)) && ($local_owner = User::getOwnerDataById($local_uid))) {
61                         $data = [
62                                 'addr'      => $local_owner['addr'],
63                                 'baseurl'   => $local_owner['baseurl'],
64                                 'url'       => $local_owner['url'],
65                                 'subscribe' => $local_owner['baseurl'] . '/contact/follow?url={uri}'];
66
67                         if (!empty($local_owner['alias']) && ($local_owner['url'] != $local_owner['alias'])) {
68                                 $data['alias'] = $local_owner['alias'];
69                         }
70
71                         return $data;
72                 }
73
74                 $webfinger = Probe::getWebfingerArray($addr);
75                 if (empty($webfinger['webfinger']['links'])) {
76                         return [];
77                 }
78
79                 $data['baseurl'] = $webfinger['baseurl'];
80
81                 foreach ($webfinger['webfinger']['links'] as $link) {
82                         if (empty($link['rel'])) {
83                                 continue;
84                         }
85
86                         if (!empty($link['template']) && ($link['rel'] == ActivityNamespace::OSTATUSSUB)) {
87                                 $data['subscribe'] = $link['template'];
88                         }
89
90                         if (!empty($link['href']) && !empty($link['type']) && ($link['rel'] == 'self') && ($link['type'] == 'application/activity+json')) {
91                                 $data['url'] = $link['href'];
92                         }
93
94                         if (!empty($link['href']) && !empty($link['type']) && ($link['rel'] == 'http://webfinger.net/rel/profile-page') && ($link['type'] == 'text/html')) {
95                                 $data['alias'] = $link['href'];
96                         }
97                 }
98
99                 if (!empty($data['url']) && !empty($data['alias']) && ($data['url'] == $data['alias'])) {
100                         unset($data['alias']);
101                 }
102
103                 return $data;
104         }
105
106         /**
107          * Fetches a profile from a given url
108          *
109          * @param string  $url    profile url
110          * @param boolean $update true = always update, false = never update, null = update when not found or outdated
111          * @return array profile array
112          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
113          * @throws \ImagickException
114          * @todo Rewrite parameter $update to avoid true|false|null (boolean is binary, null adds a third case)
115          */
116         public static function getByURL(string $url, $update = null): array
117         {
118                 if (empty($url) || Network::isUrlBlocked($url)) {
119                         Logger::info('Domain is blocked', ['url' => $url]);
120                         return [];
121                 }
122
123                 $fetched_contact = [];
124
125                 if (empty($update)) {
126                         if (is_null($update)) {
127                                 $ref_update = DateTimeFormat::utc('now - 1 month');
128                         } else {
129                                 $ref_update = DBA::NULL_DATETIME;
130                         }
131
132                         $apcontact = DBA::selectFirst('apcontact', [], ['url' => $url]);
133                         if (!DBA::isResult($apcontact)) {
134                                 $apcontact = DBA::selectFirst('apcontact', [], ['alias' => $url]);
135                         }
136
137                         if (!DBA::isResult($apcontact)) {
138                                 $apcontact = DBA::selectFirst('apcontact', [], ['addr' => $url]);
139                         }
140
141                         if (DBA::isResult($apcontact) && ($apcontact['updated'] > $ref_update) && !empty($apcontact['pubkey']) && !empty($apcontact['uri-id'])) {
142                                 return $apcontact;
143                         }
144
145                         if (!is_null($update)) {
146                                 return DBA::isResult($apcontact) ? $apcontact : [];
147                         }
148
149                         if (DBA::isResult($apcontact)) {
150                                 $fetched_contact = $apcontact;
151                         }
152                 }
153
154                 $apcontact = [];
155
156                 $webfinger = empty(parse_url($url, PHP_URL_SCHEME));
157                 if ($webfinger) {
158                         $apcontact = self::fetchWebfingerData($url);
159                         if (empty($apcontact['url'])) {
160                                 return $fetched_contact;
161                         }
162                         $url = $apcontact['url'];
163                 } elseif (empty(parse_url($url, PHP_URL_PATH))) {
164                         $apcontact['baseurl'] = $url;
165                 }
166
167                 // Detect multiple fast repeating request to the same address
168                 // See https://github.com/friendica/friendica/issues/9303
169                 $cachekey = 'apcontact:' . ItemURI::getIdByURI($url);
170                 $result = DI::cache()->get($cachekey);
171                 if (!is_null($result)) {
172                         Logger::info('Multiple requests for the address', ['url' => $url, 'update' => $update, 'callstack' => System::callstack(20), 'result' => $result]);
173                         if (!empty($fetched_contact)) {
174                                 return $fetched_contact;
175                         }
176                 } else {
177                         DI::cache()->set($cachekey, System::callstack(20), Duration::FIVE_MINUTES);
178                 }
179
180                 if (Network::isLocalLink($url) && ($local_uid = User::getIdForURL($url))) {
181                         try {
182                                 $data = Transmitter::getProfile($local_uid);
183                                 $local_owner = User::getOwnerDataById($local_uid);
184                         } catch(HTTPException\NotFoundException $e) {
185                                 $data = null;
186                         }
187                 }
188
189                 if (empty($data)) {
190                         $local_owner = [];
191
192                         try {
193                                 $curlResult = HTTPSignature::fetchRaw($url);
194                                 $failed = empty($curlResult) || empty($curlResult->getBody()) ||
195                                         (!$curlResult->isSuccess() && ($curlResult->getReturnCode() != 410));
196         
197                                 if (!$failed) {
198                                         $data = json_decode($curlResult->getBody(), true);
199                                         $failed = empty($data) || !is_array($data);
200                                 }
201
202                                 if (!$failed && ($curlResult->getReturnCode() == 410)) {
203                                         $data = ['@context' => ActivityPub::CONTEXT, 'id' => $url, 'type' => 'Tombstone'];
204                                 }
205                         } catch (\Exception $exception) {
206                                 Logger::notice('Error fetching url', ['url' => $url, 'exception' => $exception]);
207                                 $failed = true;
208                         }
209
210                         if ($failed) {
211                                 self::markForArchival($fetched_contact ?: []);
212                                 return $fetched_contact;
213                         }
214                 }
215
216                 $compacted = JsonLD::compact($data);
217                 if (empty($compacted['@id'])) {
218                         return $fetched_contact;
219                 }
220
221                 $apcontact['url'] = $compacted['@id'];
222                 $apcontact['uuid'] = JsonLD::fetchElement($compacted, 'diaspora:guid', '@value');
223                 $apcontact['type'] = str_replace('as:', '', JsonLD::fetchElement($compacted, '@type'));
224                 $apcontact['following'] = JsonLD::fetchElement($compacted, 'as:following', '@id');
225                 $apcontact['followers'] = JsonLD::fetchElement($compacted, 'as:followers', '@id');
226                 $apcontact['inbox'] = (JsonLD::fetchElement($compacted, 'ldp:inbox', '@id') ?? '');
227                 $apcontact['outbox'] = JsonLD::fetchElement($compacted, 'as:outbox', '@id');
228
229                 $apcontact['sharedinbox'] = '';
230                 if (!empty($compacted['as:endpoints'])) {
231                         $apcontact['sharedinbox'] = (JsonLD::fetchElement($compacted['as:endpoints'], 'as:sharedInbox', '@id') ?? '');
232                 }
233
234                 $apcontact['featured']      = JsonLD::fetchElement($compacted, 'toot:featured', '@id');
235                 $apcontact['featured-tags'] = JsonLD::fetchElement($compacted, 'toot:featuredTags', '@id');
236
237                 $apcontact['nick'] = JsonLD::fetchElement($compacted, 'as:preferredUsername', '@value') ?? '';
238                 $apcontact['name'] = JsonLD::fetchElement($compacted, 'as:name', '@value');
239
240                 if (empty($apcontact['name'])) {
241                         $apcontact['name'] = $apcontact['nick'];
242                 }
243
244                 $apcontact['about'] = HTML::toBBCode(JsonLD::fetchElement($compacted, 'as:summary', '@value') ?? '');
245
246                 $ims = JsonLD::fetchElementArray($compacted, 'vcard:hasInstantMessage');
247
248                 if (!empty($ims)) {
249                         foreach ($ims as $link) {
250                                 if (substr($link, 0, 5) == 'xmpp:') {
251                                         $apcontact['xmpp'] = substr($link, 5);
252                                 }
253                                 if (substr($link, 0, 7) == 'matrix:') {
254                                         $apcontact['matrix'] = substr($link, 7);
255                                 }
256                         }
257                 }
258
259                 $apcontact['photo'] = JsonLD::fetchElement($compacted, 'as:icon', '@id');
260                 if (is_array($apcontact['photo']) || !empty($compacted['as:icon']['as:url']['@id'])) {
261                         $apcontact['photo'] = JsonLD::fetchElement($compacted['as:icon'], 'as:url', '@id');
262                 }
263
264                 $apcontact['header'] = JsonLD::fetchElement($compacted, 'as:image', '@id');
265                 if (is_array($apcontact['header']) || !empty($compacted['as:image']['as:url']['@id'])) {
266                         $apcontact['header'] = JsonLD::fetchElement($compacted['as:image'], 'as:url', '@id');
267                 }
268
269                 if (empty($apcontact['alias'])) {
270                         $apcontact['alias'] = JsonLD::fetchElement($compacted, 'as:url', '@id');
271                         if (is_array($apcontact['alias'])) {
272                                 $apcontact['alias'] = JsonLD::fetchElement($compacted['as:url'], 'as:href', '@id');
273                         }
274                 }
275
276                 // Quit if none of the basic values are set
277                 if (empty($apcontact['url']) || empty($apcontact['type']) || (($apcontact['type'] != 'Tombstone') && empty($apcontact['inbox']))) {
278                         return $fetched_contact;
279                 } elseif ($apcontact['type'] == 'Tombstone') {
280                         // The "inbox" field must have a content
281                         $apcontact['inbox'] = '';
282                 }
283
284                 // Quit if this doesn't seem to be an account at all
285                 if (!in_array($apcontact['type'], ActivityPub::ACCOUNT_TYPES)) {
286                         return $fetched_contact;
287                 }
288
289                 if (empty($apcontact['addr'])) {
290                         try {
291                                 $apcontact['addr'] = $apcontact['nick'] . '@' . (new Uri($apcontact['url']))->getAuthority();
292                         } catch (\Throwable $e) {
293                                 Logger::warning('Unable to coerce APContact URL into a UriInterface object', ['url' => $apcontact['url'], 'error' => $e->getMessage()]);
294                                 $apcontact['addr'] = '';
295                         }
296                 }
297
298                 $apcontact['pubkey'] = null;
299                 if (!empty($compacted['w3id:publicKey'])) {
300                         $apcontact['pubkey'] = trim(JsonLD::fetchElement($compacted['w3id:publicKey'], 'w3id:publicKeyPem', '@value') ?? '');
301                         if (strpos($apcontact['pubkey'], 'RSA ') !== false) {
302                                 $apcontact['pubkey'] = Crypto::rsaToPem($apcontact['pubkey']);
303                         }
304                 }
305
306                 $apcontact['manually-approve'] = (int)JsonLD::fetchElement($compacted, 'as:manuallyApprovesFollowers');
307
308                 $apcontact['suspended'] = (int)JsonLD::fetchElement($compacted, 'toot:suspended');
309
310                 if (!empty($compacted['as:generator'])) {
311                         $apcontact['baseurl'] = JsonLD::fetchElement($compacted['as:generator'], 'as:url', '@id');
312                         $apcontact['generator'] = JsonLD::fetchElement($compacted['as:generator'], 'as:name', '@value');
313                 }
314
315                 if (!empty($apcontact['following'])) {
316                         if (!empty($local_owner)) {
317                                 $following = ActivityPub\Transmitter::getContacts($local_owner, [Contact::SHARING, Contact::FRIEND], 'following');
318                         } else {
319                                 $following = ActivityPub::fetchContent($apcontact['following']);
320                         }
321                         if (!empty($following['totalItems'])) {
322                                 // Mastodon seriously allows for this condition?
323                                 // Jul 14 2021 - See https://mastodon.social/@BLUW for a negative following count
324                                 if ($following['totalItems'] < 0) {
325                                         $following['totalItems'] = 0;
326                                 }
327                                 $apcontact['following_count'] = $following['totalItems'];
328                         }
329                 }
330
331                 if (!empty($apcontact['followers'])) {
332                         if (!empty($local_owner)) {
333                                 $followers = ActivityPub\Transmitter::getContacts($local_owner, [Contact::FOLLOWER, Contact::FRIEND], 'followers');
334                         } else {
335                                 $followers = ActivityPub::fetchContent($apcontact['followers']);
336                         }
337                         if (!empty($followers['totalItems'])) {
338                                 // Mastodon seriously allows for this condition?
339                                 // Jul 14 2021 - See https://mastodon.online/@goes11 for a negative followers count
340                                 if ($followers['totalItems'] < 0) {
341                                         $followers['totalItems'] = 0;
342                                 }
343                                 $apcontact['followers_count'] = $followers['totalItems'];
344                         }
345                 }
346
347                 if (!empty($apcontact['outbox'])) {
348                         if (!empty($local_owner)) {
349                                 $statuses_count = self::getStatusesCount($local_owner);
350                         } else {
351                                 $outbox = ActivityPub::fetchContent($apcontact['outbox']);
352                                 $statuses_count = $outbox['totalItems'] ?? 0;
353                         }
354                         if (!empty($statuses_count)) {
355                                 // Mastodon seriously allows for this condition?
356                                 // Jul 20 2021 - See https://chaos.social/@m11 for a negative posts count
357                                 if ($statuses_count < 0) {
358                                         $statuses_count = 0;
359                                 }
360                                 $apcontact['statuses_count'] = $statuses_count;
361                         }
362                 }
363
364                 $apcontact['discoverable'] = JsonLD::fetchElement($compacted, 'toot:discoverable', '@value');
365
366                 if (!empty($apcontact['photo'])) {
367                         $apcontact['photo'] = Network::addBasePath($apcontact['photo'], $apcontact['url']);
368
369                         if (!Network::isValidHttpUrl($apcontact['photo'])) {
370                                 Logger::warning('Invalid URL for photo', ['url' => $apcontact['url'], 'photo' => $apcontact['photo']]);
371                                 $apcontact['photo'] = '';
372                         }
373                 }
374
375                 // When the photo is too large, try to shorten it by removing parts
376                 if (strlen($apcontact['photo'] ?? '') > 255) {
377                         $parts = parse_url($apcontact['photo']);
378                         unset($parts['fragment']);
379                         $apcontact['photo'] = (string)Uri::fromParts($parts);
380
381                         if (strlen($apcontact['photo']) > 255) {
382                                 unset($parts['query']);
383                                 $apcontact['photo'] = (string)Uri::fromParts($parts);
384                         }
385
386                         if (strlen($apcontact['photo']) > 255) {
387                                 $apcontact['photo'] = substr($apcontact['photo'], 0, 255);
388                         }
389                 }
390
391                 if (!$webfinger && !empty($apcontact['addr'])) {
392                         $data = self::fetchWebfingerData($apcontact['addr']);
393                         if (!empty($data)) {
394                                 $apcontact['baseurl'] = $data['baseurl'];
395
396                                 if (empty($apcontact['alias']) && !empty($data['alias'])) {
397                                         $apcontact['alias'] = $data['alias'];
398                                 }
399                                 if (!empty($data['subscribe'])) {
400                                         $apcontact['subscribe'] = $data['subscribe'];
401                                 }
402                         } else {
403                                 $apcontact['addr'] = null;
404                         }
405                 }
406
407                 if (empty($apcontact['baseurl'])) {
408                         $apcontact['baseurl'] = null;
409                 }
410
411                 if (empty($apcontact['subscribe'])) {
412                         $apcontact['subscribe'] = null;
413                 }
414
415                 if (!empty($apcontact['baseurl']) && empty($fetched_contact['gsid'])) {
416                         $apcontact['gsid'] = GServer::getID($apcontact['baseurl']);
417                 } elseif (!empty($fetched_contact['gsid'])) {
418                         $apcontact['gsid'] = $fetched_contact['gsid'];
419                 } else {
420                         $apcontact['gsid'] = null;
421                 }
422
423                 self::unarchiveInbox($apcontact['inbox'], false, $apcontact['gsid']);
424
425                 if (!empty($apcontact['sharedinbox'])) {
426                         self::unarchiveInbox($apcontact['sharedinbox'], true, $apcontact['gsid']);
427                 }
428
429                 if ($apcontact['url'] == $apcontact['alias']) {
430                         $apcontact['alias'] = null;
431                 }
432
433                 if (empty($apcontact['uuid'])) {
434                         $apcontact['uri-id'] = ItemURI::getIdByURI($apcontact['url']);
435                 } else {
436                         $apcontact['uri-id'] = ItemURI::insert(['uri' => $apcontact['url'], 'guid' => $apcontact['uuid']]);
437                 }
438
439                 foreach (APContact\Endpoint::ENDPOINT_NAMES as $type => $name) {
440                         $value = JsonLD::fetchElement($compacted, $name, '@id');
441                         if (empty($value)) {
442                                 continue;
443                         }
444                         APContact\Endpoint::update($apcontact['uri-id'], $type, $value);
445                 }
446
447                 if (!empty($compacted['as:endpoints'])) {
448                         foreach ($compacted['as:endpoints'] as $name => $endpoint) {
449                                 if (empty($endpoint['@id']) || !is_string($endpoint['@id'])) {
450                                         continue;
451                                 }
452
453                                 if (in_array($name, APContact\Endpoint::ENDPOINT_NAMES)) {
454                                         $key = array_search($name, APContact\Endpoint::ENDPOINT_NAMES);
455                                         APContact\Endpoint::update($apcontact['uri-id'], $key, $endpoint['@id']);
456                                         Logger::debug('Store endpoint', ['key' => $key, 'name' => $name, 'endpoint' => $endpoint['@id']]);
457                                 } elseif (!in_array($name, ['as:sharedInbox', 'as:uploadMedia', 'as:oauthTokenEndpoint', 'as:oauthAuthorizationEndpoint', 'litepub:oauthRegistrationEndpoint'])) {
458                                         Logger::debug('Unknown endpoint', ['name' => $name, 'endpoint' => $endpoint['@id']]);
459                                 }
460                         }
461                 }
462
463                 $apcontact['updated'] = DateTimeFormat::utcNow();
464
465                 // We delete the old entry when the URL is changed
466                 if ($url != $apcontact['url']) {
467                         Logger::info('Delete changed profile url', ['old' => $url, 'new' => $apcontact['url']]);
468                         DBA::delete('apcontact', ['url' => $url]);
469                 }
470
471                 // Limit the length on incoming fields
472                 $apcontact = DI::dbaDefinition()->truncateFieldsForTable('apcontact', $apcontact);
473
474                 if (DBA::exists('apcontact', ['url' => $apcontact['url']])) {
475                         DBA::update('apcontact', $apcontact, ['url' => $apcontact['url']]);
476                 } else {
477                         DBA::replace('apcontact', $apcontact);
478                 }
479
480                 Logger::info('Updated profile', ['url' => $url]);
481
482                 return DBA::selectFirst('apcontact', [], ['url' => $apcontact['url']]) ?: [];
483         }
484
485         /**
486          * Fetch the number of statuses for the given owner
487          *
488          * @param array $owner
489          *
490          * @return integer
491          */
492         private static function getStatusesCount(array $owner): int
493         {
494                 $condition = [
495                         'private'        => [Item::PUBLIC, Item::UNLISTED],
496                         'author-id'      => Contact::getIdForURL($owner['url'], 0, false),
497                         'gravity'        => [Item::GRAVITY_PARENT, Item::GRAVITY_COMMENT],
498                         'network'        => Protocol::DFRN,
499                         'parent-network' => Protocol::FEDERATED,
500                         'deleted'        => false,
501                         'visible'        => true,
502                 ];
503
504                 $count = Post::countPosts($condition);
505
506                 return $count;
507         }
508
509         /**
510          * Mark the given AP Contact as "to archive"
511          *
512          * @param array $apcontact
513          * @return void
514          */
515         public static function markForArchival(array $apcontact)
516         {
517                 if (!empty($apcontact['inbox'])) {
518                         Logger::info('Set inbox status to failure', ['inbox' => $apcontact['inbox']]);
519                         HTTPSignature::setInboxStatus($apcontact['inbox'], false, false, $apcontact['gsid']);
520                 }
521
522                 if (!empty($apcontact['sharedinbox'])) {
523                         // Check if there are any available inboxes
524                         $available = DBA::exists('apcontact', ["`sharedinbox` = ? AnD `inbox` IN (SELECT `url` FROM `inbox-status` WHERE `success` > `failure`)",
525                                 $apcontact['sharedinbox']]);
526                         if (!$available) {
527                                 // If all known personal inboxes are failing then set their shared inbox to failure as well
528                                 Logger::info('Set shared inbox status to failure', ['sharedinbox' => $apcontact['sharedinbox']]);
529                                 HTTPSignature::setInboxStatus($apcontact['sharedinbox'], false, true, $apcontact['gsid']);
530                         }
531                 }
532         }
533
534         /**
535          * Unmark the given AP Contact as "to archive"
536          *
537          * @param array $apcontact
538          * @return void
539          */
540         public static function unmarkForArchival(array $apcontact)
541         {
542                 if (!empty($apcontact['inbox'])) {
543                         Logger::info('Set inbox status to success', ['inbox' => $apcontact['inbox']]);
544                         HTTPSignature::setInboxStatus($apcontact['inbox'], true, false, $apcontact['gsid']);
545                 }
546                 if (!empty($apcontact['sharedinbox'])) {
547                         Logger::info('Set shared inbox status to success', ['sharedinbox' => $apcontact['sharedinbox']]);
548                         HTTPSignature::setInboxStatus($apcontact['sharedinbox'], true, true, $apcontact['gsid']);
549                 }
550         }
551
552         /**
553          * Unarchive inboxes
554          *
555          * @param string  $url    inbox url
556          * @param boolean $shared Shared Inbox
557          * @param int     $gsid   Global server id
558          * @return void
559          */
560         private static function unarchiveInbox(string $url, bool $shared, int $gsid = null)
561         {
562                 if (empty($url)) {
563                         return;
564                 }
565
566                 HTTPSignature::setInboxStatus($url, true, $shared, $gsid);
567         }
568
569         /**
570          * Check if the apcontact is a relay account
571          *
572          * @param array $apcontact
573          *
574          * @return bool
575          */
576         public static function isRelay(array $apcontact): bool
577         {
578                 if (empty($apcontact['nick']) || $apcontact['nick'] != 'relay') {
579                         return false;
580                 }
581
582                 if (!empty($apcontact['type']) && $apcontact['type'] == 'Application') {
583                         return true;
584                 }
585
586                 if (!empty($apcontact['type']) && in_array($apcontact['type'], ['Group', 'Service']) && is_null($apcontact['outbox'])) {
587                         return true;
588                 }
589
590                 return false;
591         }
592 }