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