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