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