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