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