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