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