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