]> git.mxchange.org Git - friendica.git/blob - src/Network/Probe.php
Better support for "audience" / simplified Lemmy processing
[friendica.git] / src / Network / Probe.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\Network;
23
24 use DOMDocument;
25 use DomXPath;
26 use Exception;
27 use Friendica\Core\Hook;
28 use Friendica\Core\Logger;
29 use Friendica\Core\Protocol;
30 use Friendica\Core\System;
31 use Friendica\Database\DBA;
32 use Friendica\DI;
33 use Friendica\Model\Contact;
34 use Friendica\Model\GServer;
35 use Friendica\Model\Profile;
36 use Friendica\Model\User;
37 use Friendica\Network\HTTPClient\Client\HttpClientAccept;
38 use Friendica\Network\HTTPClient\Client\HttpClientOptions;
39 use Friendica\Protocol\ActivityNamespace;
40 use Friendica\Protocol\ActivityPub;
41 use Friendica\Protocol\Diaspora;
42 use Friendica\Protocol\Email;
43 use Friendica\Protocol\Feed;
44 use Friendica\Protocol\Salmon;
45 use Friendica\Util\Crypto;
46 use Friendica\Util\DateTimeFormat;
47 use Friendica\Util\Network;
48 use Friendica\Util\Strings;
49 use Friendica\Util\XML;
50 use GuzzleHttp\Psr7\Uri;
51
52 /**
53  * This class contain functions for probing URL
54  */
55 class Probe
56 {
57         const HOST_META = '/.well-known/host-meta';
58         const WEBFINGER = '/.well-known/webfinger?resource={uri}';
59
60         /**
61          * @var string Base URL
62          */
63         private static $baseurl;
64
65         /**
66          * @var boolean Whether a timeout has occurred
67          */
68         private static $isTimeout;
69
70         /**
71          * Checks if the provided network can be probed
72          *
73          * @param string $network
74          *
75          * @return boolean
76          */
77         public static function isProbable(string $network): bool
78         {
79                 return (in_array($network, array_merge(Protocol::FEDERATED, [Protocol::ZOT, Protocol::PHANTOM])));
80         }
81
82         /**
83          * Remove stuff from an URI that doesn't belong there
84          *
85          * @param string $rawUri
86          * @return string Cleaned URI
87          */
88         public static function cleanURI(string $rawUri): string
89         {
90                 // At first remove leading and trailing junk
91                 $rawUri = trim($rawUri, "@#?: \t\n\r\0\x0B");
92
93                 $rawUri = Network::convertToIdn($rawUri);
94
95                 $uri = new Uri($rawUri);
96                 if (!$uri->getScheme()) {
97                         return $uri->__toString();
98                 }
99
100                 // Remove the URL fragment, since these shouldn't be part of any profile URL
101                 $uri = $uri->withFragment('');
102
103                 return $uri->__toString();
104         }
105
106         /**
107          * Rearrange the array so that it always has the same order
108          *
109          * @param array $data Unordered data
110          * @return array Ordered data
111          */
112         private static function rearrangeData(array $data): array
113         {
114                 $fields = ['name', 'given_name', 'family_name', 'nick', 'guid', 'url', 'addr', 'alias',
115                         'photo', 'photo_medium', 'photo_small', 'header',
116                                 'account-type', 'community', 'keywords', 'location', 'about', 'xmpp', 'matrix',
117                                 'hide', 'batch', 'notify', 'poll', 'request', 'confirm', 'subscribe', 'poco',
118                                 'following', 'followers', 'inbox', 'outbox', 'sharedinbox',
119                                 'priority', 'network', 'pubkey', 'manually-approve', 'baseurl', 'gsid'];
120
121                 $numeric_fields = ['gsid', 'hide', 'account-type', 'manually-approve'];
122
123                 if (!empty($data['photo'])) {
124                         $data['photo'] = Network::addBasePath($data['photo'], $data['url']);
125
126                         if (!Network::isValidHttpUrl($data['photo'])) {
127                                 Logger::warning('Invalid URL for photo', ['url' => $data['url'], 'photo' => $data['photo']]);
128                                 unset($data['photo']);
129                         }
130                 }
131
132                 $newdata = [];
133                 foreach ($fields as $field) {
134                         if (isset($data[$field])) {
135                                 if (in_array($field, $numeric_fields)) {
136                                         $newdata[$field] = (int)$data[$field];
137                                 } else {
138                                         $newdata[$field] = trim($data[$field]);
139                                 }
140                         } elseif (!in_array($field, $numeric_fields)) {
141                                 $newdata[$field] = '';
142                         } else {
143                                 $newdata[$field] = null;
144                         }
145                 }
146
147                 $newdata['networks'] = [];
148                 foreach ([Protocol::DIASPORA, Protocol::OSTATUS] as $network) {
149                         if (!empty($data['networks'][$network])) {
150                                 $data['networks'][$network]['subscribe'] = $newdata['subscribe'] ?? '';
151                                 if (empty($data['networks'][$network]['baseurl'])) {
152                                         $data['networks'][$network]['baseurl'] = $newdata['baseurl'] ?? '';
153                                 } else {
154                                         $newdata['baseurl'] = $data['networks'][$network]['baseurl'];
155                                 }
156                                 if (!empty($newdata['baseurl'])) {
157                                         $newdata['gsid'] = $data['networks'][$network]['gsid'] = GServer::getID($newdata['baseurl']);
158                                 } else {
159                                         $newdata['gsid'] = $data['networks'][$network]['gsid'] = null;
160                                 }
161
162                                 $newdata['networks'][$network] = self::rearrangeData($data['networks'][$network]);
163                                 unset($newdata['networks'][$network]['networks']);
164                         }
165                 }
166
167                 // We don't use the "priority" field anymore and replace it with a dummy.
168                 $newdata['priority'] = 0;
169
170                 return $newdata;
171         }
172
173         /**
174          * Check if the hostname belongs to the own server
175          *
176          * @param string $host The hostname that is to be checked
177          * @return bool Does the testes hostname belongs to the own server?
178          */
179         private static function ownHost(string $host): bool
180         {
181                 $own_host = DI::baseUrl()->getHost();
182
183                 $parts = parse_url($host);
184
185                 if (!isset($parts['scheme'])) {
186                         $parts = parse_url('http://' . $host);
187                 }
188
189                 if (!isset($parts['host'])) {
190                         return false;
191                 }
192                 return $parts['host'] == $own_host;
193         }
194
195         /**
196          * Probes for webfinger path via "host-meta"
197          *
198          * We have to check if the servers in the future still will offer this.
199          * It seems as if it was dropped from the standard.
200          *
201          * @param string $host The host part of an url
202          *
203          * @return array with template and type of the webfinger template for JSON or XML
204          * @throws HTTPException\InternalServerErrorException
205          */
206         private static function hostMeta(string $host): array
207         {
208                 // Reset the static variable
209                 self::$baseurl = '';
210
211                 // Handles the case when the hostname contains the scheme
212                 if (!parse_url($host, PHP_URL_SCHEME)) {
213                         $ssl_url = 'https://' . $host . self::HOST_META;
214                         $url = 'http://' . $host . self::HOST_META;
215                 } else {
216                         $ssl_url = $host . self::HOST_META;
217                         $url = '';
218                 }
219
220                 $xrd_timeout = DI::config()->get('system', 'xrd_timeout', 20);
221
222                 Logger::info('Probing', ['host' => $host, 'ssl_url' => $ssl_url, 'url' => $url, 'callstack' => System::callstack(20)]);
223                 $xrd = null;
224
225                 $curlResult = DI::httpClient()->get($ssl_url, HttpClientAccept::XRD_XML, [HttpClientOptions::TIMEOUT => $xrd_timeout]);
226                 $ssl_connection_error = ($curlResult->getErrorNumber() == CURLE_COULDNT_CONNECT) || ($curlResult->getReturnCode() == 0);
227                 if ($curlResult->isSuccess()) {
228                         $xml = $curlResult->getBody();
229                         $xrd = XML::parseString($xml, true);
230                         if (!empty($url)) {
231                                 $host_url = 'https://' . $host;
232                         } else {
233                                 $host_url = $host;
234                         }
235                 } elseif ($curlResult->isTimeout()) {
236                         Logger::info('Probing timeout', ['url' => $ssl_url]);
237                         self::$isTimeout = true;
238                         return [];
239                 }
240
241                 if (!is_object($xrd) && !empty($url)) {
242                         $curlResult = DI::httpClient()->get($url, HttpClientAccept::XRD_XML, [HttpClientOptions::TIMEOUT => $xrd_timeout]);
243                         $connection_error = ($curlResult->getErrorNumber() == CURLE_COULDNT_CONNECT) || ($curlResult->getReturnCode() == 0);
244                         if ($curlResult->isTimeout()) {
245                                 Logger::info('Probing timeout', ['url' => $url]);
246                                 self::$isTimeout = true;
247                                 return [];
248                         } elseif ($connection_error && $ssl_connection_error) {
249                                 self::$isTimeout = true;
250                                 return [];
251                         }
252
253                         $xml = $curlResult->getBody();
254                         $xrd = XML::parseString($xml, true);
255                         $host_url = 'http://'.$host;
256                 }
257                 if (!is_object($xrd)) {
258                         Logger::info('No xrd object found', ['host' => $host]);
259                         return [];
260                 }
261
262                 $links = XML::elementToArray($xrd);
263                 if (!isset($links['xrd']['link'])) {
264                         Logger::info('No xrd data found', ['host' => $host]);
265                         return [];
266                 }
267
268                 $lrdd = [];
269
270                 foreach ($links['xrd']['link'] as $value => $link) {
271                         if (!empty($link['@attributes'])) {
272                                 $attributes = $link['@attributes'];
273                         } elseif ($value == '@attributes') {
274                                 $attributes = $link;
275                         } else {
276                                 continue;
277                         }
278
279                         if (!empty($attributes['rel']) && $attributes['rel'] == 'lrdd' && !empty($attributes['template'])) {
280                                 $type = (empty($attributes['type']) ? '' : $attributes['type']);
281
282                                 $lrdd[$type] = $attributes['template'];
283                         }
284                 }
285
286                 if (Network::isUrlBlocked($host_url)) {
287                         Logger::info('Domain is blocked', ['url' => $host]);
288                         return [];
289                 }
290
291                 self::$baseurl = $host_url;
292
293                 Logger::info('Probing successful', ['host' => $host]);
294
295                 return $lrdd;
296         }
297
298         /**
299          * Check an URI for LRDD data
300          *
301          * @param string $uri     Address that should be probed
302          * @return array uri data
303          * @throws HTTPException\InternalServerErrorException
304          */
305         public static function lrdd(string $uri): array
306         {
307                 $data = self::getWebfingerArray($uri);
308                 if (empty($data)) {
309                         return [];
310                 }
311                 $webfinger = $data['webfinger'];
312
313                 if (empty($webfinger['links'])) {
314                         Logger::info('No webfinger links found', ['uri' => $uri]);
315                         return [];
316                 }
317
318                 $data = [];
319
320                 foreach ($webfinger['links'] as $link) {
321                         $data[] = ['@attributes' => $link];
322                 }
323
324                 if (!empty($webfinger['aliases']) && is_array($webfinger['aliases'])) {
325                         foreach ($webfinger['aliases'] as $alias) {
326                                 $data[] = [
327                                         '@attributes' => [
328                                                 'rel' => 'alias',
329                                                 'href' => $alias,
330                                         ]
331                                 ];
332                         }
333                 }
334
335                 return $data;
336         }
337
338         /**
339          * Fetch information (protocol endpoints and user information) about a given uri
340          *
341          * @param string  $uri     Address that should be probed
342          * @param string  $network Test for this specific network
343          * @param integer $uid     User ID for the probe (only used for mails)
344          *
345          * @return array uri data
346          * @throws HTTPException\InternalServerErrorException
347          * @throws \ImagickException
348          */
349         public static function uri(string $uri, string $network = '', int $uid = -1): array
350         {
351                 // Local profiles aren't probed via network
352                 if (empty($network) && Contact::isLocal($uri)) {
353                         $data = self::localProbe($uri);
354                         if (!empty($data)) {
355                                 return $data;
356                         }
357                 }
358
359                 if ($uid == -1) {
360                         $uid = DI::userSession()->getLocalUserId();
361                 }
362
363                 if (empty($network) || ($network == Protocol::ACTIVITYPUB)) {
364                         $ap_profile = ActivityPub::probeProfile($uri);
365                 } else {
366                         $ap_profile = [];
367                 }
368
369                 self::$isTimeout = false;
370
371                 if ($network != Protocol::ACTIVITYPUB) {
372                         $data = self::detect($uri, $network, $uid, $ap_profile);
373                         if (!is_array($data)) {
374                                 $data = [];
375                         }
376                         if (empty($data) || (!empty($ap_profile) && empty($network) && (($data['network'] ?? '') != Protocol::DFRN))) {
377                                 $networks = $data['networks'] ?? [];
378                                 unset($data['networks']);
379                                 if (!empty($data['network'])) {
380                                         $networks[$data['network']] = $data;
381                                 }
382                                 $data = $ap_profile;
383                                 $data['networks'] = $networks;
384                         } elseif (!empty($ap_profile)) {
385                                 $ap_profile['batch'] = '';
386                                 $data = array_merge($ap_profile, $data);
387                         }
388                 } else {
389                         $data = $ap_profile;
390                 }
391
392                 if (!isset($data['url'])) {
393                         $data['url'] = $uri;
394                 }
395
396                 if (empty($data['photo'])) {
397                         $data['photo'] = DI::baseUrl() . Contact::DEFAULT_AVATAR_PHOTO;
398                 }
399
400                 if (empty($data['name'])) {
401                         if (!empty($data['nick'])) {
402                                 $data['name'] = $data['nick'];
403                         }
404
405                         if (empty($data['name'])) {
406                                 $data['name'] = $data['url'];
407                         }
408                 }
409
410                 if (empty($data['nick'])) {
411                         $data['nick'] = strtolower($data['name']);
412
413                         if (strpos($data['nick'], ' ')) {
414                                 $data['nick'] = trim(substr($data['nick'], 0, strpos($data['nick'], ' ')));
415                         }
416                 }
417
418                 if (!empty($data['baseurl']) && empty($data['gsid'])) {
419                         $data['gsid'] = GServer::getID($data['baseurl']);
420                 }
421
422                 if (empty($data['network'])) {
423                         $data['network'] = Protocol::PHANTOM;
424                 }
425
426                 // Ensure that local connections always are DFRN
427                 if (($network == '') && ($data['network'] != Protocol::PHANTOM) && (self::ownHost($data['baseurl'] ?? '') || self::ownHost($data['url']))) {
428                         $data['network'] = Protocol::DFRN;
429                 }
430
431                 if (!isset($data['hide']) && in_array($data['network'], Protocol::FEDERATED)) {
432                         $data['hide'] = self::getHideStatus($data['url']);
433                 }
434
435                 return self::rearrangeData($data);
436         }
437
438
439         /**
440          * Fetches the "hide" status from the profile
441          *
442          * @param string $url URL of the profile
443          * @return boolean "hide" status
444          */
445         private static function getHideStatus(string $url): bool
446         {
447                 $curlResult = DI::httpClient()->get($url, HttpClientAccept::HTML, [HttpClientOptions::CONTENT_LENGTH => 1000000]);
448                 if (!$curlResult->isSuccess()) {
449                         return false;
450                 }
451
452                 // If it isn't a HTML file then exit
453                 if (($curlResult->getContentType() != '') && !strstr(strtolower($curlResult->getContentType()), 'html')) {
454                         return false;
455                 }
456
457                 $body = $curlResult->getBody();
458                 if (empty($body)) {
459                         return false;
460                 }
461
462                 $doc = new DOMDocument();
463                 @$doc->loadHTML($body);
464
465                 $xpath = new DOMXPath($doc);
466
467                 $list = $xpath->query('//meta[@name]');
468                 foreach ($list as $node) {
469                         $meta_tag = [];
470                         if ($node->attributes->length) {
471                                 foreach ($node->attributes as $attribute) {
472                                         $meta_tag[$attribute->name] = $attribute->value;
473                                 }
474                         }
475
476                         if (empty($meta_tag['content'])) {
477                                 continue;
478                         }
479
480                         $content = strtolower(trim($meta_tag['content']));
481
482                         switch (strtolower(trim($meta_tag['name']))) {
483                                 case 'dfrn-global-visibility':
484                                         if ($content == 'false') {
485                                                 return true;
486                                         }
487                                         break;
488                                 case 'robots':
489                                         if (strpos($content, 'noindex') !== false) {
490                                                 return true;
491                                         }
492                                         break;
493                         }
494                 }
495
496                 return false;
497         }
498
499         /**
500          * Fetch the "subscribe" and add it to the result
501          *
502          * @param array $result Result array
503          * @param array $webfinger Webfinger data
504          *
505          * @return array result Altered/unaltered result array
506          */
507         private static function getSubscribeLink(array $result, array $webfinger): array
508         {
509                 if (empty($webfinger['links'])) {
510                         return $result;
511                 }
512
513                 foreach ($webfinger['links'] as $link) {
514                         if (!empty($link['template']) && ($link['rel'] === ActivityNamespace::OSTATUSSUB)) {
515                                 $result['subscribe'] = $link['template'];
516                         }
517                 }
518
519                 return $result;
520         }
521
522         /**
523          * Get webfinger data from a given URI
524          *
525          * @param string $uri URI
526          *
527          * @return array Webfinger data
528          * @throws HTTPException\InternalServerErrorException
529          */
530         public static function getWebfingerArray(string $uri): array
531         {
532                 $parts = parse_url($uri);
533
534                 if (!empty($parts['scheme']) && !empty($parts['host'])) {
535                         $host = $parts['host'];
536                         if (!empty($parts['port'])) {
537                                 $host .= ':' . $parts['port'];
538                         }
539
540                         $baseurl = $parts['scheme'] . '://' . $host;
541
542                         $nick = '';
543                         $addr = '';
544
545                         $path_parts = explode('/', trim($parts['path'] ?? '', '/'));
546                         if (!empty($path_parts)) {
547                                 $nick = ltrim(end($path_parts), '@');
548                                 $addr = $nick . '@' . $host;
549                         }
550
551                         $webfinger = self::getWebfinger($parts['scheme'] . '://' . $host . self::WEBFINGER, HttpClientAccept::JRD_JSON, $uri, $addr);
552                         if (empty($webfinger)) {
553                                 $lrdd = self::hostMeta($host);
554                         }
555
556                         if (empty($webfinger) && empty($lrdd)) {
557                                 while (empty($lrdd) && empty($webfinger) && (sizeof($path_parts) > 1)) {
558                                         $host    .= '/' . array_shift($path_parts);
559                                         $baseurl = $parts['scheme'] . '://' . $host;
560
561                                         if (!empty($nick)) {
562                                                 $addr = $nick . '@' . $host;
563                                         }
564
565                                         $webfinger = self::getWebfinger($parts['scheme'] . '://' . $host . self::WEBFINGER, HttpClientAccept::JRD_JSON, $uri, $addr);
566                                         if (empty($webfinger)) {
567                                                 $lrdd = self::hostMeta($host);
568                                         }
569                                 }
570
571                                 if (empty($lrdd) && empty($webfinger)) {
572                                         return [];
573                                 }
574                         }
575                 } elseif (strstr($uri, '@')) {
576                         // Remove "acct:" from the URI
577                         $uri = str_replace('acct:', '', $uri);
578
579                         $host = substr($uri, strpos($uri, '@') + 1);
580                         $nick = substr($uri, 0, strpos($uri, '@'));
581                         $addr = $uri;
582
583                         $webfinger = self::getWebfinger('https://' . $host . self::WEBFINGER, HttpClientAccept::JRD_JSON, $uri, $addr);
584                         if (self::$isTimeout) {
585                                 return [];
586                         }
587
588                         if (empty($webfinger)) {
589                                 $webfinger = self::getWebfinger('http://' . $host . self::WEBFINGER, HttpClientAccept::JRD_JSON, $uri, $addr);
590                                 if (self::$isTimeout) {
591                                         return [];
592                                 }
593                         } else {
594                                 $baseurl = 'https://' . $host;
595                         }
596
597                         if (empty($webfinger)) {
598                                 $lrdd = self::hostMeta($host);
599                                 if (self::$isTimeout) {
600                                         return [];
601                                 }
602                                 $baseurl = self::$baseurl;
603                         } else {
604                                 $baseurl = 'http://' . $host;
605                         }
606                 } else {
607                         Logger::info('URI was not detectable', ['uri' => $uri]);
608                         return [];
609                 }
610
611                 if (empty($webfinger)) {
612                         foreach ($lrdd as $type => $template) {
613                                 if ($webfinger) {
614                                         continue;
615                                 }
616
617                                 $webfinger = self::getWebfinger($template, $type, $uri, $addr);
618                         }
619                 }
620
621                 if (empty($webfinger)) {
622                         return [];
623                 }
624
625                 if ($webfinger['detected'] == $addr) {
626                         $webfinger['nick'] = $nick;
627                         $webfinger['addr'] = $addr;
628                 }
629
630                 $webfinger['baseurl'] = $baseurl;
631
632                 return $webfinger;
633         }
634
635         /**
636          * Perform network request for webfinger data
637          *
638          * @param string $template
639          * @param string $type
640          * @param string $uri
641          * @param string $addr
642          *
643          * @return array webfinger results
644          */
645         private static function getWebfinger(string $template, string $type, string $uri, string $addr): array
646         {
647                 if (Network::isUrlBlocked($template)) {
648                         Logger::info('Domain is blocked', ['url' => $template]);
649                         return [];
650                 }
651
652                 // First try the address because this is the primary purpose of webfinger
653                 if (!empty($addr)) {
654                         $detected = $addr;
655                         $path = str_replace('{uri}', urlencode('acct:' . $addr), $template);
656                         $webfinger = self::webfinger($path, $type);
657                         if (self::$isTimeout) {
658                                 return [];
659                         }
660                 }
661
662                 // Then try the URI
663                 if (empty($webfinger) && $uri != $addr) {
664                         $detected = $uri;
665                         $path = str_replace('{uri}', urlencode($uri), $template);
666                         $webfinger = self::webfinger($path, $type);
667                         if (self::$isTimeout) {
668                                 return [];
669                         }
670                 }
671
672                 if (empty($webfinger)) {
673                         return [];
674                 }
675
676                 return ['webfinger' => $webfinger, 'detected' => $detected];
677         }
678
679         /**
680          * Fetch information (protocol endpoints and user information) about a given uri
681          *
682          * This function is only called by the "uri" function that adds caching and rearranging of data.
683          *
684          * @param string  $uri        Address that should be probed
685          * @param string  $network    Test for this specific network
686          * @param integer $uid        User ID for the probe (only used for mails)
687          * @param array   $ap_profile Previously probed AP profile
688          * @return array URI data
689          * @throws HTTPException\InternalServerErrorException
690          */
691         private static function detect(string $uri, string $network, int $uid, array $ap_profile): array
692         {
693                 $hookData = [
694                         'uri'     => $uri,
695                         'network' => $network,
696                         'uid'     => $uid,
697                         'result'  => null,
698                 ];
699
700                 Hook::callAll('probe_detect', $hookData);
701
702                 if (isset($hookData['result'])) {
703                         return is_array($hookData['result']) ? $hookData['result'] : [];
704                 }
705
706                 $parts = parse_url($uri);
707                 if (empty($parts['scheme']) && empty($parts['host']) && (empty($parts['path']) || strpos($parts['path'], '@') === false)) {
708                         Logger::info('URI was not detectable', ['uri' => $uri]);
709                         return [];
710                 }
711
712                 // If the URI starts with "mailto:" then jump directly to the mail detection
713                 if (strpos($uri, 'mailto:') !== false) {
714                         $uri = str_replace('mailto:', '', $uri);
715                         return self::mail($uri, $uid);
716                 }
717
718                 if ($network == Protocol::MAIL) {
719                         return self::mail($uri, $uid);
720                 }
721
722                 Logger::info('Probing start', ['uri' => $uri]);
723
724                 if (!empty($ap_profile['addr']) && ($ap_profile['addr'] != $uri)) {
725                         $data = self::getWebfingerArray($ap_profile['addr']);
726                 }
727
728                 if (empty($data)) {
729                         $data = self::getWebfingerArray($uri);
730                 }
731
732                 if (empty($data)) {
733                         if (!empty($parts['scheme'])) {
734                                 return self::feed($uri);
735                         } elseif (!empty($uid)) {
736                                 return self::mail($uri, $uid);
737                         } else {
738                                 return [];
739                         }
740                 }
741
742                 $webfinger = $data['webfinger'];
743                 $nick = $data['nick'] ?? '';
744                 $addr = $data['addr'] ?? '';
745                 $baseurl = $data['baseurl'] ?? '';
746
747                 $result = [];
748
749                 if (in_array($network, ['', Protocol::DFRN])) {
750                         $result = self::dfrn($webfinger);
751                 }
752                 if ((!$result && ($network == '')) || ($network == Protocol::DIASPORA)) {
753                         $result = self::diaspora($webfinger);
754                 } else {
755                         $result['networks'][Protocol::DIASPORA] = self::diaspora($webfinger);
756                 }
757                 if ((!$result && ($network == '')) || ($network == Protocol::OSTATUS)) {
758                         $result = self::ostatus($webfinger);
759                 } else {
760                         $result['networks'][Protocol::OSTATUS] = self::ostatus($webfinger);
761                 }
762                 if (in_array($network, ['', Protocol::ZOT])) {
763                         $result = self::zot($webfinger, $result, $baseurl);
764                 }
765                 if ((!$result && ($network == '')) || ($network == Protocol::PUMPIO)) {
766                         $result = self::pumpio($webfinger, $addr, $baseurl);
767                 }
768                 if (empty($result['network']) && empty($ap_profile['network']) || ($network == Protocol::FEED)) {
769                         $result = self::feed($uri);
770                 } else {
771                         // We overwrite the detected nick with our try if the previous routines hadn't detected it.
772                         // Additionally, it is overwritten when the nickname doesn't make sense (contains spaces).
773                         if ((empty($result['nick']) || (strstr($result['nick'], ' '))) && ($nick != '')) {
774                                 $result['nick'] = $nick;
775                         }
776
777                         if (empty($result['addr']) && ($addr != '')) {
778                                 $result['addr'] = $addr;
779                         }
780                 }
781
782                 $result = self::getSubscribeLink($result, $webfinger);
783
784                 if (empty($result['network'])) {
785                         $result['network'] = Protocol::PHANTOM;
786                 }
787
788                 if (empty($result['baseurl']) && !empty($baseurl)) {
789                         $result['baseurl'] = $baseurl;
790                 }
791
792                 if (empty($result['url'])) {
793                         $result['url'] = $uri;
794                 }
795
796                 Logger::info('Probing done', ['uri' => $uri, 'network' => $result['network']]);
797
798                 return $result;
799         }
800
801         /**
802          * Check for Zot contact
803          *
804          * @param array  $webfinger Webfinger data
805          * @param array  $data      previously probed data
806          * @param string $baseUrl   Base URL
807          *
808          * @return array Zot data
809          * @throws HTTPException\InternalServerErrorException
810          */
811         private static function zot(array $webfinger, array $data, string $baseurl): array
812         {
813                 if (!empty($webfinger['aliases']) && is_array($webfinger['aliases'])) {
814                         foreach ($webfinger['aliases'] as $alias) {
815                                 if (substr($alias, 0, 5) == 'acct:') {
816                                         $data['addr'] = substr($alias, 5);
817                                 }
818                         }
819                 }
820
821                 if (!empty($webfinger['subject']) && (substr($webfinger['subject'], 0, 5) == 'acct:')) {
822                         $data['addr'] = substr($webfinger['subject'], 5);
823                 }
824
825                 $zot_url = '';
826                 foreach ($webfinger['links'] as $link) {
827                         if (($link['rel'] == 'http://purl.org/zot/protocol') && !empty($link['href'])) {
828                                 $zot_url = $link['href'];
829                         }
830                 }
831
832                 if (empty($zot_url) && !empty($data['addr']) && !empty($baseurl)) {
833                         $condition = ['nurl' => Strings::normaliseLink($baseurl), 'platform' => ['hubzilla']];
834                         if (!DBA::exists('gserver', $condition)) {
835                                 return $data;
836                         }
837                         $zot_url = $baseurl . '/.well-known/zot-info?address=' . $data['addr'];
838                 }
839
840                 if (empty($zot_url)) {
841                         return $data;
842                 }
843
844                 $data = self::pollZot($zot_url, $data);
845
846                 if (!empty($data['url']) && !empty($webfinger['aliases']) && is_array($webfinger['aliases'])) {
847                         foreach ($webfinger['aliases'] as $alias) {
848                                 if (!strstr($alias, '@') && Strings::normaliseLink($alias) != Strings::normaliseLink($data['url'])) {
849                                         $data['alias'] = $alias;
850                                 }
851                         }
852                 }
853
854                 return $data;
855         }
856
857         public static function pollZot(string $url, array $data): array
858         {
859                 $curlResult = DI::httpClient()->get($url, HttpClientAccept::JSON);
860                 if ($curlResult->isTimeout()) {
861                         return $data;
862                 }
863                 $content = $curlResult->getBody();
864                 if (!$content) {
865                         return $data;
866                 }
867
868                 $json = json_decode($content, true);
869                 if (!is_array($json)) {
870                         return $data;
871                 }
872
873                 if (empty($data['network'])) {
874                         if (!empty($json['protocols']) && in_array('zot', $json['protocols'])) {
875                                 $data['network'] = Protocol::ZOT;
876                         } elseif (!isset($json['protocols'])) {
877                                 $data['network'] = Protocol::ZOT;
878                         }
879                 }
880
881                 if (!empty($json['guid']) && empty($data['guid'])) {
882                         $data['guid'] = $json['guid'];
883                 }
884                 if (!empty($json['key']) && empty($data['pubkey'])) {
885                         $data['pubkey'] = $json['key'];
886                 }
887                 if (!empty($json['name'])) {
888                         $data['name'] = $json['name'];
889                 }
890                 if (!empty($json['photo'])) {
891                         $data['photo'] = $json['photo'];
892                         if (!empty($json['photo_updated'])) {
893                                 $data['photo'] .= '?rev=' . urlencode($json['photo_updated']);
894                         }
895                 }
896                 if (!empty($json['address'])) {
897                         $data['addr'] = $json['address'];
898                 }
899                 if (!empty($json['url'])) {
900                         $data['url'] = $json['url'];
901                 }
902                 if (!empty($json['connections_url'])) {
903                         $data['poco'] = $json['connections_url'];
904                 }
905                 if (isset($json['searchable'])) {
906                         $data['hide'] = !$json['searchable'];
907                 }
908                 if (!empty($json['public_forum'])) {
909                         $data['community'] = $json['public_forum'];
910                         $data['account-type'] = User::PAGE_FLAGS_COMMUNITY;
911                 }
912
913                 if (!empty($json['profile'])) {
914                         $profile = $json['profile'];
915                         if (!empty($profile['description'])) {
916                                 $data['about'] = $profile['description'];
917                         }
918                         if (!empty($profile['keywords'])) {
919                                 $keywords = implode(', ', $profile['keywords']);
920                                 if (!empty($keywords)) {
921                                         $data['keywords'] = $keywords;
922                                 }
923                         }
924
925                         $loc = [];
926                         if (!empty($profile['region'])) {
927                                 $loc['region'] = $profile['region'];
928                         }
929                         if (!empty($profile['country'])) {
930                                 $loc['country-name'] = $profile['country'];
931                         }
932                         $location = Profile::formatLocation($loc);
933                         if (!empty($location)) {
934                                 $data['location'] = $location;
935                         }
936                 }
937
938                 return $data;
939         }
940
941         /**
942          * Perform a webfinger request.
943          *
944          * For details see RFC 7033: <https://tools.ietf.org/html/rfc7033>
945          *
946          * @param string $url  Address that should be probed
947          * @param string $type type
948          *
949          * @return array webfinger data
950          * @throws HTTPException\InternalServerErrorException
951          */
952         public static function webfinger(string $url, string $type): array
953         {
954                 try {
955                         $curlResult = DI::httpClient()->get(
956                                 $url,
957                                 $type,
958                                 [HttpClientOptions::TIMEOUT => DI::config()->get('system', 'xrd_timeout', 20)]
959                         );
960                 } catch (\Throwable $e) {
961                         Logger::notice($e->getMessage(), ['url' => $url, 'type' => $type, 'class' => get_class($e)]);
962                         return [];
963                 }
964
965                 if ($curlResult->isTimeout()) {
966                         self::$isTimeout = true;
967                         return [];
968                 }
969                 $data = $curlResult->getBody();
970
971                 $webfinger = json_decode($data, true);
972                 if (!empty($webfinger)) {
973                         if (!isset($webfinger['links'])) {
974                                 Logger::info('No json webfinger links', ['url' => $url]);
975                                 return [];
976                         }
977                         return $webfinger;
978                 }
979
980                 // If it is not JSON, maybe it is XML
981                 $xrd = XML::parseString($data, true);
982                 if (!is_object($xrd)) {
983                         Logger::info('No webfinger data retrievable', ['url' => $url]);
984                         return [];
985                 }
986
987                 $xrd_arr = XML::elementToArray($xrd);
988                 if (!isset($xrd_arr['xrd']['link'])) {
989                         Logger::info('No XML webfinger links', ['url' => $url]);
990                         return [];
991                 }
992
993                 $webfinger = [];
994
995                 if (!empty($xrd_arr['xrd']['subject'])) {
996                         $webfinger['subject'] = $xrd_arr['xrd']['subject'];
997                 }
998
999                 if (!empty($xrd_arr['xrd']['alias'])) {
1000                         $webfinger['aliases'] = $xrd_arr['xrd']['alias'];
1001                 }
1002
1003                 $webfinger['links'] = [];
1004
1005                 foreach ($xrd_arr['xrd']['link'] as $value => $data) {
1006                         if (!empty($data['@attributes'])) {
1007                                 $attributes = $data['@attributes'];
1008                         } elseif ($value == '@attributes') {
1009                                 $attributes = $data;
1010                         } else {
1011                                 continue;
1012                         }
1013
1014                         $webfinger['links'][] = $attributes;
1015                 }
1016                 return $webfinger;
1017         }
1018
1019         /**
1020          * Poll the Friendica specific noscrape page.
1021          *
1022          * "noscrape" is a faster alternative to fetch the data from the hcard.
1023          * This functionality was originally created for the directory.
1024          *
1025          * @param string $noscrape_url Link to the noscrape page
1026          * @param array  $data         The already fetched data
1027          *
1028          * @return array noscrape data
1029          * @throws HTTPException\InternalServerErrorException
1030          */
1031         private static function pollNoscrape(string $noscrape_url, array $data): array
1032         {
1033                 $curlResult = DI::httpClient()->get($noscrape_url, HttpClientAccept::JSON);
1034                 if ($curlResult->isTimeout()) {
1035                         self::$isTimeout = true;
1036                         return $data;
1037                 }
1038                 $content = $curlResult->getBody();
1039                 if (!$content) {
1040                         Logger::info('Empty body', ['url' => $noscrape_url]);
1041                         return $data;
1042                 }
1043
1044                 $json = json_decode($content, true);
1045                 if (!is_array($json)) {
1046                         Logger::info('No json data', ['url' => $noscrape_url]);
1047                         return $data;
1048                 }
1049
1050                 if (!empty($json['fn'])) {
1051                         $data['name'] = $json['fn'];
1052                 }
1053
1054                 if (!empty($json['addr'])) {
1055                         $data['addr'] = $json['addr'];
1056                 }
1057
1058                 if (!empty($json['nick'])) {
1059                         $data['nick'] = $json['nick'];
1060                 }
1061
1062                 if (!empty($json['guid'])) {
1063                         $data['guid'] = $json['guid'];
1064                 }
1065
1066                 if (!empty($json['comm'])) {
1067                         $data['community'] = $json['comm'];
1068                 }
1069
1070                 if (!empty($json['tags'])) {
1071                         $keywords = implode(', ', $json['tags']);
1072                         if ($keywords != '') {
1073                                 $data['keywords'] = $keywords;
1074                         }
1075                 }
1076
1077                 $location = Profile::formatLocation($json);
1078                 if ($location) {
1079                         $data['location'] = $location;
1080                 }
1081
1082                 if (!empty($json['about'])) {
1083                         $data['about'] = $json['about'];
1084                 }
1085
1086                 if (!empty($json['xmpp'])) {
1087                         $data['xmpp'] = $json['xmpp'];
1088                 }
1089
1090                 if (!empty($json['matrix'])) {
1091                         $data['matrix'] = $json['matrix'];
1092                 }
1093
1094                 if (!empty($json['key'])) {
1095                         $data['pubkey'] = $json['key'];
1096                 }
1097
1098                 if (!empty($json['photo'])) {
1099                         $data['photo'] = $json['photo'];
1100                 }
1101
1102                 if (!empty($json['dfrn-request'])) {
1103                         $data['request'] = $json['dfrn-request'];
1104                 }
1105
1106                 if (!empty($json['dfrn-confirm'])) {
1107                         $data['confirm'] = $json['dfrn-confirm'];
1108                 }
1109
1110                 if (!empty($json['dfrn-notify'])) {
1111                         $data['notify'] = $json['dfrn-notify'];
1112                 }
1113
1114                 if (!empty($json['dfrn-poll'])) {
1115                         $data['poll'] = $json['dfrn-poll'];
1116                 }
1117
1118                 if (isset($json['hide'])) {
1119                         $data['hide'] = (bool)$json['hide'];
1120                 } else {
1121                         $data['hide'] = false;
1122                 }
1123
1124                 return $data;
1125         }
1126
1127         /**
1128          * Check for valid DFRN data
1129          *
1130          * @param array $data DFRN data
1131          *
1132          * @return int Number of errors
1133          */
1134         public static function validDfrn(array $data): int
1135         {
1136                 $errors = 0;
1137                 if (!isset($data['key'])) {
1138                         $errors ++;
1139                 }
1140                 if (!isset($data['dfrn-request'])) {
1141                         $errors ++;
1142                 }
1143                 if (!isset($data['dfrn-confirm'])) {
1144                         $errors ++;
1145                 }
1146                 if (!isset($data['dfrn-notify'])) {
1147                         $errors ++;
1148                 }
1149                 if (!isset($data['dfrn-poll'])) {
1150                         $errors ++;
1151                 }
1152                 return $errors;
1153         }
1154
1155         /**
1156          * Fetch data from a DFRN profile page and via "noscrape"
1157          *
1158          * @param string $profile_link Link to the profile page
1159          * @return array profile data
1160          * @throws HTTPException\InternalServerErrorException
1161          * @throws \ImagickException
1162          */
1163         public static function profile(string $profile_link): array
1164         {
1165                 $data = [];
1166
1167                 Logger::info('Check profile', ['link' => $profile_link]);
1168
1169                 // Fetch data via noscrape - this is faster
1170                 $noscrape_url = str_replace(['/hcard/', '/profile/'], '/noscrape/', $profile_link);
1171                 $data = self::pollNoscrape($noscrape_url, $data);
1172
1173                 if (!isset($data['notify'])
1174                         || !isset($data['confirm'])
1175                         || !isset($data['request'])
1176                         || !isset($data['poll'])
1177                         || !isset($data['name'])
1178                         || !isset($data['photo'])
1179                 ) {
1180                         $data = self::pollHcard($profile_link, $data, true);
1181                 }
1182
1183                 $prof_data = [];
1184
1185                 if (empty($data['addr']) || empty($data['nick'])) {
1186                         $probe_data = self::uri($profile_link);
1187                         $data['addr'] = ($data['addr'] ?? '') ?: $probe_data['addr'];
1188                         $data['nick'] = ($data['nick'] ?? '') ?: $probe_data['nick'];
1189                 }
1190
1191                 $prof_data['addr']         = $data['addr'];
1192                 $prof_data['nick']         = $data['nick'];
1193                 $prof_data['dfrn-request'] = $data['request'] ?? null;
1194                 $prof_data['dfrn-confirm'] = $data['confirm'] ?? null;
1195                 $prof_data['dfrn-notify']  = $data['notify']  ?? null;
1196                 $prof_data['dfrn-poll']    = $data['poll']    ?? null;
1197                 $prof_data['photo']        = $data['photo']   ?? null;
1198                 $prof_data['fn']           = $data['name']    ?? null;
1199                 $prof_data['key']          = $data['pubkey']  ?? null;
1200
1201                 Logger::debug('Result', ['link' => $profile_link, 'data' => $prof_data]);
1202
1203                 return $prof_data;
1204         }
1205
1206         /**
1207          * Check for DFRN contact
1208          *
1209          * @param array $webfinger Webfinger data
1210          * @return array DFRN data
1211          * @throws HTTPException\InternalServerErrorException
1212          */
1213         private static function dfrn(array $webfinger): array
1214         {
1215                 $hcard_url = '';
1216                 $data = [];
1217                 // The array is reversed to take into account the order of preference for same-rel links
1218                 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1219                 foreach (array_reverse($webfinger['links']) as $link) {
1220                         if (($link['rel'] == ActivityNamespace::DFRN) && !empty($link['href'])) {
1221                                 $data['network'] = Protocol::DFRN;
1222                         } elseif (($link['rel'] == ActivityNamespace::FEED) && !empty($link['href'])) {
1223                                 $data['poll'] = $link['href'];
1224                         } elseif (($link['rel'] == 'http://webfinger.net/rel/profile-page') && (($link['type'] ?? '') == 'text/html') && !empty($link['href'])) {
1225                                 $data['url'] = $link['href'];
1226                         } elseif (($link['rel'] == 'http://microformats.org/profile/hcard') && !empty($link['href'])) {
1227                                 $hcard_url = $link['href'];
1228                         } elseif (($link['rel'] == ActivityNamespace::POCO) && !empty($link['href'])) {
1229                                 $data['poco'] = $link['href'];
1230                         } elseif (($link['rel'] == 'http://webfinger.net/rel/avatar') && !empty($link['href'])) {
1231                                 $data['photo'] = $link['href'];
1232                         } elseif (($link['rel'] == 'http://joindiaspora.com/seed_location') && !empty($link['href'])) {
1233                                 $data['baseurl'] = trim($link['href'], '/');
1234                         } elseif (($link['rel'] == 'http://joindiaspora.com/guid') && !empty($link['href'])) {
1235                                 $data['guid'] = $link['href'];
1236                         } elseif (($link['rel'] == 'diaspora-public-key') && !empty($link['href'])) {
1237                                 $data['pubkey'] = base64_decode($link['href']);
1238
1239                                 if (strstr($data['pubkey'], 'RSA ')) {
1240                                         $data['pubkey'] = Crypto::rsaToPem($data['pubkey']);
1241                                 }
1242                         }
1243                 }
1244
1245                 if (!empty($webfinger['aliases']) && is_array($webfinger['aliases'])) {
1246                         foreach ($webfinger['aliases'] as $alias) {
1247                                 if (empty($data['url']) && !strstr($alias, '@')) {
1248                                         $data['url'] = $alias;
1249                                 } elseif (!strstr($alias, '@') && Strings::normaliseLink($alias) != Strings::normaliseLink($data['url'])) {
1250                                         $data['alias'] = $alias;
1251                                 } elseif (substr($alias, 0, 5) == 'acct:') {
1252                                         $data['addr'] = substr($alias, 5);
1253                                 }
1254                         }
1255                 }
1256
1257                 if (!empty($webfinger['subject']) && (substr($webfinger['subject'], 0, 5) == 'acct:')) {
1258                         $data['addr'] = substr($webfinger['subject'], 5);
1259                 }
1260
1261                 if (!isset($data['network']) || ($hcard_url == '')) {
1262                         return [];
1263                 }
1264
1265                 // Fetch data via noscrape - this is faster
1266                 $noscrape_url = str_replace('/hcard/', '/noscrape/', $hcard_url);
1267                 $data = self::pollNoscrape($noscrape_url, $data);
1268
1269                 if (isset($data['notify'])
1270                         && isset($data['confirm'])
1271                         && isset($data['request'])
1272                         && isset($data['poll'])
1273                         && isset($data['name'])
1274                         && isset($data['photo'])
1275                 ) {
1276                         return $data;
1277                 }
1278
1279                 $data = self::pollHcard($hcard_url, $data, true);
1280
1281                 return $data;
1282         }
1283
1284         /**
1285          * Poll the hcard page (Diaspora and Friendica specific)
1286          *
1287          * @param string  $hcard_url Link to the hcard page
1288          * @param array   $data      The already fetched data
1289          * @param boolean $dfrn      Poll DFRN specific data
1290          * @return array hcard data
1291          * @throws HTTPException\InternalServerErrorException
1292          */
1293         private static function pollHcard(string $hcard_url, array $data, bool $dfrn = false): array
1294         {
1295                 $curlResult = DI::httpClient()->get($hcard_url, HttpClientAccept::HTML);
1296                 if ($curlResult->isTimeout()) {
1297                         self::$isTimeout = true;
1298                         return [];
1299                 }
1300                 $content = $curlResult->getBody();
1301                 if (empty($content)) {
1302                         return [];
1303                 }
1304
1305                 $doc = new DOMDocument();
1306                 if (!@$doc->loadHTML($content)) {
1307                         return [];
1308                 }
1309
1310                 $xpath = new DomXPath($doc);
1311
1312                 $vcards = $xpath->query("//div[contains(concat(' ', @class, ' '), ' vcard ')]");
1313                 if (!is_object($vcards)) {
1314                         return [];
1315                 }
1316
1317                 if (!isset($data['baseurl'])) {
1318                         $data['baseurl'] = '';
1319                 }
1320
1321                 if ($vcards->length > 0) {
1322                         $vcard = $vcards->item(0);
1323
1324                         // We have to discard the guid from the hcard in favour of the guid from lrdd
1325                         // Reason: Hubzilla doesn't use the value "uid" in the hcard like Diaspora does.
1326                         $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' uid ')]", $vcard); // */
1327                         if (($search->length > 0) && empty($data['guid'])) {
1328                                 $data['guid'] = $search->item(0)->nodeValue;
1329                         }
1330
1331                         $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' nickname ')]", $vcard); // */
1332                         if ($search->length > 0) {
1333                                 $data['nick'] = $search->item(0)->nodeValue;
1334                         }
1335
1336                         $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' fn ')]", $vcard); // */
1337                         if ($search->length > 0) {
1338                                 $data['name'] = $search->item(0)->nodeValue;
1339                         }
1340
1341                         $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' given_name ')]", $vcard); // */
1342                         if ($search->length > 0) {
1343                                 $data["given_name"] = $search->item(0)->nodeValue;
1344                         }
1345
1346                         $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' family_name ')]", $vcard); // */
1347                         if ($search->length > 0) {
1348                                 $data["family_name"] = $search->item(0)->nodeValue;
1349                         }
1350
1351                         $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' searchable ')]", $vcard); // */
1352                         if ($search->length > 0) {
1353                                 $data['hide'] = (strtolower($search->item(0)->nodeValue) != 'true');
1354                         }
1355
1356                         $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' key ')]", $vcard); // */
1357                         if ($search->length > 0) {
1358                                 $data['pubkey'] = $search->item(0)->nodeValue;
1359                                 if (strstr($data['pubkey'], 'RSA ')) {
1360                                         $data['pubkey'] = Crypto::rsaToPem($data['pubkey']);
1361                                 }
1362                         }
1363
1364                         $search = $xpath->query("//*[@id='pod_location']", $vcard); // */
1365                         if ($search->length > 0) {
1366                                 $data['baseurl'] = trim($search->item(0)->nodeValue, '/');
1367                         }
1368                 }
1369
1370                 $avatars = [];
1371                 if (!empty($vcard)) {
1372                         $photos = $xpath->query("//*[contains(concat(' ', @class, ' '), ' photo ') or contains(concat(' ', @class, ' '), ' avatar ')]", $vcard); // */
1373                         foreach ($photos as $photo) {
1374                                 $attr = [];
1375                                 foreach ($photo->attributes as $attribute) {
1376                                         $attr[$attribute->name] = trim($attribute->value);
1377                                 }
1378
1379                                 if (isset($attr['src']) && isset($attr['width'])) {
1380                                         $avatars[$attr['width']] = self::fixAvatar($attr['src'], $data['baseurl']);
1381                                 }
1382
1383                                 // We don't have a width. So we just take everything that we got.
1384                                 // This is a Hubzilla workaround which doesn't send a width.
1385                                 if (!$avatars && !empty($attr['src'])) {
1386                                         $avatars[] = self::fixAvatar($attr['src'], $data['baseurl']);
1387                                 }
1388                         }
1389                 }
1390
1391                 if ($avatars) {
1392                         ksort($avatars);
1393                         $data['photo'] = array_pop($avatars);
1394                         if ($avatars) {
1395                                 $data['photo_medium'] = array_pop($avatars);
1396                         }
1397
1398                         if ($avatars) {
1399                                 $data['photo_small'] = array_pop($avatars);
1400                         }
1401                 }
1402
1403                 if ($dfrn) {
1404                         // Poll DFRN specific data
1405                         $search = $xpath->query("//link[contains(concat(' ', @rel), ' dfrn-')]");
1406                         if ($search->length > 0) {
1407                                 foreach ($search as $link) {
1408                                         //$data['request'] = $search->item(0)->nodeValue;
1409                                         $attr = [];
1410                                         foreach ($link->attributes as $attribute) {
1411                                                 $attr[$attribute->name] = trim($attribute->value);
1412                                         }
1413
1414                                         $data[substr($attr['rel'], 5)] = $attr['href'];
1415                                 }
1416                         }
1417
1418                         // Older Friendica versions had used the "uid" field differently than newer versions
1419                         if (!empty($data['nick']) && !empty($data['guid']) && ($data['nick'] == $data['guid'])) {
1420                                 unset($data['guid']);
1421                         }
1422                 }
1423
1424                 return $data;
1425         }
1426
1427         /**
1428          * Check for Diaspora contact
1429          *
1430          * @param array $webfinger Webfinger data
1431          *
1432          * @return array Diaspora data
1433          * @throws HTTPException\InternalServerErrorException
1434          */
1435         private static function diaspora(array $webfinger): array
1436         {
1437                 $hcard_url = '';
1438                 $data = [];
1439
1440                 // The array is reversed to take into account the order of preference for same-rel links
1441                 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1442                 foreach (array_reverse($webfinger['links']) as $link) {
1443                         if (($link['rel'] == 'http://microformats.org/profile/hcard') && !empty($link['href'])) {
1444                                 $hcard_url = $link['href'];
1445                         } elseif (($link['rel'] == 'http://joindiaspora.com/seed_location') && !empty($link['href'])) {
1446                                 $data['baseurl'] = trim($link['href'], '/');
1447                         } elseif (($link['rel'] == 'http://joindiaspora.com/guid') && !empty($link['href'])) {
1448                                 $data['guid'] = $link['href'];
1449                         } elseif (($link['rel'] == 'http://webfinger.net/rel/profile-page') && (($link['type'] ?? '') == 'text/html') && !empty($link['href'])) {
1450                                 $data['url'] = $link['href'];
1451                         } elseif (($link['rel'] == 'http://webfinger.net/rel/profile-page') && empty($link['type']) && !empty($link['href'])) {
1452                                 $profile_url = $link['href'];
1453                         } elseif (($link['rel'] == ActivityNamespace::FEED) && !empty($link['href'])) {
1454                                 $data['poll'] = $link['href'];
1455                         } elseif (($link['rel'] == ActivityNamespace::POCO) && !empty($link['href'])) {
1456                                 $data['poco'] = $link['href'];
1457                         } elseif (($link['rel'] == 'salmon') && !empty($link['href'])) {
1458                                 $data['notify'] = $link['href'];
1459                         } elseif (($link['rel'] == 'diaspora-public-key') && !empty($link['href'])) {
1460                                 $data['pubkey'] = base64_decode($link['href']);
1461
1462                                 if (strstr($data['pubkey'], 'RSA ')) {
1463                                         $data['pubkey'] = Crypto::rsaToPem($data['pubkey']);
1464                                 }
1465                         }
1466                 }
1467
1468                 if (empty($data['url']) && !empty($profile_url)) {
1469                         $data['url'] = $profile_url;
1470                 }
1471
1472                 if (empty($data['url']) || empty($hcard_url)) {
1473                         return [];
1474                 }
1475
1476                 if (!empty($webfinger['aliases']) && is_array($webfinger['aliases'])) {
1477                         foreach ($webfinger['aliases'] as $alias) {
1478                                 if (Strings::normaliseLink($alias) != Strings::normaliseLink($data['url']) && ! strstr($alias, '@')) {
1479                                         $data['alias'] = $alias;
1480                                 } elseif (substr($alias, 0, 5) == 'acct:') {
1481                                         $data['addr'] = substr($alias, 5);
1482                                 }
1483                         }
1484                 }
1485
1486                 if (!empty($webfinger['subject']) && (substr($webfinger['subject'], 0, 5) == 'acct:')) {
1487                         $data['addr'] = substr($webfinger['subject'], 5);
1488                 }
1489
1490                 // Fetch further information from the hcard
1491                 $data = self::pollHcard($hcard_url, $data);
1492
1493                 if (!$data) {
1494                         return [];
1495                 }
1496
1497                 if (!empty($data['url'])
1498                         && !empty($data['guid'])
1499                         && !empty($data['baseurl'])
1500                         && !empty($data['pubkey'])
1501                         && !empty($hcard_url)
1502                 ) {
1503                         $data['network'] = Protocol::DIASPORA;
1504                         $data['manually-approve'] = false;
1505
1506                         // The Diaspora handle must always be lowercase
1507                         if (!empty($data['addr'])) {
1508                                 $data['addr'] = strtolower($data['addr']);
1509                         }
1510
1511                         // We have to overwrite the detected value for "notify" since Hubzilla doesn't send it
1512                         $data['notify'] = $data['baseurl'] . '/receive/users/' . $data['guid'];
1513                         $data['batch']  = $data['baseurl'] . '/receive/public';
1514                 } else {
1515                         return [];
1516                 }
1517
1518                 return $data;
1519         }
1520
1521         /**
1522          * Check for OStatus contact
1523          *
1524          * @param array $webfinger Webfinger data
1525          * @param bool  $short     Short detection mode
1526          *
1527          * @return array|bool OStatus data or "false" on error or "true" on short mode
1528          * @throws HTTPException\InternalServerErrorException
1529          */
1530         private static function ostatus(array $webfinger, bool $short = false)
1531         {
1532                 $data = [];
1533
1534                 if (!empty($webfinger['aliases']) && is_array($webfinger['aliases'])) {
1535                         foreach ($webfinger['aliases'] as $alias) {
1536                                 if (strstr($alias, '@') && !strstr(Strings::normaliseLink($alias), 'http://')) {
1537                                         $data['addr'] = str_replace('acct:', '', $alias);
1538                                 }
1539                         }
1540                 }
1541
1542                 if (!empty($webfinger['subject']) && strstr($webfinger['subject'], '@')
1543                         && !strstr(Strings::normaliseLink($webfinger['subject']), 'http://')
1544                 ) {
1545                         $data['addr'] = str_replace('acct:', '', $webfinger['subject']);
1546                 }
1547
1548                 if (!empty($webfinger['links'])) {
1549                         // The array is reversed to take into account the order of preference for same-rel links
1550                         // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1551                         foreach (array_reverse($webfinger['links']) as $link) {
1552                                 if (($link['rel'] == 'http://webfinger.net/rel/profile-page')
1553                                         && (($link['type'] ?? '') == 'text/html')
1554                                         && ($link['href'] != '')
1555                                 ) {
1556                                         $data['url'] = $data['alias'] = $link['href'];
1557                                 } elseif (($link['rel'] == 'salmon') && !empty($link['href'])) {
1558                                         $data['notify'] = $link['href'];
1559                                 } elseif (($link['rel'] == ActivityNamespace::FEED) && !empty($link['href'])) {
1560                                         $data['poll'] = $link['href'];
1561                                 } elseif (($link['rel'] == 'magic-public-key') && !empty($link['href'])) {
1562                                         $pubkey = $link['href'];
1563
1564                                         if (substr($pubkey, 0, 5) === 'data:') {
1565                                                 if (strstr($pubkey, ',')) {
1566                                                         $pubkey = substr($pubkey, strpos($pubkey, ',') + 1);
1567                                                 } else {
1568                                                         $pubkey = substr($pubkey, 5);
1569                                                 }
1570                                         } elseif (Strings::normaliseLink($pubkey) == 'http://') {
1571                                                 $curlResult = DI::httpClient()->get($pubkey, HttpClientAccept::MAGIC_KEY);
1572                                                 if ($curlResult->isTimeout()) {
1573                                                         self::$isTimeout = true;
1574                                                         return $short ? false : [];
1575                                                 }
1576                                                 Logger::debug('Fetched public key', ['Content-Type' => $curlResult->getHeader('Content-Type'), 'url' => $pubkey]);
1577                                                 $pubkey = $curlResult->getBody();
1578                                         }
1579
1580                                         try {
1581                                                 $data['pubkey'] = Salmon::magicKeyToPem($pubkey);
1582                                         } catch (\Throwable $e) {
1583
1584                                         }
1585                                 }
1586                         }
1587                 }
1588
1589                 if (isset($data['notify']) && isset($data['pubkey'])
1590                         && isset($data['poll'])
1591                         && isset($data['url'])
1592                 ) {
1593                         $data['network'] = Protocol::OSTATUS;
1594                         $data['manually-approve'] = false;
1595                 } else {
1596                         return $short ? false : [];
1597                 }
1598
1599                 if ($short) {
1600                         return true;
1601                 }
1602
1603                 // Fetch all additional data from the feed
1604                 $curlResult = DI::httpClient()->get($data['poll'], HttpClientAccept::FEED_XML);
1605                 if ($curlResult->isTimeout()) {
1606                         self::$isTimeout = true;
1607                         return [];
1608                 }
1609                 $feed = $curlResult->getBody();
1610                 $feed_data = Feed::import($feed);
1611                 if (!$feed_data) {
1612                         return [];
1613                 }
1614
1615                 if (!empty($feed_data['header']['author-name'])) {
1616                         $data['name'] = $feed_data['header']['author-name'];
1617                 }
1618                 if (!empty($feed_data['header']['author-nick'])) {
1619                         $data['nick'] = $feed_data['header']['author-nick'];
1620                 }
1621                 if (!empty($feed_data['header']['author-avatar'])) {
1622                         $data['photo'] = self::fixAvatar($feed_data['header']['author-avatar'], $data['url']);
1623                 }
1624                 if (!empty($feed_data['header']['author-id'])) {
1625                         $data['alias'] = $feed_data['header']['author-id'];
1626                 }
1627                 if (!empty($feed_data['header']['author-location'])) {
1628                         $data['location'] = $feed_data['header']['author-location'];
1629                 }
1630                 if (!empty($feed_data['header']['author-about'])) {
1631                         $data['about'] = $feed_data['header']['author-about'];
1632                 }
1633                 // OStatus has serious issues when the url doesn't fit (ssl vs. non ssl)
1634                 // So we take the value that we just fetched, although the other one worked as well
1635                 if (!empty($feed_data['header']['author-link'])) {
1636                         $data['url'] = $feed_data['header']['author-link'];
1637                 }
1638
1639                 if ($data['url'] == $data['alias']) {
1640                         $data['alias'] = '';
1641                 }
1642
1643                 /// @todo Fetch location and "about" from the feed as well
1644                 return $data;
1645         }
1646
1647         /**
1648          * Fetch data from a pump.io profile page
1649          *
1650          * @param string $profile_link Link to the profile page
1651          *
1652          * @return array Profile data
1653          */
1654         private static function pumpioProfileData(string $profile_link, string $baseurl): array
1655         {
1656                 $curlResult = DI::httpClient()->get($profile_link, HttpClientAccept::HTML);
1657                 if (!$curlResult->isSuccess() || empty($curlResult->getBody())) {
1658                         return [];
1659                 }
1660
1661                 $doc = new DOMDocument();
1662                 if (!@$doc->loadHTML($curlResult->getBody())) {
1663                         return [];
1664                 }
1665
1666                 $xpath = new DomXPath($doc);
1667
1668                 $data = [];
1669                 $data['name'] = $xpath->query("//span[contains(@class, 'p-name')]")->item(0)->nodeValue;
1670
1671                 if ($data['name'] == '') {
1672                         // This is ugly - but pump.io doesn't seem to know a better way for it
1673                         $data['name'] = trim($xpath->query("//h1[@class='media-header']")->item(0)->nodeValue);
1674                         $pos = strpos($data['name'], chr(10));
1675                         if ($pos) {
1676                                 $data['name'] = trim(substr($data['name'], 0, $pos));
1677                         }
1678                 }
1679
1680                 $data['location'] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'p-locality')]");
1681
1682                 if ($data['location'] == '') {
1683                         $data['location'] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'location')]");
1684                 }
1685
1686                 $data['about'] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'p-note')]");
1687
1688                 if ($data['about'] == '') {
1689                         $data['about'] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'summary')]");
1690                 }
1691
1692                 $avatar = $xpath->query("//img[contains(@class, 'u-photo')]")->item(0);
1693                 if (!$avatar) {
1694                         $avatar = $xpath->query("//img[@class='img-rounded media-object']")->item(0);
1695                 }
1696                 if ($avatar) {
1697                         foreach ($avatar->attributes as $attribute) {
1698                                 if (($attribute->name == 'src') && !empty($attribute->value)) {
1699                                         $data['photo'] = Network::addBasePath($attribute->value, $baseurl);
1700                                 }
1701                         }
1702                 }
1703
1704                 return $data;
1705         }
1706
1707         /**
1708          * Check for pump.io contact
1709          *
1710          * @param array  $webfinger Webfinger data
1711          * @param string $addr
1712          *
1713          * @return array pump.io data
1714          */
1715         private static function pumpio(array $webfinger, string $addr, string $baseurl): array
1716         {
1717                 $data = [];
1718                 // The array is reversed to take into account the order of preference for same-rel links
1719                 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1720                 foreach (array_reverse($webfinger['links']) as $link) {
1721                         if (($link['rel'] == 'http://webfinger.net/rel/profile-page')
1722                                 && (($link['type'] ?? '') == 'text/html')
1723                                 && ($link['href'] != '')
1724                         ) {
1725                                 $data['url'] = $link['href'];
1726                         } elseif (($link['rel'] == 'activity-inbox') && ($link['href'] != '')) {
1727                                 $data['notify'] = $link['href'];
1728                         } elseif (($link['rel'] == 'activity-outbox') && ($link['href'] != '')) {
1729                                 $data['poll'] = $link['href'];
1730                         } elseif (($link['rel'] == 'dialback') && ($link['href'] != '')) {
1731                                 $data['dialback'] = $link['href'];
1732                         }
1733                 }
1734                 if (isset($data['poll']) && isset($data['notify'])
1735                         && isset($data['dialback'])
1736                         && isset($data['url'])
1737                 ) {
1738                         // by now we use these fields only for the network type detection
1739                         // So we unset all data that isn't used at the moment
1740                         unset($data['dialback']);
1741
1742                         $data['network'] = Protocol::PUMPIO;
1743                 } else {
1744                         return [];
1745                 }
1746
1747                 $profile_data = self::pumpioProfileData($data['url'], $baseurl);
1748
1749                 if (!$profile_data) {
1750                         return [];
1751                 }
1752
1753                 $data = array_merge($data, $profile_data);
1754
1755                 if (($addr != '') && ($data['name'] != '')) {
1756                         $name = trim(str_replace($addr, '', $data['name']));
1757                         if ($name != '') {
1758                                 $data['name'] = $name;
1759                         }
1760                 }
1761
1762                 return $data;
1763         }
1764
1765         /**
1766          * Checks HTML page for RSS feed link
1767          *
1768          * @param string $url  Page link
1769          * @param string $body Page body string
1770          *
1771          * @return string|false Feed link or false if body was invalid HTML document
1772          */
1773         public static function getFeedLink(string $url, string $body)
1774         {
1775                 if (empty($body)) {
1776                         return '';
1777                 }
1778
1779                 $doc = new DOMDocument();
1780                 if (!@$doc->loadHTML($body)) {
1781                         return false;
1782                 }
1783
1784                 $xpath = new DOMXPath($doc);
1785
1786                 $feedUrl = $xpath->evaluate('string(/html/head/link[@type="application/rss+xml" and @rel="alternate"]/@href)');
1787                 $feedUrl = $feedUrl ?: $xpath->evaluate('string(/html/head/link[@type="application/atom+xml" and @rel="alternate"]/@href)');
1788
1789                 $feedUrl = $feedUrl ? self::ensureAbsoluteLinkFromHTMLDoc($feedUrl, $url, $xpath) : '';
1790
1791                 return $feedUrl;
1792         }
1793
1794         /**
1795          * Return an absolute URL in the context of a HTML document retrieved from the provided URL.
1796          *
1797          * Loosely based on RFC 1808
1798          *
1799          * @see https://tools.ietf.org/html/rfc1808
1800          *
1801          * @param string   $href  The potential relative href found in the HTML document
1802          * @param string   $base  The HTML document URL
1803          * @param DOMXPath $xpath The HTML document XPath
1804          *
1805          * @return string Absolute URL
1806          */
1807         private static function ensureAbsoluteLinkFromHTMLDoc(string $href, string $base, DOMXPath $xpath): string
1808         {
1809                 if (filter_var($href, FILTER_VALIDATE_URL)) {
1810                         return $href;
1811                 }
1812
1813                 $base = $xpath->evaluate('string(/html/head/base/@href)') ?: $base;
1814
1815                 $baseParts = parse_url($base);
1816                 if (empty($baseParts['host'])) {
1817                         return $href;
1818                 }
1819
1820                 // Naked domain case (scheme://basehost)
1821                 $path = $baseParts['path'] ?? '/';
1822
1823                 // Remove the filename part of the path if it exists (/base/path/file)
1824                 $path = implode('/', array_slice(explode('/', $path), 0, -1));
1825
1826                 $hrefParts = parse_url($href);
1827
1828                 if (!empty($hrefParts['path'])) {
1829                         // Root path case (/path) including relative scheme case (//host/path)
1830                         if ($hrefParts['path'] && $hrefParts['path'][0] == '/') {
1831                                 $path = $hrefParts['path'];
1832                         } else {
1833                                 $path = $path . '/' . $hrefParts['path'];
1834
1835                                 // Resolve arbitrary relative path
1836                                 // Lifted from https://www.php.net/manual/en/function.realpath.php#84012
1837                                 $parts = array_filter(explode('/', $path), 'strlen');
1838                                 $absolutes = [];
1839                                 foreach ($parts as $part) {
1840                                         if ('.' == $part) continue;
1841                                         if ('..' == $part) {
1842                                                 array_pop($absolutes);
1843                                         } else {
1844                                                 $absolutes[] = $part;
1845                                         }
1846                                 }
1847
1848                                 $path = '/' . implode('/', $absolutes);
1849                         }
1850                 }
1851
1852                 // Relative scheme case (//host/path)
1853                 $baseParts['host'] = $hrefParts['host'] ?? $baseParts['host'];
1854                 $baseParts['path'] = $path;
1855                 unset($baseParts['query']);
1856                 unset($baseParts['fragment']);
1857
1858                 return Network::unparseURL($baseParts);
1859         }
1860
1861         /**
1862          * Check for feed contact
1863          *
1864          * @param string  $url   Profile link
1865          * @param boolean $probe Do a probe if the page contains a feed link
1866          *
1867          * @return array feed data
1868          * @throws HTTPException\InternalServerErrorException
1869          */
1870         private static function feed(string $url, bool $probe = true): array
1871         {
1872                 try {
1873                         $curlResult = DI::httpClient()->get($url, HttpClientAccept::FEED_XML);
1874                 } catch(\Throwable $e) {
1875                         DI::logger()->info('Error requesting feed URL', ['url' => $url, 'exception' => $e]);
1876                         return [];
1877                 }
1878
1879                 if ($curlResult->isTimeout()) {
1880                         self::$isTimeout = true;
1881                         return [];
1882                 }
1883
1884                 $feed = $curlResult->getBody();
1885                 $feed_data = Feed::import($feed);
1886
1887                 if (!$feed_data) {
1888                         if (!$probe) {
1889                                 return [];
1890                         }
1891
1892                         $feed_url = self::getFeedLink($url, $feed);
1893
1894                         if (!$feed_url) {
1895                                 return [];
1896                         }
1897
1898                         return self::feed($feed_url, false);
1899                 }
1900
1901                 if (!empty($feed_data['header']['author-name'])) {
1902                         $data['name'] = $feed_data['header']['author-name'];
1903                 }
1904
1905                 if (!empty($feed_data['header']['author-nick'])) {
1906                         $data['nick'] = $feed_data['header']['author-nick'];
1907                 }
1908
1909                 if (!empty($feed_data['header']['author-avatar'])) {
1910                         $data['photo'] = $feed_data['header']['author-avatar'];
1911                 }
1912
1913                 if (!empty($feed_data['header']['author-id'])) {
1914                         $data['alias'] = $feed_data['header']['author-id'];
1915                 }
1916
1917                 $data['url'] = $url;
1918                 $data['poll'] = $url;
1919
1920                 $data['network'] = Protocol::FEED;
1921
1922                 return $data;
1923         }
1924
1925         /**
1926          * Check for mail contact
1927          *
1928          * @param string  $uri Profile link
1929          * @param integer $uid User ID
1930          *
1931          * @return array mail data
1932          * @throws \Exception
1933          */
1934         private static function mail(string $uri, int $uid): array
1935         {
1936                 if (!Network::isEmailDomainValid($uri)) {
1937                         return [];
1938                 }
1939
1940                 if ($uid == 0) {
1941                         return [];
1942                 }
1943
1944                 $user = DBA::selectFirst('user', ['prvkey'], ['uid' => $uid]);
1945
1946                 $condition = ["`uid` = ? AND `server` != ''", $uid];
1947                 $fields = ['pass', 'user', 'server', 'port', 'ssltype', 'mailbox'];
1948                 $mailacct = DBA::selectFirst('mailacct', $fields, $condition);
1949
1950                 if (!DBA::isResult($user) || !DBA::isResult($mailacct)) {
1951                         return [];
1952                 }
1953
1954                 $mailbox = Email::constructMailboxName($mailacct);
1955                 $password = '';
1956                 openssl_private_decrypt(hex2bin($mailacct['pass']), $password, $user['prvkey']);
1957                 $mbox = Email::connect($mailbox, $mailacct['user'], $password);
1958                 if (!$mbox) {
1959                         return [];
1960                 }
1961
1962                 $msgs = Email::poll($mbox, $uri);
1963                 Logger::info('Messages found', ['uri' => $uri, 'count' => count($msgs)]);
1964
1965                 if (!count($msgs)) {
1966                         return [];
1967                 }
1968
1969                 $phost = substr($uri, strpos($uri, '@') + 1);
1970
1971                 $data = [
1972                         'addr'    => $uri,
1973                         'network' => Protocol::MAIL,
1974                         'name'    => substr($uri, 0, strpos($uri, '@')),
1975                         'photo'   => Network::lookupAvatarByEmail($uri),
1976                         'url'     => 'mailto:' . $uri,
1977                         'notify'  => 'smtp ' . Strings::getRandomHex(),
1978                         'poll'    => 'email ' . Strings::getRandomHex(),
1979                 ];
1980
1981                 $data['nick']    = $data['name'];
1982
1983                 $x = Email::messageMeta($mbox, $msgs[0]);
1984
1985                 if (stristr($x[0]->from, $uri)) {
1986                         $adr = imap_rfc822_parse_adrlist($x[0]->from, '');
1987                 } elseif (stristr($x[0]->to, $uri)) {
1988                         $adr = imap_rfc822_parse_adrlist($x[0]->to, '');
1989                 }
1990
1991                 if (isset($adr)) {
1992                         foreach ($adr as $feadr) {
1993                                 if ((strcasecmp($feadr->mailbox, $data['name']) == 0)
1994                                         &&(strcasecmp($feadr->host, $phost) == 0)
1995                                         && (strlen($feadr->personal))
1996                                 ) {
1997                                         $personal = imap_mime_header_decode($feadr->personal);
1998                                         $data['name'] = '';
1999                                         foreach ($personal as $perspart) {
2000                                                 if ($perspart->charset != 'default') {
2001                                                         $data['name'] .= iconv($perspart->charset, 'UTF-8//IGNORE', $perspart->text);
2002                                                 } else {
2003                                                         $data['name'] .= $perspart->text;
2004                                                 }
2005                                         }
2006                                 }
2007                         }
2008                 }
2009
2010                 if (!empty($mbox)) {
2011                         imap_close($mbox);
2012                 }
2013
2014                 return $data;
2015         }
2016
2017         /**
2018          * Mix two paths together to possibly fix missing parts
2019          *
2020          * @param string $avatar Path to the avatar
2021          * @param string $base   Another path that is hopefully complete
2022          *
2023          * @return string fixed avatar path
2024          * @throws \Exception
2025          */
2026         public static function fixAvatar(string $avatar, string $base): string
2027         {
2028                 $base_parts = parse_url($base);
2029
2030                 // Remove all parts that could create a problem
2031                 unset($base_parts['path']);
2032                 unset($base_parts['query']);
2033                 unset($base_parts['fragment']);
2034
2035                 $avatar_parts = parse_url($avatar);
2036
2037                 // Now we mix them
2038                 $parts = array_merge($base_parts, $avatar_parts);
2039
2040                 // And put them together again
2041                 $scheme   = isset($parts['scheme'])   ? $parts['scheme'] . '://' : '';
2042                 $host     = isset($parts['host'])     ? $parts['host']           : '';
2043                 $port     = isset($parts['port'])     ? ':' . $parts['port']     : '';
2044                 $path     = isset($parts['path'])     ? $parts['path']           : '';
2045                 $query    = isset($parts['query'])    ? '?' . $parts['query']    : '';
2046                 $fragment = isset($parts['fragment']) ? '#' . $parts['fragment'] : '';
2047
2048                 $fixed = $scheme.$host.$port.$path.$query.$fragment;
2049
2050                 Logger::debug('Avatar fixed', ['base' => $base, 'avatar' => $avatar, 'fixed' => $fixed]);
2051
2052                 return $fixed;
2053         }
2054
2055         /**
2056          * Fetch the last date that the contact had posted something (publically)
2057          *
2058          * @param array $data  probing result
2059          *
2060          * @return string last activity
2061          */
2062         public static function getLastUpdate(array $data): string
2063         {
2064                 $uid = User::getIdForURL($data['url']);
2065                 if (!empty($uid)) {
2066                         $contact = Contact::selectFirst(['url', 'last-item'], ['self' => true, 'uid' => $uid]);
2067                         if (!empty($contact['last-item'])) {
2068                                 return $contact['last-item'];
2069                         }
2070                 }
2071
2072                 if ($lastUpdate = self::updateFromNoScrape($data)) {
2073                         return $lastUpdate;
2074                 }
2075
2076                 if (!empty($data['outbox'])) {
2077                         return self::updateFromOutbox($data['outbox'], $data);
2078                 } elseif (!empty($data['poll']) && ($data['network'] == Protocol::ACTIVITYPUB)) {
2079                         return self::updateFromOutbox($data['poll'], $data);
2080                 } elseif (!empty($data['poll'])) {
2081                         return self::updateFromFeed($data);
2082                 }
2083
2084                 return '';
2085         }
2086
2087         /**
2088          * Fetch the last activity date from the "noscrape" endpoint
2089          *
2090          * @param array $data Probing result
2091          *
2092          * @return string last activity or true if update was successful or the server was unreachable
2093          */
2094         private static function updateFromNoScrape(array $data): string
2095         {
2096                 if (empty($data['baseurl'])) {
2097                         return '';
2098                 }
2099
2100                 // Check the 'noscrape' endpoint when it is a Friendica server
2101                 $gserver = DBA::selectFirst('gserver', ['noscrape'], ["`nurl` = ? AND `noscrape` != ''",
2102                         Strings::normaliseLink($data['baseurl'])]);
2103                 if (!DBA::isResult($gserver)) {
2104                         return '';
2105                 }
2106
2107                 $curlResult = DI::httpClient()->get($gserver['noscrape'] . '/' . $data['nick'], HttpClientAccept::JSON);
2108
2109                 if ($curlResult->isSuccess() && !empty($curlResult->getBody())) {
2110                         $noscrape = json_decode($curlResult->getBody(), true);
2111                         if (!empty($noscrape) && !empty($noscrape['updated'])) {
2112                                 return DateTimeFormat::utc($noscrape['updated'], DateTimeFormat::MYSQL);
2113                         }
2114                 }
2115
2116                 return '';
2117         }
2118
2119         /**
2120          * Fetch the last activity date from an ActivityPub Outbox
2121          *
2122          * @param string $feed
2123          * @param array  $data Probing result
2124          *
2125          * @return string last activity
2126          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2127          */
2128         private static function updateFromOutbox(string $feed, array $data): string
2129         {
2130                 $outbox = ActivityPub::fetchContent($feed);
2131                 if (empty($outbox)) {
2132                         return '';
2133                 }
2134
2135                 if (!empty($outbox['orderedItems'])) {
2136                         $items = $outbox['orderedItems'];
2137                 } elseif (!empty($outbox['first']['orderedItems'])) {
2138                         $items = $outbox['first']['orderedItems'];
2139                 } elseif (!empty($outbox['first']['href']) && ($outbox['first']['href'] != $feed)) {
2140                         return self::updateFromOutbox($outbox['first']['href'], $data);
2141                 } elseif (!empty($outbox['first'])) {
2142                         if (is_string($outbox['first']) && ($outbox['first'] != $feed)) {
2143                                 return self::updateFromOutbox($outbox['first'], $data);
2144                         } else {
2145                                 Logger::warning('Unexpected data', ['outbox' => $outbox]);
2146                         }
2147                         return '';
2148                 } else {
2149                         $items = [];
2150                 }
2151
2152                 $last_updated = '';
2153                 foreach ($items as $activity) {
2154                         if (!empty($activity['published'])) {
2155                                 $published =  DateTimeFormat::utc($activity['published']);
2156                         } elseif (!empty($activity['object']['published'])) {
2157                                 $published =  DateTimeFormat::utc($activity['object']['published']);
2158                         } else {
2159                                 continue;
2160                         }
2161
2162                         if ($last_updated < $published) {
2163                                 $last_updated = $published;
2164                         }
2165                 }
2166
2167                 if (!empty($last_updated)) {
2168                         return $last_updated;
2169                 }
2170
2171                 return '';
2172         }
2173
2174         /**
2175          * Fetch the last activity date from an XML feed
2176          *
2177          * @param array $data Probing result
2178          * @return string last activity
2179          */
2180         private static function updateFromFeed(array $data): string
2181         {
2182                 // Search for the newest entry in the feed
2183                 $curlResult = DI::httpClient()->get($data['poll'], HttpClientAccept::ATOM_XML);
2184                 if (!$curlResult->isSuccess() || !$curlResult->getBody()) {
2185                         return '';
2186                 }
2187
2188                 $doc = new DOMDocument();
2189                 @$doc->loadXML($curlResult->getBody());
2190
2191                 $xpath = new DOMXPath($doc);
2192                 $xpath->registerNamespace('atom', 'http://www.w3.org/2005/Atom');
2193
2194                 $entries = $xpath->query('/atom:feed/atom:entry');
2195
2196                 $last_updated = '';
2197
2198                 foreach ($entries as $entry) {
2199                         $published_item = $xpath->query('atom:published/text()', $entry)->item(0);
2200                         $updated_item   = $xpath->query('atom:updated/text()'  , $entry)->item(0);
2201                         $published      = !empty($published_item->nodeValue) ? DateTimeFormat::utc($published_item->nodeValue) : null;
2202                         $updated        = !empty($updated_item->nodeValue) ? DateTimeFormat::utc($updated_item->nodeValue) : null;
2203
2204                         if (empty($published) || empty($updated)) {
2205                                 Logger::notice('Invalid entry for XPath.', ['entry' => $entry, 'url' => $data['url']]);
2206                                 continue;
2207                         }
2208
2209                         if ($last_updated < $published) {
2210                                 $last_updated = $published;
2211                         }
2212
2213                         if ($last_updated < $updated) {
2214                                 $last_updated = $updated;
2215                         }
2216                 }
2217
2218                 if (!empty($last_updated)) {
2219                         return $last_updated;
2220                 }
2221
2222                 return '';
2223         }
2224
2225         /**
2226          * Probe data from local profiles without network traffic
2227          *
2228          * @param string $url
2229          *
2230          * @return array probed data
2231          * @throws HTTPException\InternalServerErrorException
2232          * @throws HTTPException\NotFoundException
2233          */
2234         private static function localProbe(string $url): array
2235         {
2236                 try {
2237                         $uid = User::getIdForURL($url);
2238                         if (!$uid) {
2239                                 throw new HTTPException\NotFoundException('User not found.');
2240                         }
2241
2242                         $owner     = User::getOwnerDataById($uid);
2243                         $approfile = ActivityPub\Transmitter::getProfile($uid);
2244
2245                         $split_name = Diaspora::splitName($owner['name']);
2246
2247                         if (empty($owner['gsid'])) {
2248                                 $owner['gsid'] = GServer::getID($approfile['generator']['url']);
2249                         }
2250
2251                         $data = [
2252                                 'name'             => $owner['name'], 'nick' => $owner['nick'], 'guid' => $approfile['diaspora:guid'] ?? '',
2253                                 'url'              => $owner['url'], 'addr' => $owner['addr'], 'alias' => $owner['alias'],
2254                                 'photo'            => User::getAvatarUrl($owner),
2255                                 'header'           => $owner['header'] ? Contact::getHeaderUrlForId($owner['id'], $owner['updated']) : '',
2256                                 'account-type'     => $owner['contact-type'], 'community' => ($owner['contact-type'] == User::ACCOUNT_TYPE_COMMUNITY),
2257                                 'keywords'         => $owner['keywords'], 'location' => $owner['location'], 'about' => $owner['about'],
2258                                 'xmpp'             => $owner['xmpp'], 'matrix' => $owner['matrix'],
2259                                 'hide'             => !$owner['net-publish'], 'batch' => '', 'notify' => $owner['notify'],
2260                                 'poll'             => $owner['poll'], 'request' => $owner['request'], 'confirm' => $owner['confirm'],
2261                                 'subscribe'        => $approfile['generator']['url'] . '/contact/follow?url={uri}', 'poco' => $owner['poco'],
2262                                 'following'        => $approfile['following'], 'followers' => $approfile['followers'],
2263                                 'inbox'            => $approfile['inbox'], 'outbox' => $approfile['outbox'],
2264                                 'sharedinbox'      => $approfile['endpoints']['sharedInbox'], 'network' => Protocol::DFRN,
2265                                 'pubkey'           => $owner['upubkey'], 'baseurl' => $approfile['generator']['url'], 'gsid' => $owner['gsid'],
2266                                 'manually-approve' => in_array($owner['page-flags'], [User::PAGE_FLAGS_NORMAL, User::PAGE_FLAGS_PRVGROUP]),
2267                                 'networks' => [
2268                                         Protocol::DIASPORA => [
2269                                                 'name'         => $owner['name'],
2270                                                 'given_name'   => $split_name['first'],
2271                                                 'family_name'  => $split_name['last'],
2272                                                 'nick'         => $owner['nick'],
2273                                                 'guid'         => $approfile['diaspora:guid'],
2274                                                 'url'          => $owner['url'],
2275                                                 'addr'         => $owner['addr'],
2276                                                 'alias'        => $owner['alias'],
2277                                                 'photo'        => $owner['photo'],
2278                                                 'photo_medium' => $owner['thumb'],
2279                                                 'photo_small'  => $owner['micro'],
2280                                                 'batch'        => $approfile['generator']['url'] . '/receive/public',
2281                                                 'notify'       => $owner['notify'],
2282                                                 'poll'         => $owner['poll'],
2283                                                 'poco'         => $owner['poco'],
2284                                                 'network'      => Protocol::DIASPORA,
2285                                                 'pubkey'       => $owner['upubkey'],
2286                                         ]
2287                                 ]
2288                         ];
2289                 } catch (Exception $e) {
2290                         // Default values for nonexistent targets
2291                         $data = [
2292                                 'name' => $url, 'nick' => $url, 'url' => $url, 'network' => Protocol::PHANTOM,
2293                                 'photo' => DI::baseUrl() . Contact::DEFAULT_AVATAR_PHOTO
2294                         ];
2295                 }
2296
2297                 return self::rearrangeData($data);
2298         }
2299 }