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