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