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