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