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