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