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