]> git.mxchange.org Git - friendica.git/blob - src/Network/Probe.php
Merge pull request #8978 from annando/contact-update
[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\Cache\Duration;
27 use Friendica\Core\Hook;
28 use Friendica\Core\Logger;
29 use Friendica\Core\Protocol;
30 use Friendica\Core\System;
31 use Friendica\Database\DBA;
32 use Friendica\DI;
33 use Friendica\Model\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, $cache = true)
332         {
333                 $cachekey = 'Probe::uri:' . $network . ':' . $uri;
334                 if ($cache) {
335                         $result = DI::cache()->get($cachekey);
336                         if (!is_null($result)) {
337                                 return $result;
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                 $data = self::rearrangeData($data);
412
413                 // Only store into the cache if the value seems to be valid
414                 if (!in_array($data['network'], [Protocol::PHANTOM, Protocol::MAIL])) {
415                         DI::cache()->set($cachekey, $data, Duration::DAY);
416                 }
417
418                 return $data;
419         }
420
421
422         /**
423          * Fetches the "hide" status from the profile
424          *
425          * @param string $url URL of the profile
426          *
427          * @return boolean "hide" status
428          */
429         private static function getHideStatus($url)
430         {
431                 $curlResult = DI::httpRequest()->get($url);
432                 if (!$curlResult->isSuccess()) {
433                         return false;
434                 }
435
436                 // If the file is too large then exit
437                 if (($curlResult->getInfo()['download_content_length'] ?? 0) > 1000000) {
438                         return false;
439                 }
440
441                 // If it isn't a HTML file then exit
442                 if (($curlResult->getContentType() != '') && !strstr(strtolower($curlResult->getContentType()), 'html')) {
443                         return false;
444                 }
445
446                 $body = $curlResult->getBody();
447
448                 $doc = new DOMDocument();
449                 @$doc->loadHTML($body);
450
451                 $xpath = new DOMXPath($doc);
452
453                 $list = $xpath->query('//meta[@name]');
454                 foreach ($list as $node) {
455                         $meta_tag = [];
456                         if ($node->attributes->length) {
457                                 foreach ($node->attributes as $attribute) {
458                                         $meta_tag[$attribute->name] = $attribute->value;
459                                 }
460                         }
461
462                         if (empty($meta_tag['content'])) {
463                                 continue;
464                         }
465
466                         $content = strtolower(trim($meta_tag['content']));
467
468                         switch (strtolower(trim($meta_tag['name']))) {
469                                 case 'dfrn-global-visibility':
470                                         if ($content == 'false') {
471                                                 return true;
472                                         }
473                                         break;
474                                 case 'robots':
475                                         if (strpos($content, 'noindex') !== false) {
476                                                 return true;
477                                         }
478                                         break;
479                         }
480                 }
481
482                 return false;
483         }
484
485         /**
486          * Fetch the "subscribe" and add it to the result
487          *
488          * @param array $result
489          * @param array $webfinger
490          * @return array result
491          */
492         private static function getSubscribeLink(array $result, array $webfinger)
493         {
494                 if (empty($webfinger['links'])) {
495                         return $result;
496                 }
497
498                 foreach ($webfinger['links'] as $link) {
499                         if (!empty($link['template']) && ($link['rel'] === ActivityNamespace::OSTATUSSUB)) {
500                                 $result['subscribe'] = $link['template'];
501                         }
502                 }
503
504                 return $result;
505         }
506
507         /**
508          * Get webfinger data from a given URI
509          *
510          * @param string $uri
511          * @return array Webfinger array
512          */
513         private static function getWebfingerArray(string $uri)
514         {
515                 $parts = parse_url($uri);
516
517                 if (!empty($parts['scheme']) && !empty($parts['host'])) {
518                         $host = $parts['host'];
519                         if (!empty($parts['port'])) {
520                                 $host .= ':'.$parts['port'];
521                         }
522
523                         $baseurl = $parts['scheme'] . '://' . $host;
524
525                         $nick = '';
526                         $addr = '';
527
528                         $path_parts = explode("/", trim($parts['path'] ?? '', "/"));
529                         if (!empty($path_parts)) {
530                                 $nick = ltrim(end($path_parts), '@');
531                                 // When the last part of the URI is numeric then it is most likely an ID and not a nick name
532                                 if (!is_numeric($nick)) {
533                                         $addr = $nick."@".$host;
534                                 } else {
535                                         $nick = '';
536                                 }
537                         }
538
539                         $webfinger = self::getWebfinger($parts['scheme'] . '://' . $host . self::WEBFINGER, 'application/jrd+json', $uri, $addr);
540                         if (empty($webfinger)) {
541                                 $lrdd = self::hostMeta($host);
542                         }
543
544                         if (empty($webfinger) && empty($lrdd)) {
545                                 while (empty($lrdd) && empty($webfinger) && (sizeof($path_parts) > 1)) {
546                                         $host .= "/".array_shift($path_parts);
547                                         $baseurl = $parts['scheme'] . '://' . $host;
548
549                                         if (!empty($nick)) {
550                                                 $addr = $nick."@".$host;
551                                         }
552
553                                         $webfinger = self::getWebfinger($parts['scheme'] . '://' . $host . self::WEBFINGER, 'application/jrd+json', $uri, $addr);
554                                         if (empty($webfinger)) {
555                                                 $lrdd = self::hostMeta($host);
556                                         }
557                                 }
558
559                                 if (empty($lrdd) && empty($webfinger)) {
560                                         return [];
561                                 }
562                         }
563                 } elseif (strstr($uri, '@')) {
564                         // Remove "acct:" from the URI
565                         $uri = str_replace('acct:', '', $uri);
566
567                         $host = substr($uri, strpos($uri, '@') + 1);
568                         $nick = substr($uri, 0, strpos($uri, '@'));
569                         $addr = $uri;
570
571                         $webfinger = self::getWebfinger('https://' . $host . self::WEBFINGER, 'application/jrd+json', $uri, $addr);
572                         if (self::$istimeout) {
573                                 return [];
574                         }
575
576                         if (empty($webfinger)) {
577                                 $webfinger = self::getWebfinger('http://' . $host . self::WEBFINGER, 'application/jrd+json', $uri, $addr);
578                                 if (self::$istimeout) {
579                                         return [];
580                                 }
581                         } else {
582                                 $baseurl = 'https://' . $host;
583                         }
584
585                         if (empty($webfinger)) {
586                                 $lrdd = self::hostMeta($host);
587                                 if (self::$istimeout) {
588                                         return [];
589                                 }
590                                 $baseurl = self::$baseurl;
591                         } else {
592                                 $baseurl = 'http://' . $host;
593                         }
594                 } else {
595                         Logger::info('URI was not detectable', ['uri' => $uri]);
596                         return [];
597                 }
598
599                 if (empty($webfinger)) {
600                         foreach ($lrdd as $type => $template) {
601                                 if ($webfinger) {
602                                         continue;
603                                 }
604
605                                 $webfinger = self::getWebfinger($template, $type, $uri, $addr);
606                         }
607                 }
608
609                 if (empty($webfinger)) {
610                         return [];
611                 }
612
613                 if ($webfinger['detected'] == $addr) {
614                         $webfinger['nick'] = $nick;
615                         $webfinger['addr'] = $addr;
616                 }
617
618                 $webfinger['baseurl'] = $baseurl;
619
620                 return $webfinger;
621         }
622
623         /**
624          * Perform network request for webfinger data
625          *
626          * @param string $template
627          * @param string $type
628          * @param string $uri
629          * @param string $addr
630          * @return array webfinger results
631          */
632         private static function getWebfinger(string $template, string $type, string $uri, string $addr)
633         {
634                 // First try the address because this is the primary purpose of webfinger
635                 if (!empty($addr)) {
636                         $detected = $addr;
637                         $path = str_replace('{uri}', urlencode("acct:" . $addr), $template);
638                         $webfinger = self::webfinger($path, $type);
639                         if (self::$istimeout) {
640                                 return [];
641                         }
642                 }
643
644                 // Then try the URI
645                 if (empty($webfinger) && $uri != $addr) {
646                         $detected = $uri;
647                         $path = str_replace('{uri}', urlencode($uri), $template);
648                         $webfinger = self::webfinger($path, $type);
649                         if (self::$istimeout) {
650                                 return [];
651                         }
652                 }
653
654                 if (empty($webfinger)) {
655                         return [];
656                 }
657
658                 return ['webfinger' => $webfinger, 'detected' => $detected];
659         }
660
661         /**
662          * Fetch information (protocol endpoints and user information) about a given uri
663          *
664          * This function is only called by the "uri" function that adds caching and rearranging of data.
665          *
666          * @param string  $uri        Address that should be probed
667          * @param string  $network    Test for this specific network
668          * @param integer $uid        User ID for the probe (only used for mails)
669          * @param array   $ap_profile Previously probed AP profile
670          *
671          * @return array uri data
672          * @throws HTTPException\InternalServerErrorException
673          */
674         private static function detect(string $uri, string $network, int $uid, array $ap_profile)
675         {
676                 $hookData = [
677                         'uri'     => $uri,
678                         'network' => $network,
679                         'uid'     => $uid,
680                         'result'  => [],
681                 ];
682
683                 Hook::callAll('probe_detect', $hookData);
684
685                 if ($hookData['result']) {
686                         if (!is_array($hookData['result'])) {
687                                 return [];
688                         } else {
689                                 return $hookData['result'];
690                         }
691                 }
692
693                 $parts = parse_url($uri);
694
695                 if (!empty($parts['scheme']) && !empty($parts['host'])) {
696                         if (in_array($parts['host'], ['twitter.com', 'mobile.twitter.com'])) {
697                                 return self::twitter($uri);
698                         }
699                 } elseif (strstr($uri, '@')) {
700                         // If the URI starts with "mailto:" then jump directly to the mail detection
701                         if (strpos($uri, 'mailto:') !== false) {
702                                 $uri = str_replace('mailto:', '', $uri);
703                                 return self::mail($uri, $uid);
704                         }
705
706                         if ($network == Protocol::MAIL) {
707                                 return self::mail($uri, $uid);
708                         }
709
710                         if (Strings::endsWith($uri, '@twitter.com')
711                                 || Strings::endsWith($uri, '@mobile.twitter.com')
712                         ) {
713                                 return self::twitter($uri);
714                         }
715                 } else {
716                         Logger::info('URI was not detectable', ['uri' => $uri]);
717                         return [];
718                 }
719
720                 Logger::info('Probing start', ['uri' => $uri]);
721
722                 $data = self::getWebfingerArray($uri);
723                 if (empty($data)) {
724                         if (!empty($parts['scheme'])) {
725                                 return self::feed($uri);
726                         } elseif (!empty($uid)) {
727                                 return self::mail($uri, $uid);
728                         } else {
729                                 return [];
730                         }
731                 }
732
733                 $webfinger = $data['webfinger'];
734                 $nick = $data['nick'] ?? '';
735                 $addr = $data['addr'] ?? '';
736                 $baseurl = $data['baseurl'] ?? '';
737
738                 $result = [];
739
740                 if (in_array($network, ["", Protocol::DFRN])) {
741                         $result = self::dfrn($webfinger);
742                 }
743                 if ((!$result && ($network == "")) || ($network == Protocol::DIASPORA)) {
744                         $result = self::diaspora($webfinger);
745                 }
746                 if ((!$result && ($network == "")) || ($network == Protocol::OSTATUS)) {
747                         $result = self::ostatus($webfinger);
748                 }
749                 if (in_array($network, ['', Protocol::ZOT])) {
750                         $result = self::zot($webfinger, $result, $baseurl);
751                 }
752                 if ((!$result && ($network == "")) || ($network == Protocol::PUMPIO)) {
753                         $result = self::pumpio($webfinger, $addr);
754                 }
755                 if (empty($result['network']) && empty($ap_profile['network']) || ($network == Protocol::FEED)) {
756                         $result = self::feed($uri);
757                 } else {
758                         // We overwrite the detected nick with our try if the previois routines hadn't detected it.
759                         // Additionally it is overwritten when the nickname doesn't make sense (contains spaces).
760                         if ((empty($result["nick"]) || (strstr($result["nick"], " "))) && ($nick != "")) {
761                                 $result["nick"] = $nick;
762                         }
763
764                         if (empty($result["addr"]) && ($addr != "")) {
765                                 $result["addr"] = $addr;
766                         }
767                 }
768
769                 $result = self::getSubscribeLink($result, $webfinger);
770
771                 if (empty($result["network"])) {
772                         $result["network"] = Protocol::PHANTOM;
773                 }
774
775                 if (empty($result['baseurl']) && !empty($baseurl)) {
776                         $result['baseurl'] = $baseurl;
777                 }
778
779                 if (empty($result["url"])) {
780                         $result["url"] = $uri;
781                 }
782
783                 Logger::info('Probing done', ['uri' => $uri, 'network' => $result["network"]]);
784
785                 return $result;
786         }
787
788         /**
789          * Check for Zot contact
790          *
791          * @param array $webfinger Webfinger data
792          * @param array $data      previously probed data
793          *
794          * @return array Zot data
795          * @throws HTTPException\InternalServerErrorException
796          */
797         private static function zot($webfinger, $data, $baseurl)
798         {
799                 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
800                         foreach ($webfinger["aliases"] as $alias) {
801                                 if (substr($alias, 0, 5) == 'acct:') {
802                                         $data["addr"] = substr($alias, 5);
803                                 }
804                         }
805                 }
806
807                 if (!empty($webfinger["subject"]) && (substr($webfinger["subject"], 0, 5) == "acct:")) {
808                         $data["addr"] = substr($webfinger["subject"], 5);
809                 }
810
811                 $zot_url = '';
812                 foreach ($webfinger['links'] as $link) {
813                         if (($link['rel'] == 'http://purl.org/zot/protocol') && !empty($link['href'])) {
814                                 $zot_url = $link['href'];
815                         }
816                 }
817
818                 if (empty($zot_url) && !empty($data['addr']) && !empty($baseurl)) {
819                         $condition = ['nurl' => Strings::normaliseLink($baseurl), 'platform' => ['hubzilla']];
820                         if (!DBA::exists('gserver', $condition)) {
821                                 return $data;
822                         }
823                         $zot_url = $baseurl . '/.well-known/zot-info?address=' . $data['addr'];
824                 }
825
826                 if (empty($zot_url)) {
827                         return $data;
828                 }
829
830                 $data = self::pollZot($zot_url, $data);
831
832                 if (!empty($data['url']) && !empty($webfinger['aliases']) && is_array($webfinger['aliases'])) {
833                         foreach ($webfinger['aliases'] as $alias) {
834                                 if (!strstr($alias, '@') && Strings::normaliseLink($alias) != Strings::normaliseLink($data['url'])) {
835                                         $data['alias'] = $alias;
836                                 }
837                         }
838                 }
839
840                 return $data;
841         }
842
843         public static function pollZot($url, $data)
844         {
845                 $curlResult = DI::httpRequest()->get($url);
846                 if ($curlResult->isTimeout()) {
847                         return $data;
848                 }
849                 $content = $curlResult->getBody();
850                 if (!$content) {
851                         return $data;
852                 }
853
854                 $json = json_decode($content, true);
855                 if (!is_array($json)) {
856                         return $data;
857                 }
858
859                 if (empty($data['network'])) {
860                         if (!empty($json['protocols']) && in_array('zot', $json['protocols'])) {
861                                 $data['network'] = Protocol::ZOT;
862                         } elseif (!isset($json['protocols'])) {
863                                 $data['network'] = Protocol::ZOT;
864                         }
865                 }
866
867                 if (!empty($json['guid']) && empty($data['guid'])) {
868                         $data['guid'] = $json['guid'];
869                 }
870                 if (!empty($json['key']) && empty($data['pubkey'])) {
871                         $data['pubkey'] = $json['key'];
872                 }
873                 if (!empty($json['name'])) {
874                         $data['name'] = $json['name'];
875                 }
876                 if (!empty($json['photo'])) {
877                         $data['photo'] = $json['photo'];
878                         if (!empty($json['photo_updated'])) {
879                                 $data['photo'] .= '?rev=' . urlencode($json['photo_updated']);
880                         }
881                 }
882                 if (!empty($json['address'])) {
883                         $data['addr'] = $json['address'];
884                 }
885                 if (!empty($json['url'])) {
886                         $data['url'] = $json['url'];
887                 }
888                 if (!empty($json['connections_url'])) {
889                         $data['poco'] = $json['connections_url'];
890                 }
891                 if (isset($json['searchable'])) {
892                         $data['hide'] = !$json['searchable'];
893                 }
894                 if (!empty($json['public_forum'])) {
895                         $data['community'] = $json['public_forum'];
896                         $data['account-type'] = User::PAGE_FLAGS_COMMUNITY;
897                 }
898
899                 if (!empty($json['profile'])) {
900                         $profile = $json['profile'];
901                         if (!empty($profile['description'])) {
902                                 $data['about'] = $profile['description'];
903                         }
904                         if (!empty($profile['keywords'])) {
905                                 $keywords = implode(', ', $profile['keywords']);
906                                 if (!empty($keywords)) {
907                                         $data['keywords'] = $keywords;
908                                 }
909                         }
910
911                         $loc = [];
912                         if (!empty($profile['region'])) {
913                                 $loc['region'] = $profile['region'];
914                         }
915                         if (!empty($profile['country'])) {
916                                 $loc['country-name'] = $profile['country'];
917                         }
918                         $location = Profile::formatLocation($loc);
919                         if (!empty($location)) {
920                                 $data['location'] = $location;
921                         }
922                 }
923
924                 return $data;
925         }
926
927         /**
928          * Perform a webfinger request.
929          *
930          * For details see RFC 7033: <https://tools.ietf.org/html/rfc7033>
931          *
932          * @param string $url  Address that should be probed
933          * @param string $type type
934          *
935          * @return array webfinger data
936          * @throws HTTPException\InternalServerErrorException
937          */
938         public static function webfinger($url, $type)
939         {
940                 $xrd_timeout = DI::config()->get('system', 'xrd_timeout', 20);
941
942                 $curlResult = DI::httpRequest()->get($url, false, ['timeout' => $xrd_timeout, 'accept_content' => $type]);
943                 if ($curlResult->isTimeout()) {
944                         self::$istimeout = true;
945                         return [];
946                 }
947                 $data = $curlResult->getBody();
948
949                 $webfinger = json_decode($data, true);
950                 if (!empty($webfinger)) {
951                         if (!isset($webfinger["links"])) {
952                                 Logger::info('No json webfinger links', ['url' => $url]);
953                                 return [];
954                         }
955                         return $webfinger;
956                 }
957
958                 // If it is not JSON, maybe it is XML
959                 $xrd = XML::parseString($data, true);
960                 if (!is_object($xrd)) {
961                         Logger::info('No webfinger data retrievable', ['url' => $url]);
962                         return [];
963                 }
964
965                 $xrd_arr = XML::elementToArray($xrd);
966                 if (!isset($xrd_arr["xrd"]["link"])) {
967                         Logger::info('No XML webfinger links', ['url' => $url]);
968                         return [];
969                 }
970
971                 $webfinger = [];
972
973                 if (!empty($xrd_arr["xrd"]["subject"])) {
974                         $webfinger["subject"] = $xrd_arr["xrd"]["subject"];
975                 }
976
977                 if (!empty($xrd_arr["xrd"]["alias"])) {
978                         $webfinger["aliases"] = $xrd_arr["xrd"]["alias"];
979                 }
980
981                 $webfinger["links"] = [];
982
983                 foreach ($xrd_arr["xrd"]["link"] as $value => $data) {
984                         if (!empty($data["@attributes"])) {
985                                 $attributes = $data["@attributes"];
986                         } elseif ($value == "@attributes") {
987                                 $attributes = $data;
988                         } else {
989                                 continue;
990                         }
991
992                         $webfinger["links"][] = $attributes;
993                 }
994                 return $webfinger;
995         }
996
997         /**
998          * Poll the Friendica specific noscrape page.
999          *
1000          * "noscrape" is a faster alternative to fetch the data from the hcard.
1001          * This functionality was originally created for the directory.
1002          *
1003          * @param string $noscrape_url Link to the noscrape page
1004          * @param array  $data         The already fetched data
1005          *
1006          * @return array noscrape data
1007          * @throws HTTPException\InternalServerErrorException
1008          */
1009         private static function pollNoscrape($noscrape_url, $data)
1010         {
1011                 $curlResult = DI::httpRequest()->get($noscrape_url);
1012                 if ($curlResult->isTimeout()) {
1013                         self::$istimeout = true;
1014                         return [];
1015                 }
1016                 $content = $curlResult->getBody();
1017                 if (!$content) {
1018                         Logger::info('Empty body', ['url' => $noscrape_url]);
1019                         return [];
1020                 }
1021
1022                 $json = json_decode($content, true);
1023                 if (!is_array($json)) {
1024                         Logger::info('No json data', ['url' => $noscrape_url]);
1025                         return [];
1026                 }
1027
1028                 if (!empty($json["fn"])) {
1029                         $data["name"] = $json["fn"];
1030                 }
1031
1032                 if (!empty($json["addr"])) {
1033                         $data["addr"] = $json["addr"];
1034                 }
1035
1036                 if (!empty($json["nick"])) {
1037                         $data["nick"] = $json["nick"];
1038                 }
1039
1040                 if (!empty($json["guid"])) {
1041                         $data["guid"] = $json["guid"];
1042                 }
1043
1044                 if (!empty($json["comm"])) {
1045                         $data["community"] = $json["comm"];
1046                 }
1047
1048                 if (!empty($json["tags"])) {
1049                         $keywords = implode(", ", $json["tags"]);
1050                         if ($keywords != "") {
1051                                 $data["keywords"] = $keywords;
1052                         }
1053                 }
1054
1055                 $location = Profile::formatLocation($json);
1056                 if ($location) {
1057                         $data["location"] = $location;
1058                 }
1059
1060                 if (!empty($json["about"])) {
1061                         $data["about"] = $json["about"];
1062                 }
1063
1064                 if (!empty($json["key"])) {
1065                         $data["pubkey"] = $json["key"];
1066                 }
1067
1068                 if (!empty($json["photo"])) {
1069                         $data["photo"] = $json["photo"];
1070                 }
1071
1072                 if (!empty($json["dfrn-request"])) {
1073                         $data["request"] = $json["dfrn-request"];
1074                 }
1075
1076                 if (!empty($json["dfrn-confirm"])) {
1077                         $data["confirm"] = $json["dfrn-confirm"];
1078                 }
1079
1080                 if (!empty($json["dfrn-notify"])) {
1081                         $data["notify"] = $json["dfrn-notify"];
1082                 }
1083
1084                 if (!empty($json["dfrn-poll"])) {
1085                         $data["poll"] = $json["dfrn-poll"];
1086                 }
1087
1088                 if (isset($json["hide"])) {
1089                         $data["hide"] = (bool)$json["hide"];
1090                 } else {
1091                         $data["hide"] = false;
1092                 }
1093
1094                 return $data;
1095         }
1096
1097         /**
1098          * Check for valid DFRN data
1099          *
1100          * @param array $data DFRN data
1101          *
1102          * @return int Number of errors
1103          */
1104         public static function validDfrn($data)
1105         {
1106                 $errors = 0;
1107                 if (!isset($data['key'])) {
1108                         $errors ++;
1109                 }
1110                 if (!isset($data['dfrn-request'])) {
1111                         $errors ++;
1112                 }
1113                 if (!isset($data['dfrn-confirm'])) {
1114                         $errors ++;
1115                 }
1116                 if (!isset($data['dfrn-notify'])) {
1117                         $errors ++;
1118                 }
1119                 if (!isset($data['dfrn-poll'])) {
1120                         $errors ++;
1121                 }
1122                 return $errors;
1123         }
1124
1125         /**
1126          * Fetch data from a DFRN profile page and via "noscrape"
1127          *
1128          * @param string $profile_link Link to the profile page
1129          *
1130          * @return array profile data
1131          * @throws HTTPException\InternalServerErrorException
1132          * @throws \ImagickException
1133          */
1134         public static function profile($profile_link)
1135         {
1136                 $data = [];
1137
1138                 Logger::info('Check profile', ['link' => $profile_link]);
1139
1140                 // Fetch data via noscrape - this is faster
1141                 $noscrape_url = str_replace(["/hcard/", "/profile/"], "/noscrape/", $profile_link);
1142                 $data = self::pollNoscrape($noscrape_url, $data);
1143
1144                 if (!isset($data["notify"])
1145                         || !isset($data["confirm"])
1146                         || !isset($data["request"])
1147                         || !isset($data["poll"])
1148                         || !isset($data["name"])
1149                         || !isset($data["photo"])
1150                 ) {
1151                         $data = self::pollHcard($profile_link, $data, true);
1152                 }
1153
1154                 $prof_data = [];
1155
1156                 if (empty($data["addr"]) || empty($data["nick"])) {
1157                         $probe_data = self::uri($profile_link);
1158                         $data["addr"] = ($data["addr"] ?? '') ?: $probe_data["addr"];
1159                         $data["nick"] = ($data["nick"] ?? '') ?: $probe_data["nick"];
1160                 }
1161
1162                 $prof_data["addr"]         = $data["addr"];
1163                 $prof_data["nick"]         = $data["nick"];
1164                 $prof_data["dfrn-request"] = $data['request'] ?? null;
1165                 $prof_data["dfrn-confirm"] = $data['confirm'] ?? null;
1166                 $prof_data["dfrn-notify"]  = $data['notify']  ?? null;
1167                 $prof_data["dfrn-poll"]    = $data['poll']    ?? null;
1168                 $prof_data["photo"]        = $data['photo']   ?? null;
1169                 $prof_data["fn"]           = $data['name']    ?? null;
1170                 $prof_data["key"]          = $data['pubkey']  ?? null;
1171
1172                 Logger::debug('Result', ['link' => $profile_link, 'data' => $prof_data]);
1173
1174                 return $prof_data;
1175         }
1176
1177         /**
1178          * Check for DFRN contact
1179          *
1180          * @param array $webfinger Webfinger data
1181          *
1182          * @return array DFRN data
1183          * @throws HTTPException\InternalServerErrorException
1184          */
1185         private static function dfrn($webfinger)
1186         {
1187                 $hcard_url = "";
1188                 $data = [];
1189                 // The array is reversed to take into account the order of preference for same-rel links
1190                 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1191                 foreach (array_reverse($webfinger["links"]) as $link) {
1192                         if (($link["rel"] == ActivityNamespace::DFRN) && !empty($link["href"])) {
1193                                 $data["network"] = Protocol::DFRN;
1194                         } elseif (($link["rel"] == ActivityNamespace::FEED) && !empty($link["href"])) {
1195                                 $data["poll"] = $link["href"];
1196                         } elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") && (($link["type"] ?? "") == "text/html") && !empty($link["href"])) {
1197                                 $data["url"] = $link["href"];
1198                         } elseif (($link["rel"] == "http://microformats.org/profile/hcard") && !empty($link["href"])) {
1199                                 $hcard_url = $link["href"];
1200                         } elseif (($link["rel"] == ActivityNamespace::POCO) && !empty($link["href"])) {
1201                                 $data["poco"] = $link["href"];
1202                         } elseif (($link["rel"] == "http://webfinger.net/rel/avatar") && !empty($link["href"])) {
1203                                 $data["photo"] = $link["href"];
1204                         } elseif (($link["rel"] == "http://joindiaspora.com/seed_location") && !empty($link["href"])) {
1205                                 $data["baseurl"] = trim($link["href"], '/');
1206                         } elseif (($link["rel"] == "http://joindiaspora.com/guid") && !empty($link["href"])) {
1207                                 $data["guid"] = $link["href"];
1208                         } elseif (($link["rel"] == "diaspora-public-key") && !empty($link["href"])) {
1209                                 $data["pubkey"] = base64_decode($link["href"]);
1210
1211                                 //if (strstr($data["pubkey"], 'RSA ') || ($link["type"] == "RSA"))
1212                                 if (strstr($data["pubkey"], 'RSA ')) {
1213                                         $data["pubkey"] = Crypto::rsaToPem($data["pubkey"]);
1214                                 }
1215                         }
1216                 }
1217
1218                 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
1219                         foreach ($webfinger["aliases"] as $alias) {
1220                                 if (empty($data["url"]) && !strstr($alias, "@")) {
1221                                         $data["url"] = $alias;
1222                                 } elseif (!strstr($alias, "@") && Strings::normaliseLink($alias) != Strings::normaliseLink($data["url"])) {
1223                                         $data["alias"] = $alias;
1224                                 } elseif (substr($alias, 0, 5) == 'acct:') {
1225                                         $data["addr"] = substr($alias, 5);
1226                                 }
1227                         }
1228                 }
1229
1230                 if (!empty($webfinger["subject"]) && (substr($webfinger["subject"], 0, 5) == "acct:")) {
1231                         $data["addr"] = substr($webfinger["subject"], 5);
1232                 }
1233
1234                 if (!isset($data["network"]) || ($hcard_url == "")) {
1235                         return [];
1236                 }
1237
1238                 // Fetch data via noscrape - this is faster
1239                 $noscrape_url = str_replace("/hcard/", "/noscrape/", $hcard_url);
1240                 $data = self::pollNoscrape($noscrape_url, $data);
1241
1242                 if (isset($data["notify"])
1243                         && isset($data["confirm"])
1244                         && isset($data["request"])
1245                         && isset($data["poll"])
1246                         && isset($data["name"])
1247                         && isset($data["photo"])
1248                 ) {
1249                         return $data;
1250                 }
1251
1252                 $data = self::pollHcard($hcard_url, $data, true);
1253
1254                 return $data;
1255         }
1256
1257         /**
1258          * Poll the hcard page (Diaspora and Friendica specific)
1259          *
1260          * @param string  $hcard_url Link to the hcard page
1261          * @param array   $data      The already fetched data
1262          * @param boolean $dfrn      Poll DFRN specific data
1263          *
1264          * @return array hcard data
1265          * @throws HTTPException\InternalServerErrorException
1266          */
1267         private static function pollHcard($hcard_url, $data, $dfrn = false)
1268         {
1269                 $curlResult = DI::httpRequest()->get($hcard_url);
1270                 if ($curlResult->isTimeout()) {
1271                         self::$istimeout = true;
1272                         return [];
1273                 }
1274                 $content = $curlResult->getBody();
1275                 if (!$content) {
1276                         return [];
1277                 }
1278
1279                 $doc = new DOMDocument();
1280                 if (!@$doc->loadHTML($content)) {
1281                         return [];
1282                 }
1283
1284                 $xpath = new DomXPath($doc);
1285
1286                 $vcards = $xpath->query("//div[contains(concat(' ', @class, ' '), ' vcard ')]");
1287                 if (!is_object($vcards)) {
1288                         return [];
1289                 }
1290
1291                 if (!isset($data["baseurl"])) {
1292                         $data["baseurl"] = "";
1293                 }
1294
1295                 if ($vcards->length > 0) {
1296                         $vcard = $vcards->item(0);
1297
1298                         // We have to discard the guid from the hcard in favour of the guid from lrdd
1299                         // Reason: Hubzilla doesn't use the value "uid" in the hcard like Diaspora does.
1300                         $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' uid ')]", $vcard); // */
1301                         if (($search->length > 0) && empty($data["guid"])) {
1302                                 $data["guid"] = $search->item(0)->nodeValue;
1303                         }
1304
1305                         $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' nickname ')]", $vcard); // */
1306                         if ($search->length > 0) {
1307                                 $data["nick"] = $search->item(0)->nodeValue;
1308                         }
1309
1310                         $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' fn ')]", $vcard); // */
1311                         if ($search->length > 0) {
1312                                 $data["name"] = $search->item(0)->nodeValue;
1313                         }
1314
1315                         $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' searchable ')]", $vcard); // */
1316                         if ($search->length > 0) {
1317                                 $data["searchable"] = $search->item(0)->nodeValue;
1318                         }
1319
1320                         $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' key ')]", $vcard); // */
1321                         if ($search->length > 0) {
1322                                 $data["pubkey"] = $search->item(0)->nodeValue;
1323                                 if (strstr($data["pubkey"], 'RSA ')) {
1324                                         $data["pubkey"] = Crypto::rsaToPem($data["pubkey"]);
1325                                 }
1326                         }
1327
1328                         $search = $xpath->query("//*[@id='pod_location']", $vcard); // */
1329                         if ($search->length > 0) {
1330                                 $data["baseurl"] = trim($search->item(0)->nodeValue, "/");
1331                         }
1332                 }
1333
1334                 $avatar = [];
1335                 if (!empty($vcard)) {
1336                         $photos = $xpath->query("//*[contains(concat(' ', @class, ' '), ' photo ') or contains(concat(' ', @class, ' '), ' avatar ')]", $vcard); // */
1337                         foreach ($photos as $photo) {
1338                                 $attr = [];
1339                                 foreach ($photo->attributes as $attribute) {
1340                                         $attr[$attribute->name] = trim($attribute->value);
1341                                 }
1342
1343                                 if (isset($attr["src"]) && isset($attr["width"])) {
1344                                         $avatar[$attr["width"]] = $attr["src"];
1345                                 }
1346
1347                                 // We don't have a width. So we just take everything that we got.
1348                                 // This is a Hubzilla workaround which doesn't send a width.
1349                                 if ((sizeof($avatar) == 0) && !empty($attr["src"])) {
1350                                         $avatar[] = $attr["src"];
1351                                 }
1352                         }
1353                 }
1354
1355                 if (sizeof($avatar)) {
1356                         ksort($avatar);
1357                         $data["photo"] = self::fixAvatar(array_pop($avatar), $data["baseurl"]);
1358                 }
1359
1360                 if ($dfrn) {
1361                         // Poll DFRN specific data
1362                         $search = $xpath->query("//link[contains(concat(' ', @rel), ' dfrn-')]");
1363                         if ($search->length > 0) {
1364                                 foreach ($search as $link) {
1365                                         //$data["request"] = $search->item(0)->nodeValue;
1366                                         $attr = [];
1367                                         foreach ($link->attributes as $attribute) {
1368                                                 $attr[$attribute->name] = trim($attribute->value);
1369                                         }
1370
1371                                         $data[substr($attr["rel"], 5)] = $attr["href"];
1372                                 }
1373                         }
1374
1375                         // Older Friendica versions had used the "uid" field differently than newer versions
1376                         if (!empty($data["nick"]) && !empty($data["guid"]) && ($data["nick"] == $data["guid"])) {
1377                                 unset($data["guid"]);
1378                         }
1379                 }
1380
1381
1382                 return $data;
1383         }
1384
1385         /**
1386          * Check for Diaspora contact
1387          *
1388          * @param array $webfinger Webfinger data
1389          *
1390          * @return array Diaspora data
1391          * @throws HTTPException\InternalServerErrorException
1392          */
1393         private static function diaspora($webfinger)
1394         {
1395                 $hcard_url = "";
1396                 $data = [];
1397
1398                 // The array is reversed to take into account the order of preference for same-rel links
1399                 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1400                 foreach (array_reverse($webfinger["links"]) as $link) {
1401                         if (($link["rel"] == "http://microformats.org/profile/hcard") && !empty($link["href"])) {
1402                                 $hcard_url = $link["href"];
1403                         } elseif (($link["rel"] == "http://joindiaspora.com/seed_location") && !empty($link["href"])) {
1404                                 $data["baseurl"] = trim($link["href"], '/');
1405                         } elseif (($link["rel"] == "http://joindiaspora.com/guid") && !empty($link["href"])) {
1406                                 $data["guid"] = $link["href"];
1407                         } elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") && (($link["type"] ?? "") == "text/html") && !empty($link["href"])) {
1408                                 $data["url"] = $link["href"];
1409                         } elseif (($link["rel"] == ActivityNamespace::FEED) && !empty($link["href"])) {
1410                                 $data["poll"] = $link["href"];
1411                         } elseif (($link["rel"] == ActivityNamespace::POCO) && !empty($link["href"])) {
1412                                 $data["poco"] = $link["href"];
1413                         } elseif (($link["rel"] == "salmon") && !empty($link["href"])) {
1414                                 $data["notify"] = $link["href"];
1415                         } elseif (($link["rel"] == "diaspora-public-key") && !empty($link["href"])) {
1416                                 $data["pubkey"] = base64_decode($link["href"]);
1417
1418                                 //if (strstr($data["pubkey"], 'RSA ') || ($link["type"] == "RSA"))
1419                                 if (strstr($data["pubkey"], 'RSA ')) {
1420                                         $data["pubkey"] = Crypto::rsaToPem($data["pubkey"]);
1421                                 }
1422                         }
1423                 }
1424
1425                 if (empty($data["url"]) || empty($hcard_url)) {
1426                         return [];
1427                 }
1428
1429                 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
1430                         foreach ($webfinger["aliases"] as $alias) {
1431                                 if (Strings::normaliseLink($alias) != Strings::normaliseLink($data["url"]) && ! strstr($alias, "@")) {
1432                                         $data["alias"] = $alias;
1433                                 } elseif (substr($alias, 0, 5) == 'acct:') {
1434                                         $data["addr"] = substr($alias, 5);
1435                                 }
1436                         }
1437                 }
1438
1439                 if (!empty($webfinger["subject"]) && (substr($webfinger["subject"], 0, 5) == 'acct:')) {
1440                         $data["addr"] = substr($webfinger["subject"], 5);
1441                 }
1442
1443                 // Fetch further information from the hcard
1444                 $data = self::pollHcard($hcard_url, $data);
1445
1446                 if (!$data) {
1447                         return [];
1448                 }
1449
1450                 if (!empty($data["url"])
1451                         && !empty($data["guid"])
1452                         && !empty($data["baseurl"])
1453                         && !empty($data["pubkey"])
1454                         && !empty($hcard_url)
1455                 ) {
1456                         $data["network"] = Protocol::DIASPORA;
1457
1458                         // The Diaspora handle must always be lowercase
1459                         if (!empty($data["addr"])) {
1460                                 $data["addr"] = strtolower($data["addr"]);
1461                         }
1462
1463                         // We have to overwrite the detected value for "notify" since Hubzilla doesn't send it
1464                         $data["notify"] = $data["baseurl"] . "/receive/users/" . $data["guid"];
1465                         $data["batch"]  = $data["baseurl"] . "/receive/public";
1466                 } else {
1467                         return [];
1468                 }
1469
1470                 return $data;
1471         }
1472
1473         /**
1474          * Check for OStatus contact
1475          *
1476          * @param array $webfinger Webfinger data
1477          * @param bool  $short     Short detection mode
1478          *
1479          * @return array|bool OStatus data or "false" on error or "true" on short mode
1480          * @throws HTTPException\InternalServerErrorException
1481          */
1482         private static function ostatus($webfinger, $short = false)
1483         {
1484                 $data = [];
1485
1486                 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
1487                         foreach ($webfinger["aliases"] as $alias) {
1488                                 if (strstr($alias, "@") && !strstr(Strings::normaliseLink($alias), "http://")) {
1489                                         $data["addr"] = str_replace('acct:', '', $alias);
1490                                 }
1491                         }
1492                 }
1493
1494                 if (!empty($webfinger["subject"]) && strstr($webfinger["subject"], "@")
1495                         && !strstr(Strings::normaliseLink($webfinger["subject"]), "http://")
1496                 ) {
1497                         $data["addr"] = str_replace('acct:', '', $webfinger["subject"]);
1498                 }
1499
1500                 if (!empty($webfinger["links"])) {
1501                         // The array is reversed to take into account the order of preference for same-rel links
1502                         // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1503                         foreach (array_reverse($webfinger["links"]) as $link) {
1504                                 if (($link["rel"] == "http://webfinger.net/rel/profile-page")
1505                                         && (($link["type"] ?? "") == "text/html")
1506                                         && ($link["href"] != "")
1507                                 ) {
1508                                         $data["url"] = $data["alias"] = $link["href"];
1509                                 } elseif (($link["rel"] == "salmon") && !empty($link["href"])) {
1510                                         $data["notify"] = $link["href"];
1511                                 } elseif (($link["rel"] == ActivityNamespace::FEED) && !empty($link["href"])) {
1512                                         $data["poll"] = $link["href"];
1513                                 } elseif (($link["rel"] == "magic-public-key") && !empty($link["href"])) {
1514                                         $pubkey = $link["href"];
1515
1516                                         if (substr($pubkey, 0, 5) === 'data:') {
1517                                                 if (strstr($pubkey, ',')) {
1518                                                         $pubkey = substr($pubkey, strpos($pubkey, ',') + 1);
1519                                                 } else {
1520                                                         $pubkey = substr($pubkey, 5);
1521                                                 }
1522                                         } elseif (Strings::normaliseLink($pubkey) == 'http://') {
1523                                                 $curlResult = DI::httpRequest()->get($pubkey);
1524                                                 if ($curlResult->isTimeout()) {
1525                                                         self::$istimeout = true;
1526                                                         return $short ? false : [];
1527                                                 }
1528                                                 $pubkey = $curlResult->getBody();
1529                                         }
1530
1531                                         $key = explode(".", $pubkey);
1532
1533                                         if (sizeof($key) >= 3) {
1534                                                 $m = Strings::base64UrlDecode($key[1]);
1535                                                 $e = Strings::base64UrlDecode($key[2]);
1536                                                 $data["pubkey"] = Crypto::meToPem($m, $e);
1537                                         }
1538                                 }
1539                         }
1540                 }
1541
1542                 if (isset($data["notify"]) && isset($data["pubkey"])
1543                         && isset($data["poll"])
1544                         && isset($data["url"])
1545                 ) {
1546                         $data["network"] = Protocol::OSTATUS;
1547                 } else {
1548                         return $short ? false : [];
1549                 }
1550
1551                 if ($short) {
1552                         return true;
1553                 }
1554
1555                 // Fetch all additional data from the feed
1556                 $curlResult = DI::httpRequest()->get($data["poll"]);
1557                 if ($curlResult->isTimeout()) {
1558                         self::$istimeout = true;
1559                         return [];
1560                 }
1561                 $feed = $curlResult->getBody();
1562                 $feed_data = Feed::import($feed);
1563                 if (!$feed_data) {
1564                         return [];
1565                 }
1566
1567                 if (!empty($feed_data["header"]["author-name"])) {
1568                         $data["name"] = $feed_data["header"]["author-name"];
1569                 }
1570                 if (!empty($feed_data["header"]["author-nick"])) {
1571                         $data["nick"] = $feed_data["header"]["author-nick"];
1572                 }
1573                 if (!empty($feed_data["header"]["author-avatar"])) {
1574                         $data["photo"] = self::fixAvatar($feed_data["header"]["author-avatar"], $data["url"]);
1575                 }
1576                 if (!empty($feed_data["header"]["author-id"])) {
1577                         $data["alias"] = $feed_data["header"]["author-id"];
1578                 }
1579                 if (!empty($feed_data["header"]["author-location"])) {
1580                         $data["location"] = $feed_data["header"]["author-location"];
1581                 }
1582                 if (!empty($feed_data["header"]["author-about"])) {
1583                         $data["about"] = $feed_data["header"]["author-about"];
1584                 }
1585                 // OStatus has serious issues when the the url doesn't fit (ssl vs. non ssl)
1586                 // So we take the value that we just fetched, although the other one worked as well
1587                 if (!empty($feed_data["header"]["author-link"])) {
1588                         $data["url"] = $feed_data["header"]["author-link"];
1589                 }
1590
1591                 if ($data["url"] == $data["alias"]) {
1592                         $data["alias"] = '';
1593                 }
1594
1595                 /// @todo Fetch location and "about" from the feed as well
1596                 return $data;
1597         }
1598
1599         /**
1600          * Fetch data from a pump.io profile page
1601          *
1602          * @param string $profile_link Link to the profile page
1603          *
1604          * @return array profile data
1605          */
1606         private static function pumpioProfileData($profile_link)
1607         {
1608                 $curlResult = DI::httpRequest()->get($profile_link);
1609                 if (!$curlResult->isSuccess()) {
1610                         return [];
1611                 }
1612
1613                 $doc = new DOMDocument();
1614                 if (!@$doc->loadHTML($curlResult->getBody())) {
1615                         return [];
1616                 }
1617
1618                 $xpath = new DomXPath($doc);
1619
1620                 $data = [];
1621
1622                 $data["name"] = $xpath->query("//span[contains(@class, 'p-name')]")->item(0)->nodeValue;
1623
1624                 if ($data["name"] == '') {
1625                         // This is ugly - but pump.io doesn't seem to know a better way for it
1626                         $data["name"] = trim($xpath->query("//h1[@class='media-header']")->item(0)->nodeValue);
1627                         $pos = strpos($data["name"], chr(10));
1628                         if ($pos) {
1629                                 $data["name"] = trim(substr($data["name"], 0, $pos));
1630                         }
1631                 }
1632
1633                 $data["location"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'p-locality')]");
1634
1635                 if ($data["location"] == '') {
1636                         $data["location"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'location')]");
1637                 }
1638
1639                 $data["about"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'p-note')]");
1640
1641                 if ($data["about"] == '') {
1642                         $data["about"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'summary')]");
1643                 }
1644
1645                 $avatar = $xpath->query("//img[contains(@class, 'u-photo')]")->item(0);
1646                 if (!$avatar) {
1647                         $avatar = $xpath->query("//img[@class='img-rounded media-object']")->item(0);
1648                 }
1649                 if ($avatar) {
1650                         foreach ($avatar->attributes as $attribute) {
1651                                 if ($attribute->name == "src") {
1652                                         $data["photo"] = trim($attribute->value);
1653                                 }
1654                         }
1655                 }
1656
1657                 return $data;
1658         }
1659
1660         /**
1661          * Check for pump.io contact
1662          *
1663          * @param array  $webfinger Webfinger data
1664          * @param string $addr
1665          * @return array pump.io data
1666          */
1667         private static function pumpio($webfinger, $addr)
1668         {
1669                 $data = [];
1670                 // The array is reversed to take into account the order of preference for same-rel links
1671                 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1672                 foreach (array_reverse($webfinger["links"]) as $link) {
1673                         if (($link["rel"] == "http://webfinger.net/rel/profile-page")
1674                                 && (($link["type"] ?? "") == "text/html")
1675                                 && ($link["href"] != "")
1676                         ) {
1677                                 $data["url"] = $link["href"];
1678                         } elseif (($link["rel"] == "activity-inbox") && ($link["href"] != "")) {
1679                                 $data["notify"] = $link["href"];
1680                         } elseif (($link["rel"] == "activity-outbox") && ($link["href"] != "")) {
1681                                 $data["poll"] = $link["href"];
1682                         } elseif (($link["rel"] == "dialback") && ($link["href"] != "")) {
1683                                 $data["dialback"] = $link["href"];
1684                         }
1685                 }
1686                 if (isset($data["poll"]) && isset($data["notify"])
1687                         && isset($data["dialback"])
1688                         && isset($data["url"])
1689                 ) {
1690                         // by now we use these fields only for the network type detection
1691                         // So we unset all data that isn't used at the moment
1692                         unset($data["dialback"]);
1693
1694                         $data["network"] = Protocol::PUMPIO;
1695                 } else {
1696                         return [];
1697                 }
1698
1699                 $profile_data = self::pumpioProfileData($data["url"]);
1700
1701                 if (!$profile_data) {
1702                         return [];
1703                 }
1704
1705                 $data = array_merge($data, $profile_data);
1706
1707                 if (($addr != '') && ($data['name'] != '')) {
1708                         $name = trim(str_replace($addr, '', $data['name']));
1709                         if ($name != '') {
1710                                 $data['name'] = $name;
1711                         }
1712                 }
1713
1714                 return $data;
1715         }
1716
1717         /**
1718          * Check for twitter contact
1719          *
1720          * @param string $uri
1721          *
1722          * @return array twitter data
1723          */
1724         private static function twitter($uri)
1725         {
1726                 if (preg_match('=([^@]+)@(?:mobile\.)?twitter\.com$=i', $uri, $matches)) {
1727                         $nick = $matches[1];
1728                 } elseif (preg_match('=^https?://(?:mobile\.)?twitter\.com/(.+)=i', $uri, $matches)) {
1729                         $nick = $matches[1];
1730                 } else {
1731                         return [];
1732                 }
1733
1734                 $data = [];
1735                 $data['url'] = 'https://twitter.com/' . $nick;
1736                 $data['addr'] = $nick . '@twitter.com';
1737                 $data['nick'] = $data['name'] = $nick;
1738                 $data['network'] = Protocol::TWITTER;
1739                 $data['baseurl'] = 'https://twitter.com';
1740
1741                 return $data;
1742         }
1743
1744         /**
1745          * Checks HTML page for RSS feed link
1746          *
1747          * @param string $url  Page link
1748          * @param string $body Page body string
1749          * @return string|false Feed link or false if body was invalid HTML document
1750          */
1751         public static function getFeedLink(string $url, string $body)
1752         {
1753                 $doc = new DOMDocument();
1754                 if (!@$doc->loadHTML($body)) {
1755                         return false;
1756                 }
1757
1758                 $xpath = new DOMXPath($doc);
1759
1760                 $feedUrl = $xpath->evaluate('string(/html/head/link[@type="application/rss+xml" and @rel="alternate"]/@href)');
1761
1762                 $feedUrl = $feedUrl ? self::ensureAbsoluteLinkFromHTMLDoc($feedUrl, $url, $xpath) : '';
1763
1764                 return $feedUrl;
1765         }
1766
1767         /**
1768          * Return an absolute URL in the context of a HTML document retrieved from the provided URL.
1769          *
1770          * Loosely based on RFC 1808
1771          *
1772          * @see https://tools.ietf.org/html/rfc1808
1773          *
1774          * @param string   $href  The potential relative href found in the HTML document
1775          * @param string   $base  The HTML document URL
1776          * @param DOMXPath $xpath The HTML document XPath
1777          * @return string
1778          */
1779         private static function ensureAbsoluteLinkFromHTMLDoc(string $href, string $base, DOMXPath $xpath)
1780         {
1781                 if (filter_var($href, FILTER_VALIDATE_URL)) {
1782                         return $href;
1783                 }
1784
1785                 $base = $xpath->evaluate('string(/html/head/base/@href)') ?: $base;
1786
1787                 $baseParts = parse_url($base);
1788                 if (empty($baseParts['host'])) {
1789                         return $href;
1790                 }
1791
1792                 // Naked domain case (scheme://basehost)
1793                 $path = $baseParts['path'] ?? '/';
1794
1795                 // Remove the filename part of the path if it exists (/base/path/file)
1796                 $path = implode('/', array_slice(explode('/', $path), 0, -1));
1797
1798                 $hrefParts = parse_url($href);
1799
1800                 // Root path case (/path) including relative scheme case (//host/path)
1801                 if ($hrefParts['path'] && $hrefParts['path'][0] == '/') {
1802                         $path = $hrefParts['path'];
1803                 } else {
1804                         $path = $path . '/' . $hrefParts['path'];
1805
1806                         // Resolve arbitrary relative path
1807                         // Lifted from https://www.php.net/manual/en/function.realpath.php#84012
1808                         $parts = array_filter(explode('/', $path), 'strlen');
1809                         $absolutes = array();
1810                         foreach ($parts as $part) {
1811                                 if ('.' == $part) continue;
1812                                 if ('..' == $part) {
1813                                         array_pop($absolutes);
1814                                 } else {
1815                                         $absolutes[] = $part;
1816                                 }
1817                         }
1818
1819                         $path = '/' . implode('/', $absolutes);
1820                 }
1821
1822                 // Relative scheme case (//host/path)
1823                 $baseParts['host'] = $hrefParts['host'] ?? $baseParts['host'];
1824                 $baseParts['path'] = $path;
1825                 unset($baseParts['query']);
1826                 unset($baseParts['fragment']);
1827
1828                 return Network::unparseURL($baseParts);
1829         }
1830
1831         /**
1832          * Check for feed contact
1833          *
1834          * @param string  $url   Profile link
1835          * @param boolean $probe Do a probe if the page contains a feed link
1836          *
1837          * @return array feed data
1838          * @throws HTTPException\InternalServerErrorException
1839          */
1840         private static function feed($url, $probe = true)
1841         {
1842                 $curlResult = DI::httpRequest()->get($url);
1843                 if ($curlResult->isTimeout()) {
1844                         self::$istimeout = true;
1845                         return [];
1846                 }
1847                 $feed = $curlResult->getBody();
1848                 $feed_data = Feed::import($feed);
1849
1850                 if (!$feed_data) {
1851                         if (!$probe) {
1852                                 return [];
1853                         }
1854
1855                         $feed_url = self::getFeedLink($url, $feed);
1856
1857                         if (!$feed_url) {
1858                                 return [];
1859                         }
1860
1861                         return self::feed($feed_url, false);
1862                 }
1863
1864                 if (!empty($feed_data["header"]["author-name"])) {
1865                         $data["name"] = $feed_data["header"]["author-name"];
1866                 }
1867
1868                 if (!empty($feed_data["header"]["author-nick"])) {
1869                         $data["nick"] = $feed_data["header"]["author-nick"];
1870                 }
1871
1872                 if (!empty($feed_data["header"]["author-avatar"])) {
1873                         $data["photo"] = $feed_data["header"]["author-avatar"];
1874                 }
1875
1876                 if (!empty($feed_data["header"]["author-id"])) {
1877                         $data["alias"] = $feed_data["header"]["author-id"];
1878                 }
1879
1880                 $data["url"] = $url;
1881                 $data["poll"] = $url;
1882
1883                 $data["network"] = Protocol::FEED;
1884
1885                 return $data;
1886         }
1887
1888         /**
1889          * Check for mail contact
1890          *
1891          * @param string  $uri Profile link
1892          * @param integer $uid User ID
1893          *
1894          * @return array mail data
1895          * @throws \Exception
1896          */
1897         private static function mail($uri, $uid)
1898         {
1899                 if (!Network::isEmailDomainValid($uri)) {
1900                         return [];
1901                 }
1902
1903                 if ($uid == 0) {
1904                         return [];
1905                 }
1906
1907                 $user = DBA::selectFirst('user', ['prvkey'], ['uid' => $uid]);
1908
1909                 $condition = ["`uid` = ? AND `server` != ''", $uid];
1910                 $fields = ['pass', 'user', 'server', 'port', 'ssltype', 'mailbox'];
1911                 $mailacct = DBA::selectFirst('mailacct', $fields, $condition);
1912
1913                 if (!DBA::isResult($user) || !DBA::isResult($mailacct)) {
1914                         return [];
1915                 }
1916
1917                 $mailbox = Email::constructMailboxName($mailacct);
1918                 $password = '';
1919                 openssl_private_decrypt(hex2bin($mailacct['pass']), $password, $user['prvkey']);
1920                 $mbox = Email::connect($mailbox, $mailacct['user'], $password);
1921                 if (!$mbox) {
1922                         return [];
1923                 }
1924
1925                 $msgs = Email::poll($mbox, $uri);
1926                 Logger::info('Messages found', ['uri' => $uri, 'count' => count($msgs)]);
1927
1928                 if (!count($msgs)) {
1929                         return [];
1930                 }
1931
1932                 $phost = substr($uri, strpos($uri, '@') + 1);
1933
1934                 $data = [];
1935                 $data["addr"]    = $uri;
1936                 $data["network"] = Protocol::MAIL;
1937                 $data["name"]    = substr($uri, 0, strpos($uri, '@'));
1938                 $data["nick"]    = $data["name"];
1939                 $data["photo"]   = Network::lookupAvatarByEmail($uri);
1940                 $data["url"]     = 'mailto:'.$uri;
1941                 $data["notify"]  = 'smtp ' . Strings::getRandomHex();
1942                 $data["poll"]    = 'email ' . Strings::getRandomHex();
1943
1944                 $x = Email::messageMeta($mbox, $msgs[0]);
1945                 if (stristr($x[0]->from, $uri)) {
1946                         $adr = imap_rfc822_parse_adrlist($x[0]->from, '');
1947                 } elseif (stristr($x[0]->to, $uri)) {
1948                         $adr = imap_rfc822_parse_adrlist($x[0]->to, '');
1949                 }
1950                 if (isset($adr)) {
1951                         foreach ($adr as $feadr) {
1952                                 if ((strcasecmp($feadr->mailbox, $data["name"]) == 0)
1953                                         &&(strcasecmp($feadr->host, $phost) == 0)
1954                                         && (strlen($feadr->personal))
1955                                 ) {
1956                                         $personal = imap_mime_header_decode($feadr->personal);
1957                                         $data["name"] = "";
1958                                         foreach ($personal as $perspart) {
1959                                                 if ($perspart->charset != "default") {
1960                                                         $data["name"] .= iconv($perspart->charset, 'UTF-8//IGNORE', $perspart->text);
1961                                                 } else {
1962                                                         $data["name"] .= $perspart->text;
1963                                                 }
1964                                         }
1965
1966                                         $data["name"] = Strings::escapeTags($data["name"]);
1967                                 }
1968                         }
1969                 }
1970                 if (!empty($mbox)) {
1971                         imap_close($mbox);
1972                 }
1973                 return $data;
1974         }
1975
1976         /**
1977          * Mix two paths together to possibly fix missing parts
1978          *
1979          * @param string $avatar Path to the avatar
1980          * @param string $base   Another path that is hopefully complete
1981          *
1982          * @return string fixed avatar path
1983          * @throws \Exception
1984          */
1985         public static function fixAvatar($avatar, $base)
1986         {
1987                 $base_parts = parse_url($base);
1988
1989                 // Remove all parts that could create a problem
1990                 unset($base_parts['path']);
1991                 unset($base_parts['query']);
1992                 unset($base_parts['fragment']);
1993
1994                 $avatar_parts = parse_url($avatar);
1995
1996                 // Now we mix them
1997                 $parts = array_merge($base_parts, $avatar_parts);
1998
1999                 // And put them together again
2000                 $scheme   = isset($parts['scheme'])   ? $parts['scheme'] . '://' : '';
2001                 $host     = isset($parts['host'])     ? $parts['host']           : '';
2002                 $port     = isset($parts['port'])     ? ':' . $parts['port']     : '';
2003                 $path     = isset($parts['path'])     ? $parts['path']           : '';
2004                 $query    = isset($parts['query'])    ? '?' . $parts['query']    : '';
2005                 $fragment = isset($parts['fragment']) ? '#' . $parts['fragment'] : '';
2006
2007                 $fixed = $scheme.$host.$port.$path.$query.$fragment;
2008
2009                 Logger::debug('Avatar fixed', ['base' => $base, 'avatar' => $avatar, 'fixed' => $fixed]);
2010
2011                 return $fixed;
2012         }
2013
2014         /**
2015          * Fetch the last date that the contact had posted something (publically)
2016          *
2017          * @param string $data  probing result
2018          * @return string last activity
2019          */
2020         public static function getLastUpdate(array $data)
2021         {
2022                 if ($lastUpdate = self::updateFromNoScrape($data)) {
2023                         return $lastUpdate;
2024                 }
2025
2026                 if (!empty($data['outbox'])) {
2027                         return self::updateFromOutbox($data['outbox'], $data);
2028                 } elseif (!empty($data['poll']) && ($data['network'] == Protocol::ACTIVITYPUB)) {
2029                         return self::updateFromOutbox($data['poll'], $data);
2030                 } elseif (!empty($data['poll'])) {
2031                         return self::updateFromFeed($data);
2032                 }
2033
2034                 return '';
2035         }
2036
2037         /**
2038          * Fetch the last activity date from the "noscrape" endpoint
2039          *
2040          * @param array $data Probing result
2041          * @return string last activity
2042          *
2043          * @return bool 'true' if update was successful or the server was unreachable
2044          */
2045         private static function updateFromNoScrape(array $data)
2046         {
2047                 if (empty($data['baseurl'])) {
2048                         return '';
2049                 }
2050
2051                 // Check the 'noscrape' endpoint when it is a Friendica server
2052                 $gserver = DBA::selectFirst('gserver', ['noscrape'], ["`nurl` = ? AND `noscrape` != ''",
2053                         Strings::normaliseLink($data['baseurl'])]);
2054                 if (!DBA::isResult($gserver)) {
2055                         return '';
2056                 }
2057
2058                 $curlResult = DI::httpRequest()->get($gserver['noscrape'] . '/' . $data['nick']);
2059
2060                 if ($curlResult->isSuccess() && !empty($curlResult->getBody())) {
2061                         $noscrape = json_decode($curlResult->getBody(), true);
2062                         if (!empty($noscrape) && !empty($noscrape['updated'])) {
2063                                 return DateTimeFormat::utc($noscrape['updated'], DateTimeFormat::MYSQL);
2064                         }
2065                 }
2066
2067                 return '';
2068         }
2069
2070         /**
2071          * Fetch the last activity date from an ActivityPub Outbox
2072          *
2073          * @param string $feed
2074          * @param array  $data Probing result
2075          * @return string last activity
2076          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2077          */
2078         private static function updateFromOutbox(string $feed, array $data)
2079         {
2080                 $outbox = ActivityPub::fetchContent($feed);
2081                 if (empty($outbox)) {
2082                         return '';
2083                 }
2084
2085                 if (!empty($outbox['orderedItems'])) {
2086                         $items = $outbox['orderedItems'];
2087                 } elseif (!empty($outbox['first']['orderedItems'])) {
2088                         $items = $outbox['first']['orderedItems'];
2089                 } elseif (!empty($outbox['first']['href']) && ($outbox['first']['href'] != $feed)) {
2090                         return self::updateFromOutbox($outbox['first']['href'], $data);
2091                 } elseif (!empty($outbox['first'])) {
2092                         if (is_string($outbox['first']) && ($outbox['first'] != $feed)) {
2093                                 return self::updateFromOutbox($outbox['first'], $data);
2094                         } else {
2095                                 Logger::warning('Unexpected data', ['outbox' => $outbox]);
2096                         }
2097                         return '';
2098                 } else {
2099                         $items = [];
2100                 }
2101
2102                 $last_updated = '';
2103                 foreach ($items as $activity) {
2104                         if (!empty($activity['published'])) {
2105                                 $published =  DateTimeFormat::utc($activity['published']);
2106                         } elseif (!empty($activity['object']['published'])) {
2107                                 $published =  DateTimeFormat::utc($activity['object']['published']);
2108                         } else {
2109                                 continue;
2110                         }
2111
2112                         if ($last_updated < $published) {
2113                                 $last_updated = $published;
2114                         }
2115                 }
2116
2117                 if (!empty($last_updated)) {
2118                         return $last_updated;
2119                 }
2120
2121                 return '';
2122         }
2123
2124         /**
2125          * Fetch the last activity date from an XML feed
2126          *
2127          * @param array $data Probing result
2128          * @return string last activity
2129          */
2130         private static function updateFromFeed(array $data)
2131         {
2132                 // Search for the newest entry in the feed
2133                 $curlResult = DI::httpRequest()->get($data['poll']);
2134                 if (!$curlResult->isSuccess()) {
2135                         return '';
2136                 }
2137
2138                 $doc = new DOMDocument();
2139                 @$doc->loadXML($curlResult->getBody());
2140
2141                 $xpath = new DOMXPath($doc);
2142                 $xpath->registerNamespace('atom', 'http://www.w3.org/2005/Atom');
2143
2144                 $entries = $xpath->query('/atom:feed/atom:entry');
2145
2146                 $last_updated = '';
2147
2148                 foreach ($entries as $entry) {
2149                         $published_item = $xpath->query('atom:published/text()', $entry)->item(0);
2150                         $updated_item   = $xpath->query('atom:updated/text()'  , $entry)->item(0);
2151                         $published      = !empty($published_item->nodeValue) ? DateTimeFormat::utc($published_item->nodeValue) : null;
2152                         $updated        = !empty($updated_item->nodeValue) ? DateTimeFormat::utc($updated_item->nodeValue) : null;
2153
2154                         if (empty($published) || empty($updated)) {
2155                                 Logger::notice('Invalid entry for XPath.', ['entry' => $entry, 'url' => $data['url']]);
2156                                 continue;
2157                         }
2158
2159                         if ($last_updated < $published) {
2160                                 $last_updated = $published;
2161                         }
2162
2163                         if ($last_updated < $updated) {
2164                                 $last_updated = $updated;
2165                         }
2166                 }
2167
2168                 if (!empty($last_updated)) {
2169                         return $last_updated;
2170                 }
2171
2172                 return '';
2173         }
2174 }