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