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