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