]> git.mxchange.org Git - friendica.git/blob - src/Network/Probe.php
Create own base URL class which holds the whole base url business logic
[friendica.git] / src / Network / Probe.php
1 <?php
2 /**
3  * @file src/Network/Probe.php
4  */
5 namespace Friendica\Network;
6
7 /**
8  * @file src/Network/Probe.php
9  * @brief Functions for probing URL
10  */
11
12 use DOMDocument;
13 use DomXPath;
14 use Friendica\Core\Cache;
15 use Friendica\Core\Config;
16 use Friendica\Core\Logger;
17 use Friendica\Core\Protocol;
18 use Friendica\Core\System;
19 use Friendica\Database\DBA;
20 use Friendica\Model\Contact;
21 use Friendica\Model\Profile;
22 use Friendica\Protocol\ActivityPub;
23 use Friendica\Protocol\Email;
24 use Friendica\Protocol\Feed;
25 use Friendica\Util\Crypto;
26 use Friendica\Util\DateTimeFormat;
27 use Friendica\Util\Network;
28 use Friendica\Util\Strings;
29 use Friendica\Util\XML;
30
31 /**
32  * @brief This class contain functions for probing URL
33  *
34  */
35 class Probe
36 {
37         private static $baseurl;
38         private static $istimeout;
39
40         /**
41          * @brief Rearrange the array so that it always has the same order
42          *
43          * @param array $data Unordered data
44          *
45          * @return array Ordered data
46          */
47         private static function rearrangeData($data)
48         {
49                 $fields = ["name", "nick", "guid", "url", "addr", "alias",
50                                 "photo", "community", "keywords", "location", "about",
51                                 "batch", "notify", "poll", "request", "confirm", "poco",
52                                 "priority", "network", "pubkey", "baseurl"];
53
54                 $newdata = [];
55                 foreach ($fields as $field) {
56                         if (isset($data[$field])) {
57                                 $newdata[$field] = $data[$field];
58                         } else {
59                                 $newdata[$field] = "";
60                         }
61                 }
62
63                 // We don't use the "priority" field anymore and replace it with a dummy.
64                 $newdata["priority"] = 0;
65
66                 return $newdata;
67         }
68
69         /**
70          * @brief Check if the hostname belongs to the own server
71          *
72          * @param string $host The hostname that is to be checked
73          *
74          * @return bool Does the testes hostname belongs to the own server?
75          */
76         private static function ownHost($host)
77         {
78                 $own_host = \get_app()->getHostName();
79
80                 $parts = parse_url($host);
81
82                 if (!isset($parts['scheme'])) {
83                         $parts = parse_url('http://'.$host);
84                 }
85
86                 if (!isset($parts['host'])) {
87                         return false;
88                 }
89                 return $parts['host'] == $own_host;
90         }
91
92         /**
93          * @brief Probes for webfinger path via "host-meta"
94          *
95          * We have to check if the servers in the future still will offer this.
96          * It seems as if it was dropped from the standard.
97          *
98          * @param string $host The host part of an url
99          *
100          * @return array with template and type of the webfinger template for JSON or XML
101          * @throws HTTPException\InternalServerErrorException
102          */
103         private static function hostMeta($host)
104         {
105                 // Reset the static variable
106                 self::$baseurl = '';
107
108                 $ssl_url = "https://".$host."/.well-known/host-meta";
109                 $url = "http://".$host."/.well-known/host-meta";
110
111                 $xrd_timeout = Config::get('system', 'xrd_timeout', 20);
112                 $redirects = 0;
113
114                 Logger::log("Probing for ".$host, Logger::DEBUG);
115                 $xrd = null;
116
117                 $curlResult = Network::curl($ssl_url, false, $redirects, ['timeout' => $xrd_timeout, 'accept_content' => 'application/xrd+xml']);
118                 if ($curlResult->isSuccess()) {
119                         $xml = $curlResult->getBody();
120                         $xrd = XML::parseString($xml, false);
121                         $host_url = 'https://'.$host;
122                 }
123
124                 if (!is_object($xrd)) {
125                         $curlResult = Network::curl($url, false, $redirects, ['timeout' => $xrd_timeout, 'accept_content' => 'application/xrd+xml']);
126                         if ($curlResult->isTimeout()) {
127                                 Logger::log("Probing timeout for " . $url, Logger::DEBUG);
128                                 self::$istimeout = true;
129                                 return false;
130                         }
131                         $xml = $curlResult->getBody();
132                         $xrd = XML::parseString($xml, false);
133                         $host_url = 'http://'.$host;
134                 }
135                 if (!is_object($xrd)) {
136                         Logger::log("No xrd object found for ".$host, Logger::DEBUG);
137                         return [];
138                 }
139
140                 $links = XML::elementToArray($xrd);
141                 if (!isset($links["xrd"]["link"])) {
142                         Logger::log("No xrd data found for ".$host, Logger::DEBUG);
143                         return [];
144                 }
145
146                 $lrdd = [];
147                 // The following webfinger path is defined in RFC 7033 https://tools.ietf.org/html/rfc7033
148                 // Problem is that Hubzilla currently doesn't provide all data in the JSON webfinger
149                 // compared to the XML webfinger. So this is commented out by now.
150                 // $lrdd = array("application/jrd+json" => $host_url.'/.well-known/webfinger?resource={uri}');
151
152                 foreach ($links["xrd"]["link"] as $value => $link) {
153                         if (!empty($link["@attributes"])) {
154                                 $attributes = $link["@attributes"];
155                         } elseif ($value == "@attributes") {
156                                 $attributes = $link;
157                         } else {
158                                 continue;
159                         }
160
161                         if (!empty($attributes["rel"]) && $attributes["rel"] == "lrdd" && !empty($attributes["template"])) {
162                                 $type = (empty($attributes["type"]) ? '' : $attributes["type"]);
163
164                                 $lrdd[$type] = $attributes["template"];
165                         }
166                 }
167
168                 self::$baseurl = $host_url;
169
170                 Logger::log("Probing successful for ".$host, Logger::DEBUG);
171
172                 return $lrdd;
173         }
174
175         /**
176          * @brief Perform Webfinger lookup and return DFRN data
177          *
178          * Given an email style address, perform webfinger lookup and
179          * return the resulting DFRN profile URL, or if no DFRN profile URL
180          * is located, returns an OStatus subscription template (prefixed
181          * with the string 'stat:' to identify it as on OStatus template).
182          * If this isn't an email style address just return $webbie.
183          * Return an empty string if email-style addresses but webfinger fails,
184          * or if the resultant personal XRD doesn't contain a supported
185          * subscription/friend-request attribute.
186          *
187          * amended 7/9/2011 to return an hcard which could save potentially loading
188          * a lengthy content page to scrape dfrn attributes
189          *
190          * @param string $webbie    Address that should be probed
191          * @param string $hcard_url Link to the hcard - is returned by reference
192          *
193          * @return string profile link
194          * @throws HTTPException\InternalServerErrorException
195          */
196         public static function webfingerDfrn($webbie, &$hcard_url)
197         {
198                 $profile_link = '';
199
200                 $links = self::lrdd($webbie);
201                 Logger::log('webfingerDfrn: '.$webbie.':'.print_r($links, true), Logger::DATA);
202                 if (count($links)) {
203                         foreach ($links as $link) {
204                                 if ($link['@attributes']['rel'] === NAMESPACE_DFRN) {
205                                         $profile_link = $link['@attributes']['href'];
206                                 }
207                                 if (($link['@attributes']['rel'] === NAMESPACE_OSTATUSSUB) && ($profile_link == "")) {
208                                         $profile_link = 'stat:'.$link['@attributes']['template'];
209                                 }
210                                 if ($link['@attributes']['rel'] === 'http://microformats.org/profile/hcard') {
211                                         $hcard_url = $link['@attributes']['href'];
212                                 }
213                         }
214                 }
215                 return $profile_link;
216         }
217
218         /**
219          * @brief Check an URI for LRDD data
220          *
221          * this is a replacement for the "lrdd" function.
222          * It isn't used in this class and has some redundancies in the code.
223          * When time comes we can check the existing calls for "lrdd" if we can rework them.
224          *
225          * @param string $uri Address that should be probed
226          *
227          * @return array uri data
228          * @throws HTTPException\InternalServerErrorException
229          */
230         public static function lrdd($uri)
231         {
232                 $lrdd = self::hostMeta($uri);
233                 $webfinger = null;
234
235                 if (is_bool($lrdd)) {
236                         return [];
237                 }
238
239                 if (!$lrdd) {
240                         $parts = @parse_url($uri);
241                         if (!$parts || empty($parts["host"]) || empty($parts["path"])) {
242                                 return [];
243                         }
244
245                         $host = $parts["host"];
246                         if (!empty($parts["port"])) {
247                                 $host .= ':'.$parts["port"];
248                         }
249
250                         $path_parts = explode("/", trim($parts["path"], "/"));
251
252                         $nick = array_pop($path_parts);
253
254                         do {
255                                 $lrdd = self::hostMeta($host);
256                                 $host .= "/".array_shift($path_parts);
257                         } while (!$lrdd && (sizeof($path_parts) > 0));
258                 }
259
260                 if (!$lrdd) {
261                         Logger::log("No lrdd data found for ".$uri, Logger::DEBUG);
262                         return [];
263                 }
264
265                 foreach ($lrdd as $type => $template) {
266                         if ($webfinger) {
267                                 continue;
268                         }
269
270                         $path = str_replace('{uri}', urlencode($uri), $template);
271                         $webfinger = self::webfinger($path, $type);
272
273                         if (!$webfinger && (strstr($uri, "@"))) {
274                                 $path = str_replace('{uri}', urlencode("acct:".$uri), $template);
275                                 $webfinger = self::webfinger($path, $type);
276                         }
277
278                         // Special treatment for Mastodon
279                         // Problem is that Mastodon uses an URL format like http://domain.tld/@nick
280                         // But the webfinger for this format fails.
281                         if (!$webfinger && !empty($nick)) {
282                                 // Mastodon uses a "@" as prefix for usernames in their url format
283                                 $nick = ltrim($nick, '@');
284
285                                 $addr = $nick."@".$host;
286
287                                 $path = str_replace('{uri}', urlencode("acct:".$addr), $template);
288                                 $webfinger = self::webfinger($path, $type);
289                         }
290                 }
291
292                 if (!is_array($webfinger["links"])) {
293                         Logger::log("No webfinger links found for ".$uri, Logger::DEBUG);
294                         return false;
295                 }
296
297                 $data = [];
298
299                 foreach ($webfinger["links"] as $link) {
300                         $data[] = ["@attributes" => $link];
301                 }
302
303                 if (is_array($webfinger["aliases"])) {
304                         foreach ($webfinger["aliases"] as $alias) {
305                                 $data[] = ["@attributes" =>
306                                                         ["rel" => "alias",
307                                                                 "href" => $alias]];
308                         }
309                 }
310
311                 return $data;
312         }
313
314         /**
315          * @brief Fetch information (protocol endpoints and user information) about a given uri
316          *
317          * @param string  $uri     Address that should be probed
318          * @param string  $network Test for this specific network
319          * @param integer $uid     User ID for the probe (only used for mails)
320          * @param boolean $cache   Use cached values?
321          *
322          * @return array uri data
323          * @throws HTTPException\InternalServerErrorException
324          * @throws \ImagickException
325          */
326         public static function uri($uri, $network = '', $uid = -1, $cache = true)
327         {
328                 if ($cache) {
329                         $result = Cache::get('Probe::uri:' . $network . ':' . $uri);
330                         if (!is_null($result)) {
331                                 return $result;
332                         }
333                 }
334
335                 if ($uid == -1) {
336                         $uid = local_user();
337                 }
338
339                 self::$istimeout = false;
340
341                 if ($network != Protocol::ACTIVITYPUB) {
342                         $data = self::detect($uri, $network, $uid);
343                 } else {
344                         $data = null;
345                 }
346
347                 // When the previous detection process had got a time out
348                 // we could falsely detect a Friendica profile as AP profile.
349                 if (!self::$istimeout) {
350                         $ap_profile = ActivityPub::probeProfile($uri);
351
352                         if (!empty($ap_profile) && empty($network) && (defaults($data, 'network', '') != Protocol::DFRN)) {
353                                 $data = $ap_profile;
354                         }
355                 } else {
356                         Logger::notice('Time out detected. AP will not be probed.', ['uri' => $uri]);
357                 }
358
359                 if (!isset($data['url'])) {
360                         $data['url'] = $uri;
361                 }
362
363                 if (!empty($data['photo'])) {
364                         $data['baseurl'] = Network::getUrlMatch(Strings::normaliseLink(defaults($data, 'baseurl', '')), Strings::normaliseLink($data['photo']));
365                 } else {
366                         $data['photo'] = System::baseUrl() . '/images/person-300.jpg';
367                 }
368
369                 if (empty($data['name'])) {
370                         if (!empty($data['nick'])) {
371                                 $data['name'] = $data['nick'];
372                         }
373
374                         if (empty($data['name'])) {
375                                 $data['name'] = $data['url'];
376                         }
377                 }
378
379                 if (empty($data['nick'])) {
380                         $data['nick'] = strtolower($data['name']);
381
382                         if (strpos($data['nick'], ' ')) {
383                                 $data['nick'] = trim(substr($data['nick'], 0, strpos($data['nick'], ' ')));
384                         }
385                 }
386
387                 if (!empty(self::$baseurl)) {
388                         $data['baseurl'] = self::$baseurl;
389                 }
390
391                 if (empty($data['network'])) {
392                         $data['network'] = Protocol::PHANTOM;
393                 }
394
395                 $data = self::rearrangeData($data);
396
397                 // Only store into the cache if the value seems to be valid
398                 if (!in_array($data['network'], [Protocol::PHANTOM, Protocol::MAIL])) {
399                         Cache::set('Probe::uri:' . $network . ':' . $uri, $data, Cache::DAY);
400
401                         /// @todo temporary fix - we need a real contact update function that updates only changing fields
402                         /// The biggest problem is the avatar picture that could have a reduced image size.
403                         /// It should only be updated if the existing picture isn't existing anymore.
404                         /// We only update the contact when it is no probing for a specific network.
405                         if (($data['network'] != Protocol::FEED)
406                                 && ($network == '')
407                                 && $data['name']
408                                 && $data['nick']
409                                 && $data['url']
410                                 && $data['addr']
411                                 && $data['poll']
412                         ) {
413                                 $fields = [
414                                         'name' => $data['name'],
415                                         'nick' => $data['nick'],
416                                         'url' => $data['url'],
417                                         'addr' => $data['addr'],
418                                         'photo' => $data['photo'],
419                                         'keywords' => $data['keywords'],
420                                         'location' => $data['location'],
421                                         'about' => $data['about'],
422                                         'notify' => $data['notify'],
423                                         'network' => $data['network'],
424                                         'server_url' => $data['baseurl']
425                                 ];
426
427                                 // This doesn't cover the case when a community isn't a community anymore
428                                 if (!empty($data['community']) && $data['community']) {
429                                         $fields['community'] = $data['community'];
430                                         $fields['contact-type'] = Contact::TYPE_COMMUNITY;
431                                 }
432
433                                 $fieldnames = [];
434
435                                 foreach ($fields as $key => $val) {
436                                         if (empty($val)) {
437                                                 unset($fields[$key]);
438                                         } else {
439                                                 $fieldnames[] = $key;
440                                         }
441                                 }
442
443                                 $fields['updated'] = DateTimeFormat::utcNow();
444
445                                 $condition = ['nurl' => Strings::normaliseLink($data['url'])];
446
447                                 $old_fields = DBA::selectFirst('gcontact', $fieldnames, $condition);
448
449                                 // When the gcontact doesn't exist, the value "true" will trigger an insert.
450                                 // In difference to the public contacts we want to have every contact
451                                 // in the world in our global contacts.
452                                 if (!$old_fields) {
453                                         $old_fields = true;
454
455                                         // These values have to be set only on insert
456                                         $fields['photo'] = $data['photo'];
457                                         $fields['created'] = DateTimeFormat::utcNow();
458                                 }
459
460                                 DBA::update('gcontact', $fields, $condition, $old_fields);
461
462                                 $fields = [
463                                         'name' => $data['name'],
464                                         'nick' => $data['nick'],
465                                         'url' => $data['url'],
466                                         'addr' => $data['addr'],
467                                         'alias' => $data['alias'],
468                                         'keywords' => $data['keywords'],
469                                         'location' => $data['location'],
470                                         'about' => $data['about'],
471                                         'batch' => $data['batch'],
472                                         'notify' => $data['notify'],
473                                         'poll' => $data['poll'],
474                                         'request' => $data['request'],
475                                         'confirm' => $data['confirm'],
476                                         'poco' => $data['poco'],
477                                         'network' => $data['network'],
478                                         'pubkey' => $data['pubkey'],
479                                         'priority' => $data['priority'],
480                                         'writable' => true,
481                                         'rel' => Contact::SHARING
482                                 ];
483
484                                 $fieldnames = [];
485
486                                 foreach ($fields as $key => $val) {
487                                         if (empty($val)) {
488                                                 unset($fields[$key]);
489                                         } else {
490                                                 $fieldnames[] = $key;
491                                         }
492                                 }
493
494                                 $condition = ['nurl' => Strings::normaliseLink($data['url']), 'self' => false, 'uid' => 0];
495
496                                 // "$old_fields" will return a "false" when the contact doesn't exist.
497                                 // This won't trigger an insert. This is intended, since we only need
498                                 // public contacts for everyone we store items from.
499                                 // We don't need to store every contact on the planet.
500                                 $old_fields = DBA::selectFirst('contact', $fieldnames, $condition);
501
502                                 $fields['name-date'] = DateTimeFormat::utcNow();
503                                 $fields['uri-date'] = DateTimeFormat::utcNow();
504                                 $fields['success_update'] = DateTimeFormat::utcNow();
505
506                                 DBA::update('contact', $fields, $condition, $old_fields);
507                         }
508                 }
509
510                 return $data;
511         }
512
513         /**
514          * @brief Checks if a profile url should be OStatus but only provides partial information
515          *
516          * @param array  $webfinger Webfinger data
517          * @param string $lrdd      Path template for webfinger request
518          * @param string $type      type
519          *
520          * @return array fixed webfinger data
521          * @throws HTTPException\InternalServerErrorException
522          */
523         private static function fixOStatus($webfinger, $lrdd, $type)
524         {
525                 if (empty($webfinger['links']) || empty($webfinger['subject'])) {
526                         return $webfinger;
527                 }
528
529                 $is_ostatus = false;
530                 $has_key = false;
531
532                 foreach ($webfinger['links'] as $link) {
533                         if ($link['rel'] == NAMESPACE_OSTATUSSUB) {
534                                 $is_ostatus = true;
535                         }
536                         if ($link['rel'] == 'magic-public-key') {
537                                 $has_key = true;
538                         }
539                 }
540
541                 if (!$is_ostatus || $has_key) {
542                         return $webfinger;
543                 }
544
545                 $url = Network::switchScheme($webfinger['subject']);
546                 $path = str_replace('{uri}', urlencode($url), $lrdd);
547                 $webfinger2 = self::webfinger($path, $type);
548
549                 // Is the new webfinger detectable as OStatus?
550                 if (self::ostatus($webfinger2, true)) {
551                         $webfinger = $webfinger2;
552                 }
553
554                 return $webfinger;
555         }
556
557         /**
558          * @brief Fetch information (protocol endpoints and user information) about a given uri
559          *
560          * This function is only called by the "uri" function that adds caching and rearranging of data.
561          *
562          * @param string  $uri     Address that should be probed
563          * @param string  $network Test for this specific network
564          * @param integer $uid     User ID for the probe (only used for mails)
565          *
566          * @return array uri data
567          * @throws HTTPException\InternalServerErrorException
568          */
569         private static function detect($uri, $network, $uid)
570         {
571                 $parts = parse_url($uri);
572
573                 if (!empty($parts["scheme"]) && !empty($parts["host"])) {
574                         $host = $parts["host"];
575                         if (!empty($parts["port"])) {
576                                 $host .= ':'.$parts["port"];
577                         }
578
579                         if ($host == 'twitter.com') {
580                                 return ["network" => Protocol::TWITTER];
581                         }
582                         $lrdd = self::hostMeta($host);
583
584                         if (is_bool($lrdd)) {
585                                 return [];
586                         }
587
588                         $path_parts = explode("/", trim(defaults($parts, 'path', ''), "/"));
589
590                         while (!$lrdd && (sizeof($path_parts) > 1)) {
591                                 $host .= "/".array_shift($path_parts);
592                                 $lrdd = self::hostMeta($host);
593                         }
594                         if (!$lrdd) {
595                                 Logger::log('No XRD data was found for '.$uri, Logger::DEBUG);
596                                 return self::feed($uri);
597                         }
598                         $nick = array_pop($path_parts);
599
600                         // Mastodon uses a "@" as prefix for usernames in their url format
601                         $nick = ltrim($nick, '@');
602
603                         $addr = $nick."@".$host;
604                 } elseif (strstr($uri, '@')) {
605                         // If the URI starts with "mailto:" then jump directly to the mail detection
606                         if (strpos($uri, 'mailto:') !== false) {
607                                 $uri = str_replace('mailto:', '', $uri);
608                                 return self::mail($uri, $uid);
609                         }
610
611                         if ($network == Protocol::MAIL) {
612                                 return self::mail($uri, $uid);
613                         }
614                         // Remove "acct:" from the URI
615                         $uri = str_replace('acct:', '', $uri);
616
617                         $host = substr($uri, strpos($uri, '@') + 1);
618                         $nick = substr($uri, 0, strpos($uri, '@'));
619
620                         if (strpos($uri, '@twitter.com')) {
621                                 return ["network" => Protocol::TWITTER];
622                         }
623                         $lrdd = self::hostMeta($host);
624
625                         if (is_bool($lrdd)) {
626                                 return [];
627                         }
628
629                         if (!$lrdd) {
630                                 Logger::log('No XRD data was found for '.$uri, Logger::DEBUG);
631                                 return self::mail($uri, $uid);
632                         }
633                         $addr = $uri;
634                 } else {
635                         Logger::log("Uri ".$uri." was not detectable", Logger::DEBUG);
636                         return false;
637                 }
638
639                 $webfinger = false;
640
641                 /// @todo Do we need the prefix "acct:" or "acct://"?
642
643                 foreach ($lrdd as $type => $template) {
644                         if ($webfinger) {
645                                 continue;
646                         }
647
648                         // At first try it with the given uri
649                         $path = str_replace('{uri}', urlencode($uri), $template);
650                         $webfinger = self::webfinger($path, $type);
651
652                         // Fix possible problems with GNU Social probing to wrong scheme
653                         $webfinger = self::fixOStatus($webfinger, $template, $type);
654
655                         // We cannot be sure that the detected address was correct, so we don't use the values
656                         if ($webfinger && ($uri != $addr)) {
657                                 $nick = "";
658                                 $addr = "";
659                         }
660
661                         // Try webfinger with the address (user@domain.tld)
662                         if (!$webfinger) {
663                                 $path = str_replace('{uri}', urlencode($addr), $template);
664                                 $webfinger = self::webfinger($path, $type);
665                         }
666
667                         // Mastodon needs to have it with "acct:"
668                         if (!$webfinger) {
669                                 $path = str_replace('{uri}', urlencode("acct:".$addr), $template);
670                                 $webfinger = self::webfinger($path, $type);
671                         }
672                 }
673
674                 if (!$webfinger) {
675                         return self::feed($uri);
676                 }
677
678                 $result = false;
679
680                 Logger::log("Probing ".$uri, Logger::DEBUG);
681
682                 if (in_array($network, ["", Protocol::DFRN])) {
683                         $result = self::dfrn($webfinger);
684                 }
685                 if ((!$result && ($network == "")) || ($network == Protocol::DIASPORA)) {
686                         $result = self::diaspora($webfinger);
687                 }
688                 if ((!$result && ($network == "")) || ($network == Protocol::OSTATUS)) {
689                         $result = self::ostatus($webfinger);
690                 }
691                 if ((!$result && ($network == "")) || ($network == Protocol::PUMPIO)) {
692                         $result = self::pumpio($webfinger, $addr);
693                 }
694                 if ((!$result && ($network == "")) || ($network == Protocol::FEED)) {
695                         $result = self::feed($uri);
696                 } else {
697                         // We overwrite the detected nick with our try if the previois routines hadn't detected it.
698                         // Additionally it is overwritten when the nickname doesn't make sense (contains spaces).
699                         if ((empty($result["nick"]) || (strstr($result["nick"], " "))) && ($nick != "")) {
700                                 $result["nick"] = $nick;
701                         }
702
703                         if (empty($result["addr"]) && ($addr != "")) {
704                                 $result["addr"] = $addr;
705                         }
706                 }
707
708                 if (empty($result["network"])) {
709                         $result["network"] = Protocol::PHANTOM;
710                 }
711
712                 if (empty($result["url"])) {
713                         $result["url"] = $uri;
714                 }
715
716                 Logger::log($uri." is ".$result["network"], Logger::DEBUG);
717
718                 if (empty($result["baseurl"])) {
719                         $pos = strpos($result["url"], $host);
720                         if ($pos) {
721                                 $result["baseurl"] = substr($result["url"], 0, $pos).$host;
722                         }
723                 }
724                 return $result;
725         }
726
727         /**
728          * @brief Perform a webfinger request.
729          *
730          * For details see RFC 7033: <https://tools.ietf.org/html/rfc7033>
731          *
732          * @param string $url  Address that should be probed
733          * @param string $type type
734          *
735          * @return array webfinger data
736          * @throws HTTPException\InternalServerErrorException
737          */
738         private static function webfinger($url, $type)
739         {
740                 $xrd_timeout = Config::get('system', 'xrd_timeout', 20);
741                 $redirects = 0;
742
743                 $curlResult = Network::curl($url, false, $redirects, ['timeout' => $xrd_timeout, 'accept_content' => $type]);
744                 if ($curlResult->isTimeout()) {
745                         self::$istimeout = true;
746                         return false;
747                 }
748                 $data = $curlResult->getBody();
749
750                 $webfinger = json_decode($data, true);
751                 if (is_array($webfinger)) {
752                         if (!isset($webfinger["links"])) {
753                                 Logger::log("No json webfinger links for ".$url, Logger::DEBUG);
754                                 return false;
755                         }
756                         return $webfinger;
757                 }
758
759                 // If it is not JSON, maybe it is XML
760                 $xrd = XML::parseString($data, false);
761                 if (!is_object($xrd)) {
762                         Logger::log("No webfinger data retrievable for ".$url, Logger::DEBUG);
763                         return false;
764                 }
765
766                 $xrd_arr = XML::elementToArray($xrd);
767                 if (!isset($xrd_arr["xrd"]["link"])) {
768                         Logger::log("No XML webfinger links for ".$url, Logger::DEBUG);
769                         return false;
770                 }
771
772                 $webfinger = [];
773
774                 if (!empty($xrd_arr["xrd"]["subject"])) {
775                         $webfinger["subject"] = $xrd_arr["xrd"]["subject"];
776                 }
777
778                 if (!empty($xrd_arr["xrd"]["alias"])) {
779                         $webfinger["aliases"] = $xrd_arr["xrd"]["alias"];
780                 }
781
782                 $webfinger["links"] = [];
783
784                 foreach ($xrd_arr["xrd"]["link"] as $value => $data) {
785                         if (!empty($data["@attributes"])) {
786                                 $attributes = $data["@attributes"];
787                         } elseif ($value == "@attributes") {
788                                 $attributes = $data;
789                         } else {
790                                 continue;
791                         }
792
793                         $webfinger["links"][] = $attributes;
794                 }
795                 return $webfinger;
796         }
797
798         /**
799          * @brief Poll the Friendica specific noscrape page.
800          *
801          * "noscrape" is a faster alternative to fetch the data from the hcard.
802          * This functionality was originally created for the directory.
803          *
804          * @param string $noscrape_url Link to the noscrape page
805          * @param array  $data         The already fetched data
806          *
807          * @return array noscrape data
808          * @throws HTTPException\InternalServerErrorException
809          */
810         private static function pollNoscrape($noscrape_url, $data)
811         {
812                 $curlResult = Network::curl($noscrape_url);
813                 if ($curlResult->isTimeout()) {
814                         self::$istimeout = true;
815                         return false;
816                 }
817                 $content = $curlResult->getBody();
818                 if (!$content) {
819                         Logger::log("Empty body for ".$noscrape_url, Logger::DEBUG);
820                         return false;
821                 }
822
823                 $json = json_decode($content, true);
824                 if (!is_array($json)) {
825                         Logger::log("No json data for ".$noscrape_url, Logger::DEBUG);
826                         return false;
827                 }
828
829                 if (!empty($json["fn"])) {
830                         $data["name"] = $json["fn"];
831                 }
832
833                 if (!empty($json["addr"])) {
834                         $data["addr"] = $json["addr"];
835                 }
836
837                 if (!empty($json["nick"])) {
838                         $data["nick"] = $json["nick"];
839                 }
840
841                 if (!empty($json["guid"])) {
842                         $data["guid"] = $json["guid"];
843                 }
844
845                 if (!empty($json["comm"])) {
846                         $data["community"] = $json["comm"];
847                 }
848
849                 if (!empty($json["tags"])) {
850                         $keywords = implode(" ", $json["tags"]);
851                         if ($keywords != "") {
852                                 $data["keywords"] = $keywords;
853                         }
854                 }
855
856                 $location = Profile::formatLocation($json);
857                 if ($location) {
858                         $data["location"] = $location;
859                 }
860
861                 if (!empty($json["about"])) {
862                         $data["about"] = $json["about"];
863                 }
864
865                 if (!empty($json["key"])) {
866                         $data["pubkey"] = $json["key"];
867                 }
868
869                 if (!empty($json["photo"])) {
870                         $data["photo"] = $json["photo"];
871                 }
872
873                 if (!empty($json["dfrn-request"])) {
874                         $data["request"] = $json["dfrn-request"];
875                 }
876
877                 if (!empty($json["dfrn-confirm"])) {
878                         $data["confirm"] = $json["dfrn-confirm"];
879                 }
880
881                 if (!empty($json["dfrn-notify"])) {
882                         $data["notify"] = $json["dfrn-notify"];
883                 }
884
885                 if (!empty($json["dfrn-poll"])) {
886                         $data["poll"] = $json["dfrn-poll"];
887                 }
888
889                 return $data;
890         }
891
892         /**
893          * @brief Check for valid DFRN data
894          *
895          * @param array $data DFRN data
896          *
897          * @return int Number of errors
898          */
899         public static function validDfrn($data)
900         {
901                 $errors = 0;
902                 if (!isset($data['key'])) {
903                         $errors ++;
904                 }
905                 if (!isset($data['dfrn-request'])) {
906                         $errors ++;
907                 }
908                 if (!isset($data['dfrn-confirm'])) {
909                         $errors ++;
910                 }
911                 if (!isset($data['dfrn-notify'])) {
912                         $errors ++;
913                 }
914                 if (!isset($data['dfrn-poll'])) {
915                         $errors ++;
916                 }
917                 return $errors;
918         }
919
920         /**
921          * @brief Fetch data from a DFRN profile page and via "noscrape"
922          *
923          * @param string $profile_link Link to the profile page
924          *
925          * @return array profile data
926          * @throws HTTPException\InternalServerErrorException
927          * @throws \ImagickException
928          */
929         public static function profile($profile_link)
930         {
931                 $data = [];
932
933                 Logger::log("Check profile ".$profile_link, Logger::DEBUG);
934
935                 // Fetch data via noscrape - this is faster
936                 $noscrape_url = str_replace(["/hcard/", "/profile/"], "/noscrape/", $profile_link);
937                 $data = self::pollNoscrape($noscrape_url, $data);
938
939                 if (!isset($data["notify"])
940                         || !isset($data["confirm"])
941                         || !isset($data["request"])
942                         || !isset($data["poll"])
943                         || !isset($data["name"])
944                         || !isset($data["photo"])
945                 ) {
946                         $data = self::pollHcard($profile_link, $data, true);
947                 }
948
949                 $prof_data = [];
950
951                 if (empty($data["addr"]) || empty($data["nick"])) {
952                         $probe_data = self::uri($profile_link);
953                         $data["addr"] = defaults($data, "addr", $probe_data["addr"]);
954                         $data["nick"] = defaults($data, "nick", $probe_data["nick"]);
955                 }
956
957                 $prof_data["addr"]         = $data["addr"];
958                 $prof_data["nick"]         = $data["nick"];
959                 $prof_data["dfrn-request"] = defaults($data, 'request', null);
960                 $prof_data["dfrn-confirm"] = defaults($data, 'confirm', null);
961                 $prof_data["dfrn-notify"]  = defaults($data, 'notify' , null);
962                 $prof_data["dfrn-poll"]    = defaults($data, 'poll'   , null);
963                 $prof_data["photo"]        = defaults($data, 'photo'  , null);
964                 $prof_data["fn"]           = defaults($data, 'name'   , null);
965                 $prof_data["key"]          = defaults($data, 'pubkey' , null);
966
967                 Logger::log("Result for profile ".$profile_link.": ".print_r($prof_data, true), Logger::DEBUG);
968
969                 return $prof_data;
970         }
971
972         /**
973          * @brief Check for DFRN contact
974          *
975          * @param array $webfinger Webfinger data
976          *
977          * @return array DFRN data
978          * @throws HTTPException\InternalServerErrorException
979          */
980         private static function dfrn($webfinger)
981         {
982                 $hcard_url = "";
983                 $data = [];
984                 // The array is reversed to take into account the order of preference for same-rel links
985                 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
986                 foreach (array_reverse($webfinger["links"]) as $link) {
987                         if (($link["rel"] == NAMESPACE_DFRN) && !empty($link["href"])) {
988                                 $data["network"] = Protocol::DFRN;
989                         } elseif (($link["rel"] == NAMESPACE_FEED) && !empty($link["href"])) {
990                                 $data["poll"] = $link["href"];
991                         } elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") && (defaults($link, "type", "") == "text/html") && !empty($link["href"])) {
992                                 $data["url"] = $link["href"];
993                         } elseif (($link["rel"] == "http://microformats.org/profile/hcard") && !empty($link["href"])) {
994                                 $hcard_url = $link["href"];
995                         } elseif (($link["rel"] == NAMESPACE_POCO) && !empty($link["href"])) {
996                                 $data["poco"] = $link["href"];
997                         } elseif (($link["rel"] == "http://webfinger.net/rel/avatar") && !empty($link["href"])) {
998                                 $data["photo"] = $link["href"];
999                         } elseif (($link["rel"] == "http://joindiaspora.com/seed_location") && !empty($link["href"])) {
1000                                 $data["baseurl"] = trim($link["href"], '/');
1001                         } elseif (($link["rel"] == "http://joindiaspora.com/guid") && !empty($link["href"])) {
1002                                 $data["guid"] = $link["href"];
1003                         } elseif (($link["rel"] == "diaspora-public-key") && !empty($link["href"])) {
1004                                 $data["pubkey"] = base64_decode($link["href"]);
1005
1006                                 //if (strstr($data["pubkey"], 'RSA ') || ($link["type"] == "RSA"))
1007                                 if (strstr($data["pubkey"], 'RSA ')) {
1008                                         $data["pubkey"] = Crypto::rsaToPem($data["pubkey"]);
1009                                 }
1010                         }
1011                 }
1012
1013                 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
1014                         foreach ($webfinger["aliases"] as $alias) {
1015                                 if (empty($data["url"]) && !strstr($alias, "@")) {
1016                                         $data["url"] = $alias;
1017                                 } elseif (!strstr($alias, "@") && Strings::normaliseLink($alias) != Strings::normaliseLink($data["url"])) {
1018                                         $data["alias"] = $alias;
1019                                 } elseif (substr($alias, 0, 5) == 'acct:') {
1020                                         $data["addr"] = substr($alias, 5);
1021                                 }
1022                         }
1023                 }
1024
1025                 if (!empty($webfinger["subject"]) && (substr($webfinger["subject"], 0, 5) == "acct:")) {
1026                         $data["addr"] = substr($webfinger["subject"], 5);
1027                 }
1028
1029                 if (!isset($data["network"]) || ($hcard_url == "")) {
1030                         return false;
1031                 }
1032
1033                 // Fetch data via noscrape - this is faster
1034                 $noscrape_url = str_replace("/hcard/", "/noscrape/", $hcard_url);
1035                 $data = self::pollNoscrape($noscrape_url, $data);
1036
1037                 if (isset($data["notify"])
1038                         && isset($data["confirm"])
1039                         && isset($data["request"])
1040                         && isset($data["poll"])
1041                         && isset($data["name"])
1042                         && isset($data["photo"])
1043                 ) {
1044                         return $data;
1045                 }
1046
1047                 $data = self::pollHcard($hcard_url, $data, true);
1048
1049                 return $data;
1050         }
1051
1052         /**
1053          * @brief Poll the hcard page (Diaspora and Friendica specific)
1054          *
1055          * @param string  $hcard_url Link to the hcard page
1056          * @param array   $data      The already fetched data
1057          * @param boolean $dfrn      Poll DFRN specific data
1058          *
1059          * @return array hcard data
1060          * @throws HTTPException\InternalServerErrorException
1061          */
1062         private static function pollHcard($hcard_url, $data, $dfrn = false)
1063         {
1064                 $curlResult = Network::curl($hcard_url);
1065                 if ($curlResult->isTimeout()) {
1066                         self::$istimeout = true;
1067                         return false;
1068                 }
1069                 $content = $curlResult->getBody();
1070                 if (!$content) {
1071                         return false;
1072                 }
1073
1074                 $doc = new DOMDocument();
1075                 if (!@$doc->loadHTML($content)) {
1076                         return false;
1077                 }
1078
1079                 $xpath = new DomXPath($doc);
1080
1081                 $vcards = $xpath->query("//div[contains(concat(' ', @class, ' '), ' vcard ')]");
1082                 if (!is_object($vcards)) {
1083                         return false;
1084                 }
1085
1086                 if (!isset($data["baseurl"])) {
1087                         $data["baseurl"] = "";
1088                 }
1089
1090                 if ($vcards->length > 0) {
1091                         $vcard = $vcards->item(0);
1092
1093                         // We have to discard the guid from the hcard in favour of the guid from lrdd
1094                         // Reason: Hubzilla doesn't use the value "uid" in the hcard like Diaspora does.
1095                         $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' uid ')]", $vcard); // */
1096                         if (($search->length > 0) && empty($data["guid"])) {
1097                                 $data["guid"] = $search->item(0)->nodeValue;
1098                         }
1099
1100                         $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' nickname ')]", $vcard); // */
1101                         if ($search->length > 0) {
1102                                 $data["nick"] = $search->item(0)->nodeValue;
1103                         }
1104
1105                         $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' fn ')]", $vcard); // */
1106                         if ($search->length > 0) {
1107                                 $data["name"] = $search->item(0)->nodeValue;
1108                         }
1109
1110                         $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' searchable ')]", $vcard); // */
1111                         if ($search->length > 0) {
1112                                 $data["searchable"] = $search->item(0)->nodeValue;
1113                         }
1114
1115                         $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' key ')]", $vcard); // */
1116                         if ($search->length > 0) {
1117                                 $data["pubkey"] = $search->item(0)->nodeValue;
1118                                 if (strstr($data["pubkey"], 'RSA ')) {
1119                                         $data["pubkey"] = Crypto::rsaToPem($data["pubkey"]);
1120                                 }
1121                         }
1122
1123                         $search = $xpath->query("//*[@id='pod_location']", $vcard); // */
1124                         if ($search->length > 0) {
1125                                 $data["baseurl"] = trim($search->item(0)->nodeValue, "/");
1126                         }
1127                 }
1128
1129                 $avatar = [];
1130                 if (!empty($vcard)) {
1131                         $photos = $xpath->query("//*[contains(concat(' ', @class, ' '), ' photo ') or contains(concat(' ', @class, ' '), ' avatar ')]", $vcard); // */
1132                         foreach ($photos as $photo) {
1133                                 $attr = [];
1134                                 foreach ($photo->attributes as $attribute) {
1135                                         $attr[$attribute->name] = trim($attribute->value);
1136                                 }
1137
1138                                 if (isset($attr["src"]) && isset($attr["width"])) {
1139                                         $avatar[$attr["width"]] = $attr["src"];
1140                                 }
1141
1142                                 // We don't have a width. So we just take everything that we got.
1143                                 // This is a Hubzilla workaround which doesn't send a width.
1144                                 if ((sizeof($avatar) == 0) && !empty($attr["src"])) {
1145                                         $avatar[] = $attr["src"];
1146                                 }
1147                         }
1148                 }
1149
1150                 if (sizeof($avatar)) {
1151                         ksort($avatar);
1152                         $data["photo"] = self::fixAvatar(array_pop($avatar), $data["baseurl"]);
1153                 }
1154
1155                 if ($dfrn) {
1156                         // Poll DFRN specific data
1157                         $search = $xpath->query("//link[contains(concat(' ', @rel), ' dfrn-')]");
1158                         if ($search->length > 0) {
1159                                 foreach ($search as $link) {
1160                                         //$data["request"] = $search->item(0)->nodeValue;
1161                                         $attr = [];
1162                                         foreach ($link->attributes as $attribute) {
1163                                                 $attr[$attribute->name] = trim($attribute->value);
1164                                         }
1165
1166                                         $data[substr($attr["rel"], 5)] = $attr["href"];
1167                                 }
1168                         }
1169
1170                         // Older Friendica versions had used the "uid" field differently than newer versions
1171                         if (!empty($data["nick"]) && !empty($data["guid"]) && ($data["nick"] == $data["guid"])) {
1172                                 unset($data["guid"]);
1173                         }
1174                 }
1175
1176
1177                 return $data;
1178         }
1179
1180         /**
1181          * @brief Check for Diaspora contact
1182          *
1183          * @param array $webfinger Webfinger data
1184          *
1185          * @return array Diaspora data
1186          * @throws HTTPException\InternalServerErrorException
1187          */
1188         private static function diaspora($webfinger)
1189         {
1190                 $hcard_url = "";
1191                 $data = [];
1192                 // The array is reversed to take into account the order of preference for same-rel links
1193                 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1194                 foreach (array_reverse($webfinger["links"]) as $link) {
1195                         if (($link["rel"] == "http://microformats.org/profile/hcard") && !empty($link["href"])) {
1196                                 $hcard_url = $link["href"];
1197                         } elseif (($link["rel"] == "http://joindiaspora.com/seed_location") && !empty($link["href"])) {
1198                                 $data["baseurl"] = trim($link["href"], '/');
1199                         } elseif (($link["rel"] == "http://joindiaspora.com/guid") && !empty($link["href"])) {
1200                                 $data["guid"] = $link["href"];
1201                         } elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") && (defaults($link, "type", "") == "text/html") && !empty($link["href"])) {
1202                                 $data["url"] = $link["href"];
1203                         } elseif (($link["rel"] == NAMESPACE_FEED) && !empty($link["href"])) {
1204                                 $data["poll"] = $link["href"];
1205                         } elseif (($link["rel"] == NAMESPACE_POCO) && !empty($link["href"])) {
1206                                 $data["poco"] = $link["href"];
1207                         } elseif (($link["rel"] == "salmon") && !empty($link["href"])) {
1208                                 $data["notify"] = $link["href"];
1209                         } elseif (($link["rel"] == "diaspora-public-key") && !empty($link["href"])) {
1210                                 $data["pubkey"] = base64_decode($link["href"]);
1211
1212                                 //if (strstr($data["pubkey"], 'RSA ') || ($link["type"] == "RSA"))
1213                                 if (strstr($data["pubkey"], 'RSA ')) {
1214                                         $data["pubkey"] = Crypto::rsaToPem($data["pubkey"]);
1215                                 }
1216                         }
1217                 }
1218
1219                 if (!isset($data["url"]) || ($hcard_url == "")) {
1220                         return false;
1221                 }
1222
1223                 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
1224                         foreach ($webfinger["aliases"] as $alias) {
1225                                 if (Strings::normaliseLink($alias) != Strings::normaliseLink($data["url"]) && ! strstr($alias, "@")) {
1226                                         $data["alias"] = $alias;
1227                                 } elseif (substr($alias, 0, 5) == 'acct:') {
1228                                         $data["addr"] = substr($alias, 5);
1229                                 }
1230                         }
1231                 }
1232
1233                 if (!empty($webfinger["subject"]) && (substr($webfinger["subject"], 0, 5) == 'acct:')) {
1234                         $data["addr"] = substr($webfinger["subject"], 5);
1235                 }
1236
1237                 // Fetch further information from the hcard
1238                 $data = self::pollHcard($hcard_url, $data);
1239
1240                 if (!$data) {
1241                         return false;
1242                 }
1243
1244                 if (isset($data["url"])
1245                         && isset($data["guid"])
1246                         && isset($data["baseurl"])
1247                         && isset($data["pubkey"])
1248                         && ($hcard_url != "")
1249                 ) {
1250                         $data["network"] = Protocol::DIASPORA;
1251
1252                         // The Diaspora handle must always be lowercase
1253                         if (!empty($data["addr"])) {
1254                                 $data["addr"] = strtolower($data["addr"]);
1255                         }
1256
1257                         // We have to overwrite the detected value for "notify" since Hubzilla doesn't send it
1258                         $data["notify"] = $data["baseurl"] . "/receive/users/" . $data["guid"];
1259                         $data["batch"]  = $data["baseurl"] . "/receive/public";
1260                 } else {
1261                         return false;
1262                 }
1263
1264                 return $data;
1265         }
1266
1267         /**
1268          * @brief Check for OStatus contact
1269          *
1270          * @param array $webfinger Webfinger data
1271          * @param bool  $short     Short detection mode
1272          *
1273          * @return array|bool OStatus data or "false" on error or "true" on short mode
1274          * @throws HTTPException\InternalServerErrorException
1275          */
1276         private static function ostatus($webfinger, $short = false)
1277         {
1278                 $data = [];
1279
1280                 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
1281                         foreach ($webfinger["aliases"] as $alias) {
1282                                 if (strstr($alias, "@") && !strstr(Strings::normaliseLink($alias), "http://")) {
1283                                         $data["addr"] = str_replace('acct:', '', $alias);
1284                                 }
1285                         }
1286                 }
1287
1288                 if (!empty($webfinger["subject"]) && strstr($webfinger["subject"], "@")
1289                         && !strstr(Strings::normaliseLink($webfinger["subject"]), "http://")
1290                 ) {
1291                         $data["addr"] = str_replace('acct:', '', $webfinger["subject"]);
1292                 }
1293
1294                 if (is_array($webfinger["links"])) {
1295                         // The array is reversed to take into account the order of preference for same-rel links
1296                         // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1297                         foreach (array_reverse($webfinger["links"]) as $link) {
1298                                 if (($link["rel"] == "http://webfinger.net/rel/profile-page")
1299                                         && (defaults($link, "type", "") == "text/html")
1300                                         && ($link["href"] != "")
1301                                 ) {
1302                                         $data["url"] = $link["href"];
1303                                 } elseif (($link["rel"] == "salmon") && !empty($link["href"])) {
1304                                         $data["notify"] = $link["href"];
1305                                 } elseif (($link["rel"] == NAMESPACE_FEED) && !empty($link["href"])) {
1306                                         $data["poll"] = $link["href"];
1307                                 } elseif (($link["rel"] == "magic-public-key") && !empty($link["href"])) {
1308                                         $pubkey = $link["href"];
1309
1310                                         if (substr($pubkey, 0, 5) === 'data:') {
1311                                                 if (strstr($pubkey, ',')) {
1312                                                         $pubkey = substr($pubkey, strpos($pubkey, ',') + 1);
1313                                                 } else {
1314                                                         $pubkey = substr($pubkey, 5);
1315                                                 }
1316                                         } elseif (Strings::normaliseLink($pubkey) == 'http://') {
1317                                                 $curlResult = Network::curl($pubkey);
1318                                                 if ($curlResult->isTimeout()) {
1319                                                         self::$istimeout = true;
1320                                                         return false;
1321                                                 }
1322                                                 $pubkey = $curlResult->getBody();
1323                                         }
1324
1325                                         $key = explode(".", $pubkey);
1326
1327                                         if (sizeof($key) >= 3) {
1328                                                 $m = Strings::base64UrlDecode($key[1]);
1329                                                 $e = Strings::base64UrlDecode($key[2]);
1330                                                 $data["pubkey"] = Crypto::meToPem($m, $e);
1331                                         }
1332                                 }
1333                         }
1334                 }
1335
1336                 if (isset($data["notify"]) && isset($data["pubkey"])
1337                         && isset($data["poll"])
1338                         && isset($data["url"])
1339                 ) {
1340                         $data["network"] = Protocol::OSTATUS;
1341                 } else {
1342                         return false;
1343                 }
1344
1345                 if ($short) {
1346                         return true;
1347                 }
1348
1349                 // Fetch all additional data from the feed
1350                 $curlResult = Network::curl($data["poll"]);
1351                 if ($curlResult->isTimeout()) {
1352                         self::$istimeout = true;
1353                         return false;
1354                 }
1355                 $feed = $curlResult->getBody();
1356                 $dummy1 = null;
1357                 $dummy2 = null;
1358                 $dummy2 = null;
1359                 $feed_data = Feed::import($feed, $dummy1, $dummy2, $dummy3, true);
1360                 if (!$feed_data) {
1361                         return false;
1362                 }
1363
1364                 if (!empty($feed_data["header"]["author-name"])) {
1365                         $data["name"] = $feed_data["header"]["author-name"];
1366                 }
1367                 if (!empty($feed_data["header"]["author-nick"])) {
1368                         $data["nick"] = $feed_data["header"]["author-nick"];
1369                 }
1370                 if (!empty($feed_data["header"]["author-avatar"])) {
1371                         $data["photo"] = self::fixAvatar($feed_data["header"]["author-avatar"], $data["url"]);
1372                 }
1373                 if (!empty($feed_data["header"]["author-id"])) {
1374                         $data["alias"] = $feed_data["header"]["author-id"];
1375                 }
1376                 if (!empty($feed_data["header"]["author-location"])) {
1377                         $data["location"] = $feed_data["header"]["author-location"];
1378                 }
1379                 if (!empty($feed_data["header"]["author-about"])) {
1380                         $data["about"] = $feed_data["header"]["author-about"];
1381                 }
1382                 // OStatus has serious issues when the the url doesn't fit (ssl vs. non ssl)
1383                 // So we take the value that we just fetched, although the other one worked as well
1384                 if (!empty($feed_data["header"]["author-link"])) {
1385                         $data["url"] = $feed_data["header"]["author-link"];
1386                 }
1387
1388                 if (($data['poll'] == $data['url']) && ($data["alias"] != '')) {
1389                         $data['url'] = $data["alias"];
1390                         $data["alias"] = '';
1391                 }
1392
1393                 /// @todo Fetch location and "about" from the feed as well
1394                 return $data;
1395         }
1396
1397         /**
1398          * @brief Fetch data from a pump.io profile page
1399          *
1400          * @param string $profile_link Link to the profile page
1401          *
1402          * @return array profile data
1403          */
1404         private static function pumpioProfileData($profile_link)
1405         {
1406                 $doc = new DOMDocument();
1407                 if (!@$doc->loadHTMLFile($profile_link)) {
1408                         return false;
1409                 }
1410
1411                 $xpath = new DomXPath($doc);
1412
1413                 $data = [];
1414
1415                 $data["name"] = $xpath->query("//span[contains(@class, 'p-name')]")->item(0)->nodeValue;
1416
1417                 if ($data["name"] == '') {
1418                         // This is ugly - but pump.io doesn't seem to know a better way for it
1419                         $data["name"] = trim($xpath->query("//h1[@class='media-header']")->item(0)->nodeValue);
1420                         $pos = strpos($data["name"], chr(10));
1421                         if ($pos) {
1422                                 $data["name"] = trim(substr($data["name"], 0, $pos));
1423                         }
1424                 }
1425
1426                 $data["location"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'p-locality')]");
1427
1428                 if ($data["location"] == '') {
1429                         $data["location"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'location')]");
1430                 }
1431
1432                 $data["about"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'p-note')]");
1433
1434                 if ($data["about"] == '') {
1435                         $data["about"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'summary')]");
1436                 }
1437
1438                 $avatar = $xpath->query("//img[contains(@class, 'u-photo')]")->item(0);
1439                 if (!$avatar) {
1440                         $avatar = $xpath->query("//img[@class='img-rounded media-object']")->item(0);
1441                 }
1442                 if ($avatar) {
1443                         foreach ($avatar->attributes as $attribute) {
1444                                 if ($attribute->name == "src") {
1445                                         $data["photo"] = trim($attribute->value);
1446                                 }
1447                         }
1448                 }
1449
1450                 return $data;
1451         }
1452
1453         /**
1454          * @brief Check for pump.io contact
1455          *
1456          * @param array $webfinger Webfinger data
1457          *
1458          * @param       $addr
1459          * @return array pump.io data
1460          */
1461         private static function pumpio($webfinger, $addr)
1462         {
1463                 $data = [];
1464                 // The array is reversed to take into account the order of preference for same-rel links
1465                 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1466                 foreach (array_reverse($webfinger["links"]) as $link) {
1467                         if (($link["rel"] == "http://webfinger.net/rel/profile-page")
1468                                 && (defaults($link, "type", "") == "text/html")
1469                                 && ($link["href"] != "")
1470                         ) {
1471                                 $data["url"] = $link["href"];
1472                         } elseif (($link["rel"] == "activity-inbox") && ($link["href"] != "")) {
1473                                 $data["notify"] = $link["href"];
1474                         } elseif (($link["rel"] == "activity-outbox") && ($link["href"] != "")) {
1475                                 $data["poll"] = $link["href"];
1476                         } elseif (($link["rel"] == "dialback") && ($link["href"] != "")) {
1477                                 $data["dialback"] = $link["href"];
1478                         }
1479                 }
1480                 if (isset($data["poll"]) && isset($data["notify"])
1481                         && isset($data["dialback"])
1482                         && isset($data["url"])
1483                 ) {
1484                         // by now we use these fields only for the network type detection
1485                         // So we unset all data that isn't used at the moment
1486                         unset($data["dialback"]);
1487
1488                         $data["network"] = Protocol::PUMPIO;
1489                 } else {
1490                         return false;
1491                 }
1492
1493                 $profile_data = self::pumpioProfileData($data["url"]);
1494
1495                 if (!$profile_data) {
1496                         return false;
1497                 }
1498
1499                 $data = array_merge($data, $profile_data);
1500
1501                 if (($addr != '') && ($data['name'] != '')) {
1502                         $name = trim(str_replace($addr, '', $data['name']));
1503                         if ($name != '') {
1504                                 $data['name'] = $name;
1505                         }
1506                 }
1507
1508                 return $data;
1509         }
1510
1511         /**
1512          * @brief Check page for feed link
1513          *
1514          * @param string $url Page link
1515          *
1516          * @return string feed link
1517          */
1518         private static function getFeedLink($url)
1519         {
1520                 $doc = new DOMDocument();
1521
1522                 if (!@$doc->loadHTMLFile($url)) {
1523                         return false;
1524                 }
1525
1526                 $xpath = new DomXPath($doc);
1527
1528                 //$feeds = $xpath->query("/html/head/link[@type='application/rss+xml']");
1529                 $feeds = $xpath->query("/html/head/link[@type='application/rss+xml' and @rel='alternate']");
1530                 if (!is_object($feeds)) {
1531                         return false;
1532                 }
1533
1534                 if ($feeds->length == 0) {
1535                         return false;
1536                 }
1537
1538                 $feed_url = "";
1539
1540                 foreach ($feeds as $feed) {
1541                         $attr = [];
1542                         foreach ($feed->attributes as $attribute) {
1543                                 $attr[$attribute->name] = trim($attribute->value);
1544                         }
1545
1546                         if ($feed_url == "") {
1547                                 $feed_url = $attr["href"];
1548                         }
1549                 }
1550
1551                 return $feed_url;
1552         }
1553
1554         /**
1555          * @brief Check for feed contact
1556          *
1557          * @param string  $url   Profile link
1558          * @param boolean $probe Do a probe if the page contains a feed link
1559          *
1560          * @return array feed data
1561          * @throws HTTPException\InternalServerErrorException
1562          */
1563         private static function feed($url, $probe = true)
1564         {
1565                 $curlResult = Network::curl($url);
1566                 if ($curlResult->isTimeout()) {
1567                         self::$istimeout = true;
1568                         return false;
1569                 }
1570                 $feed = $curlResult->getBody();
1571                 $dummy1 = $dummy2 = $dummy3 = null;
1572                 $feed_data = Feed::import($feed, $dummy1, $dummy2, $dummy3, true);
1573
1574                 if (!$feed_data) {
1575                         if (!$probe) {
1576                                 return false;
1577                         }
1578
1579                         $feed_url = self::getFeedLink($url);
1580
1581                         if (!$feed_url) {
1582                                 return false;
1583                         }
1584
1585                         return self::feed($feed_url, false);
1586                 }
1587
1588                 if (!empty($feed_data["header"]["author-name"])) {
1589                         $data["name"] = $feed_data["header"]["author-name"];
1590                 }
1591
1592                 if (!empty($feed_data["header"]["author-nick"])) {
1593                         $data["nick"] = $feed_data["header"]["author-nick"];
1594                 }
1595
1596                 if (!empty($feed_data["header"]["author-avatar"])) {
1597                         $data["photo"] = $feed_data["header"]["author-avatar"];
1598                 }
1599
1600                 if (!empty($feed_data["header"]["author-id"])) {
1601                         $data["alias"] = $feed_data["header"]["author-id"];
1602                 }
1603
1604                 $data["url"] = $url;
1605                 $data["poll"] = $url;
1606
1607                 if (!empty($feed_data["header"]["author-link"])) {
1608                         $data["baseurl"] = $feed_data["header"]["author-link"];
1609                 } else {
1610                         $data["baseurl"] = $data["url"];
1611                 }
1612
1613                 $data["network"] = Protocol::FEED;
1614
1615                 return $data;
1616         }
1617
1618         /**
1619          * @brief Check for mail contact
1620          *
1621          * @param string  $uri Profile link
1622          * @param integer $uid User ID
1623          *
1624          * @return array mail data
1625          * @throws \Exception
1626          */
1627         private static function mail($uri, $uid)
1628         {
1629                 if (!Network::isEmailDomainValid($uri)) {
1630                         return false;
1631                 }
1632
1633                 if ($uid == 0) {
1634                         return false;
1635                 }
1636
1637                 $user = DBA::selectFirst('user', ['prvkey'], ['uid' => $uid]);
1638
1639                 $condition = ["`uid` = ? AND `server` != ''", $uid];
1640                 $fields = ['pass', 'user', 'server', 'port', 'ssltype', 'mailbox'];
1641                 $mailacct = DBA::selectFirst('mailacct', $fields, $condition);
1642
1643                 if (!DBA::isResult($user) || !DBA::isResult($mailacct)) {
1644                         return false;
1645                 }
1646
1647                 $mailbox = Email::constructMailboxName($mailacct);
1648                 $password = '';
1649                 openssl_private_decrypt(hex2bin($mailacct['pass']), $password, $user['prvkey']);
1650                 $mbox = Email::connect($mailbox, $mailacct['user'], $password);
1651                 if (!$mbox) {
1652                         return false;
1653                 }
1654
1655                 $msgs = Email::poll($mbox, $uri);
1656                 Logger::log('searching '.$uri.', '.count($msgs).' messages found.', Logger::DEBUG);
1657
1658                 if (!count($msgs)) {
1659                         return false;
1660                 }
1661
1662                 $phost = substr($uri, strpos($uri, '@') + 1);
1663
1664                 $data = [];
1665                 $data["addr"]    = $uri;
1666                 $data["network"] = Protocol::MAIL;
1667                 $data["name"]    = substr($uri, 0, strpos($uri, '@'));
1668                 $data["nick"]    = $data["name"];
1669                 $data["photo"]   = Network::lookupAvatarByEmail($uri);
1670                 $data["url"]     = 'mailto:'.$uri;
1671                 $data["notify"]  = 'smtp ' . Strings::getRandomHex();
1672                 $data["poll"]    = 'email ' . Strings::getRandomHex();
1673
1674                 $x = Email::messageMeta($mbox, $msgs[0]);
1675                 if (stristr($x[0]->from, $uri)) {
1676                         $adr = imap_rfc822_parse_adrlist($x[0]->from, '');
1677                 } elseif (stristr($x[0]->to, $uri)) {
1678                         $adr = imap_rfc822_parse_adrlist($x[0]->to, '');
1679                 }
1680                 if (isset($adr)) {
1681                         foreach ($adr as $feadr) {
1682                                 if ((strcasecmp($feadr->mailbox, $data["name"]) == 0)
1683                                         &&(strcasecmp($feadr->host, $phost) == 0)
1684                                         && (strlen($feadr->personal))
1685                                 ) {
1686                                         $personal = imap_mime_header_decode($feadr->personal);
1687                                         $data["name"] = "";
1688                                         foreach ($personal as $perspart) {
1689                                                 if ($perspart->charset != "default") {
1690                                                         $data["name"] .= iconv($perspart->charset, 'UTF-8//IGNORE', $perspart->text);
1691                                                 } else {
1692                                                         $data["name"] .= $perspart->text;
1693                                                 }
1694                                         }
1695
1696                                         $data["name"] = Strings::escapeTags($data["name"]);
1697                                 }
1698                         }
1699                 }
1700                 if (!empty($mbox)) {
1701                         imap_close($mbox);
1702                 }
1703                 return $data;
1704         }
1705
1706         /**
1707          * @brief Mix two paths together to possibly fix missing parts
1708          *
1709          * @param string $avatar Path to the avatar
1710          * @param string $base   Another path that is hopefully complete
1711          *
1712          * @return string fixed avatar path
1713          * @throws \Exception
1714          */
1715         public static function fixAvatar($avatar, $base)
1716         {
1717                 $base_parts = parse_url($base);
1718
1719                 // Remove all parts that could create a problem
1720                 unset($base_parts['path']);
1721                 unset($base_parts['query']);
1722                 unset($base_parts['fragment']);
1723
1724                 $avatar_parts = parse_url($avatar);
1725
1726                 // Now we mix them
1727                 $parts = array_merge($base_parts, $avatar_parts);
1728
1729                 // And put them together again
1730                 $scheme   = isset($parts['scheme'])   ? $parts['scheme'] . '://' : '';
1731                 $host     = isset($parts['host'])     ? $parts['host']           : '';
1732                 $port     = isset($parts['port'])     ? ':' . $parts['port']     : '';
1733                 $path     = isset($parts['path'])     ? $parts['path']           : '';
1734                 $query    = isset($parts['query'])    ? '?' . $parts['query']    : '';
1735                 $fragment = isset($parts['fragment']) ? '#' . $parts['fragment'] : '';
1736
1737                 $fixed = $scheme.$host.$port.$path.$query.$fragment;
1738
1739                 Logger::log('Base: '.$base.' - Avatar: '.$avatar.' - Fixed: '.$fixed, Logger::DATA);
1740
1741                 return $fixed;
1742         }
1743 }