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