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