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