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