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