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