]> git.mxchange.org Git - friendica.git/blob - src/Network/Probe.php
port hubzillas OpenWebAuth - remote authentification
[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 Friendica\App;
13 use Friendica\Core\System;
14 use Friendica\Core\Cache;
15 use Friendica\Core\Config;
16 use Friendica\Database\DBM;
17 use Friendica\Model\Profile;
18 use Friendica\Protocol\Email;
19 use Friendica\Protocol\Feed;
20 use Friendica\Util\Crypto;
21 use Friendica\Util\Network;
22 use Friendica\Util\XML;
23 use Friendica\Util\DateTimeFormat;
24 use dba;
25 use DOMXPath;
26 use DOMDocument;
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
113                 $ret = Network::curl($ssl_url, false, $redirects, ['timeout' => $xrd_timeout, 'accept_content' => 'application/xrd+xml']);
114                 if ($ret['success']) {
115                         $xml = $ret['body'];
116                         $xrd = XML::parseString($xml, false);
117                         $host_url = 'https://'.$host;
118                 }
119
120                 if (!is_object($xrd)) {
121                         $ret = Network::curl($url, false, $redirects, ['timeout' => $xrd_timeout, 'accept_content' => 'application/xrd+xml']);
122                         if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
123                                 logger("Probing timeout for ".$url, LOGGER_DEBUG);
124                                 return false;
125                         }
126                         $xml = $ret['body'];
127                         $xrd = XML::parseString($xml, false);
128                         $host_url = 'http://'.$host;
129                 }
130                 if (!is_object($xrd)) {
131                         logger("No xrd object found for ".$host, LOGGER_DEBUG);
132                         return [];
133                 }
134
135                 $links = XML::elementToArray($xrd);
136                 if (!isset($links["xrd"]["link"])) {
137                         logger("No xrd data found for ".$host, LOGGER_DEBUG);
138                         return [];
139                 }
140
141                 $lrdd = [];
142                 // The following webfinger path is defined in RFC 7033 https://tools.ietf.org/html/rfc7033
143                 // Problem is that Hubzilla currently doesn't provide all data in the JSON webfinger
144                 // compared to the XML webfinger. So this is commented out by now.
145                 // $lrdd = array("application/jrd+json" => $host_url.'/.well-known/webfinger?resource={uri}');
146
147                 foreach ($links["xrd"]["link"] as $value => $link) {
148                         if (!empty($link["@attributes"])) {
149                                 $attributes = $link["@attributes"];
150                         } elseif ($value == "@attributes") {
151                                 $attributes = $link;
152                         } else {
153                                 continue;
154                         }
155
156                         if (($attributes["rel"] == "lrdd") && !empty($attributes["template"])) {
157                                 $type = (empty($attributes["type"]) ? '' : $attributes["type"]);
158
159                                 $lrdd[$type] = $attributes["template"];
160                         }
161                 }
162
163                 self::$baseurl = "http://".$host;
164
165                 logger("Probing successful for ".$host, LOGGER_DEBUG);
166
167                 return $lrdd;
168         }
169
170         /**
171          * @brief Perform Webfinger lookup and return DFRN data
172          *
173          * Given an email style address, perform webfinger lookup and
174          * return the resulting DFRN profile URL, or if no DFRN profile URL
175          * is located, returns an OStatus subscription template (prefixed
176          * with the string 'stat:' to identify it as on OStatus template).
177          * If this isn't an email style address just return $webbie.
178          * Return an empty string if email-style addresses but webfinger fails,
179          * or if the resultant personal XRD doesn't contain a supported
180          * subscription/friend-request attribute.
181          *
182          * amended 7/9/2011 to return an hcard which could save potentially loading
183          * a lengthy content page to scrape dfrn attributes
184          *
185          * @param string $webbie    Address that should be probed
186          * @param string $hcard_url Link to the hcard - is returned by reference
187          *
188          * @return string profile link
189          */
190         public static function webfingerDfrn($webbie, &$hcard_url)
191         {
192                 $profile_link = '';
193
194                 $links = self::lrdd($webbie);
195                 logger('webfingerDfrn: '.$webbie.':'.print_r($links, true), LOGGER_DATA);
196                 if (count($links)) {
197                         foreach ($links as $link) {
198                                 if ($link['@attributes']['rel'] === NAMESPACE_DFRN) {
199                                         $profile_link = $link['@attributes']['href'];
200                                 }
201                                 if (($link['@attributes']['rel'] === NAMESPACE_OSTATUSSUB) && ($profile_link == "")) {
202                                         $profile_link = 'stat:'.$link['@attributes']['template'];
203                                 }
204                                 if ($link['@attributes']['rel'] === 'http://microformats.org/profile/hcard') {
205                                         $hcard_url = $link['@attributes']['href'];
206                                 }
207                         }
208                 }
209                 return $profile_link;
210         }
211
212         /**
213          * @brief Check an URI for LRDD data
214          *
215          * this is a replacement for the "lrdd" function.
216          * It isn't used in this class and has some redundancies in the code.
217          * When time comes we can check the existing calls for "lrdd" if we can rework them.
218          *
219          * @param string $uri Address that should be probed
220          *
221          * @return array uri data
222          */
223         public static function lrdd($uri)
224         {
225                 $lrdd = self::hostMeta($uri);
226                 $webfinger = null;
227
228                 if (is_bool($lrdd)) {
229                         return [];
230                 }
231
232                 if (!$lrdd) {
233                         $parts = @parse_url($uri);
234                         if (!$parts) {
235                                 return [];
236                         }
237
238                         $host = $parts["host"];
239                         if (!empty($parts["port"])) {
240                                 $host .= ':'.$parts["port"];
241                         }
242
243                         $path_parts = explode("/", trim($parts["path"], "/"));
244
245                         $nick = array_pop($path_parts);
246
247                         do {
248                                 $lrdd = self::hostMeta($host);
249                                 $host .= "/".array_shift($path_parts);
250                         } while (!$lrdd && (sizeof($path_parts) > 0));
251                 }
252
253                 if (!$lrdd) {
254                         logger("No lrdd data found for ".$uri, LOGGER_DEBUG);
255                         return [];
256                 }
257
258                 foreach ($lrdd as $type => $template) {
259                         if ($webfinger) {
260                                 continue;
261                         }
262
263                         $path = str_replace('{uri}', urlencode($uri), $template);
264                         $webfinger = self::webfinger($path, $type);
265
266                         if (!$webfinger && (strstr($uri, "@"))) {
267                                 $path = str_replace('{uri}', urlencode("acct:".$uri), $template);
268                                 $webfinger = self::webfinger($path, $type);
269                         }
270
271                         // Special treatment for Mastodon
272                         // Problem is that Mastodon uses an URL format like http://domain.tld/@nick
273                         // But the webfinger for this format fails.
274                         if (!$webfinger && !empty($nick)) {
275                                 // Mastodon uses a "@" as prefix for usernames in their url format
276                                 $nick = ltrim($nick, '@');
277
278                                 $addr = $nick."@".$host;
279
280                                 $path = str_replace('{uri}', urlencode("acct:".$addr), $template);
281                                 $webfinger = self::webfinger($path, $type);
282                         }
283                 }
284
285                 if (!is_array($webfinger["links"])) {
286                         logger("No webfinger links found for ".$uri, LOGGER_DEBUG);
287                         return false;
288                 }
289
290                 $data = [];
291
292                 foreach ($webfinger["links"] as $link) {
293                         $data[] = ["@attributes" => $link];
294                 }
295
296                 if (is_array($webfinger["aliases"])) {
297                         foreach ($webfinger["aliases"] as $alias) {
298                                 $data[] = ["@attributes" =>
299                                                         ["rel" => "alias",
300                                                                 "href" => $alias]];
301                         }
302                 }
303
304                 return $data;
305         }
306
307         /**
308          * @brief Fetch information (protocol endpoints and user information) about a given uri
309          *
310          * @param string  $uri     Address that should be probed
311          * @param string  $network Test for this specific network
312          * @param integer $uid     User ID for the probe (only used for mails)
313          * @param boolean $cache   Use cached values?
314          * @param boolean $insert  Insert the contact into the contact table.
315          *
316          * @return array uri data
317          */
318         public static function uri($uri, $network = "", $uid = -1, $cache = true, $insert = false)
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($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"] = NETWORK_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'], [NETWORK_PHANTOM, NETWORK_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'] != NETWORK_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'] = 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'] = DBM::date();
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_IS_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 except $insert is set to true.
468                                 // This is intended, since we only need public contacts
469                                 // for everyone we store items from. We don't need to store
470                                 // every contact on the planet.
471                                 $old_fields = dba::selectFirst('contact', $fieldnames, $condition);
472
473                                 // When the contact doesn't exist, the value "true" will trigger an insert
474                                 if (!$old_fields && $insert) {
475                                         $old_fields = true;
476                                         $fields['blocked'] = false;
477                                         $fields['pending'] = false;
478                                 }
479
480                                 $fields['name-date'] = DateTimeFormat::utcNow();
481                                 $fields['uri-date'] = DateTimeFormat::utcNow();
482                                 $fields['success_update'] = DateTimeFormat::utcNow();
483
484                                 dba::update('contact', $fields, $condition, $old_fields);
485                         }
486                 }
487
488                 return $data;
489         }
490
491         /**
492          * @brief Switch the scheme of an url between http and https
493          *
494          * @param string $url URL
495          *
496          * @return string switched URL
497          */
498         private static function switchScheme($url)
499         {
500                 $parts = parse_url($url);
501
502                 if (!isset($parts['scheme'])) {
503                         return $url;
504                 }
505
506                 if ($parts['scheme'] == 'http') {
507                         $url = str_replace('http://', 'https://', $url);
508                 } elseif ($parts['scheme'] == 'https') {
509                         $url = str_replace('https://', 'http://', $url);
510                 }
511
512                 return $url;
513         }
514
515         /**
516          * @brief Checks if a profile url should be OStatus but only provides partial information
517          *
518          * @param array  $webfinger Webfinger data
519          * @param string $lrdd      Path template for webfinger request
520          * @param string $type      type
521          *
522          * @return array fixed webfinger data
523          */
524         private static function fixOStatus($webfinger, $lrdd, $type)
525         {
526                 if (empty($webfinger['links']) || empty($webfinger['subject'])) {
527                         return $webfinger;
528                 }
529
530                 $is_ostatus = false;
531                 $has_key = false;
532
533                 foreach ($webfinger['links'] as $link) {
534                         if ($link['rel'] == NAMESPACE_OSTATUSSUB) {
535                                 $is_ostatus = true;
536                         }
537                         if ($link['rel'] == 'magic-public-key') {
538                                 $has_key = true;
539                         }
540                 }
541
542                 if (!$is_ostatus || $has_key) {
543                         return $webfinger;
544                 }
545
546                 $url = self::switchScheme($webfinger['subject']);
547                 $path = str_replace('{uri}', urlencode($url), $lrdd);
548                 $webfinger2 = self::webfinger($path, $type);
549
550                 // Is the new webfinger detectable as OStatus?
551                 if (self::ostatus($webfinger2, true)) {
552                         $webfinger = $webfinger2;
553                 }
554
555                 return $webfinger;
556         }
557
558         /**
559          * @brief Fetch information (protocol endpoints and user information) about a given uri
560          *
561          * This function is only called by the "uri" function that adds caching and rearranging of data.
562          *
563          * @param string  $uri     Address that should be probed
564          * @param string  $network Test for this specific network
565          * @param integer $uid     User ID for the probe (only used for mails)
566          *
567          * @return array uri data
568          */
569         private static function detect($uri, $network, $uid)
570         {
571                 $parts = parse_url($uri);
572
573                 if (!empty($parts["scheme"]) && !empty($parts["host"]) && !empty($parts["path"])) {
574                         $host = $parts["host"];
575                         if (!empty($parts["port"])) {
576                                 $host .= ':'.$parts["port"];
577                         }
578
579                         if ($host == 'twitter.com') {
580                                 return ["network" => NETWORK_TWITTER];
581                         }
582                         $lrdd = self::hostMeta($host);
583
584                         if (is_bool($lrdd)) {
585                                 return [];
586                         }
587
588                         $path_parts = explode("/", trim($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('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 == NETWORK_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" => NETWORK_TWITTER];
622                         }
623                         $lrdd = self::hostMeta($host);
624
625                         if (is_bool($lrdd)) {
626                                 return [];
627                         }
628
629                         if (!$lrdd) {
630                                 logger('No XRD data was found for '.$uri, LOGGER_DEBUG);
631                                 return self::mail($uri, $uid);
632                         }
633                         $addr = $uri;
634                 } else {
635                         logger("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("Probing ".$uri, LOGGER_DEBUG);
681
682                 if (in_array($network, ["", NETWORK_DFRN])) {
683                         $result = self::dfrn($webfinger);
684                 }
685                 if ((!$result && ($network == "")) || ($network == NETWORK_DIASPORA)) {
686                         $result = self::diaspora($webfinger);
687                 }
688                 if ((!$result && ($network == "")) || ($network == NETWORK_OSTATUS)) {
689                         $result = self::ostatus($webfinger);
690                 }
691                 if ((!$result && ($network == "")) || ($network == NETWORK_PUMPIO)) {
692                         $result = self::pumpio($webfinger, $addr);
693                 }
694                 if ((!$result && ($network == "")) || ($network == NETWORK_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                 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 ($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 ($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["poco"])
930                         || !isset($data["name"])
931                         || !isset($data["photo"])
932                 ) {
933                         $data = self::pollHcard($profile_link, $data, true);
934                 }
935
936                 $prof_data = [];
937                 $prof_data["addr"]         = $data["addr"];
938                 $prof_data["nick"]         = $data["nick"];
939                 $prof_data["dfrn-request"] = $data["request"];
940                 $prof_data["dfrn-confirm"] = $data["confirm"];
941                 $prof_data["dfrn-notify"]  = $data["notify"];
942                 $prof_data["dfrn-poll"]    = $data["poll"];
943                 $prof_data["dfrn-poco"]    = $data["poco"];
944                 $prof_data["photo"]        = $data["photo"];
945                 $prof_data["fn"]           = $data["name"];
946                 $prof_data["key"]          = $data["pubkey"];
947
948                 logger("Result for profile ".$profile_link.": ".print_r($prof_data, true), LOGGER_DEBUG);
949
950                 return $prof_data;
951         }
952
953         /**
954          * @brief Check for DFRN contact
955          *
956          * @param array $webfinger Webfinger data
957          *
958          * @return array DFRN data
959          */
960         private static function dfrn($webfinger)
961         {
962                 $hcard_url = "";
963                 $data = [];
964                 foreach ($webfinger["links"] as $link) {
965                         if (($link["rel"] == NAMESPACE_DFRN) && ($link["href"] != "")) {
966                                 $data["network"] = NETWORK_DFRN;
967                         } elseif (($link["rel"] == NAMESPACE_FEED) && ($link["href"] != "")) {
968                                 $data["poll"] = $link["href"];
969                         } elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") && ($link["type"] == "text/html") && ($link["href"] != "")) {
970                                 $data["url"] = $link["href"];
971                         } elseif (($link["rel"] == "http://microformats.org/profile/hcard") && ($link["href"] != "")) {
972                                 $hcard_url = $link["href"];
973                         } elseif (($link["rel"] == NAMESPACE_POCO) && ($link["href"] != "")) {
974                                 $data["poco"] = $link["href"];
975                         } elseif (($link["rel"] == "http://webfinger.net/rel/avatar") && ($link["href"] != "")) {
976                                 $data["photo"] = $link["href"];
977                         } elseif (($link["rel"] == "http://joindiaspora.com/seed_location") && ($link["href"] != "")) {
978                                 $data["baseurl"] = trim($link["href"], '/');
979                         } elseif (($link["rel"] == "http://joindiaspora.com/guid") && ($link["href"] != "")) {
980                                 $data["guid"] = $link["href"];
981                         } elseif (($link["rel"] == "diaspora-public-key") && ($link["href"] != "")) {
982                                 $data["pubkey"] = base64_decode($link["href"]);
983
984                                 //if (strstr($data["pubkey"], 'RSA ') || ($link["type"] == "RSA"))
985                                 if (strstr($data["pubkey"], 'RSA ')) {
986                                         $data["pubkey"] = Crypto::rsaToPem($data["pubkey"]);
987                                 }
988                         }
989                 }
990
991                 if (is_array($webfinger["aliases"])) {
992                         foreach ($webfinger["aliases"] as $alias) {
993                                 if (normalise_link($alias) != normalise_link($data["url"]) && ! strstr($alias, "@")) {
994                                         $data["alias"] = $alias;
995                                 } elseif (substr($alias, 0, 5) == 'acct:') {
996                                         $data["addr"] = substr($alias, 5);
997                                 }
998                         }
999                 }
1000
1001                 if (substr($webfinger["subject"], 0, 5) == "acct:") {
1002                         $data["addr"] = substr($webfinger["subject"], 5);
1003                 }
1004
1005                 if (!isset($data["network"]) || ($hcard_url == "")) {
1006                         return false;
1007                 }
1008
1009                 // Fetch data via noscrape - this is faster
1010                 $noscrape_url = str_replace("/hcard/", "/noscrape/", $hcard_url);
1011                 $data = self::pollNoscrape($noscrape_url, $data);
1012
1013                 if (isset($data["notify"])
1014                         && isset($data["confirm"])
1015                         && isset($data["request"])
1016                         && isset($data["poll"])
1017                         && isset($data["name"])
1018                         && isset($data["photo"])
1019                 ) {
1020                         return $data;
1021                 }
1022
1023                 $data = self::pollHcard($hcard_url, $data, true);
1024
1025                 return $data;
1026         }
1027
1028         /**
1029          * @brief Poll the hcard page (Diaspora and Friendica specific)
1030          *
1031          * @param string  $hcard_url Link to the hcard page
1032          * @param array   $data      The already fetched data
1033          * @param boolean $dfrn      Poll DFRN specific data
1034          *
1035          * @return array hcard data
1036          */
1037         private static function pollHcard($hcard_url, $data, $dfrn = false)
1038         {
1039                 $ret = Network::curl($hcard_url);
1040                 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
1041                         return false;
1042                 }
1043                 $content = $ret['body'];
1044                 if (!$content) {
1045                         return false;
1046                 }
1047
1048                 $doc = new DOMDocument();
1049                 if (!@$doc->loadHTML($content)) {
1050                         return false;
1051                 }
1052
1053                 $xpath = new DomXPath($doc);
1054
1055                 $vcards = $xpath->query("//div[contains(concat(' ', @class, ' '), ' vcard ')]");
1056                 if (!is_object($vcards)) {
1057                         return false;
1058                 }
1059
1060                 if ($vcards->length > 0) {
1061                         $vcard = $vcards->item(0);
1062
1063                         // We have to discard the guid from the hcard in favour of the guid from lrdd
1064                         // Reason: Hubzilla doesn't use the value "uid" in the hcard like Diaspora does.
1065                         $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' uid ')]", $vcard); // */
1066                         if (($search->length > 0) && ($data["guid"] == "")) {
1067                                 $data["guid"] = $search->item(0)->nodeValue;
1068                         }
1069
1070                         $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' nickname ')]", $vcard); // */
1071                         if ($search->length > 0) {
1072                                 $data["nick"] = $search->item(0)->nodeValue;
1073                         }
1074
1075                         $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' fn ')]", $vcard); // */
1076                         if ($search->length > 0) {
1077                                 $data["name"] = $search->item(0)->nodeValue;
1078                         }
1079
1080                         $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' searchable ')]", $vcard); // */
1081                         if ($search->length > 0) {
1082                                 $data["searchable"] = $search->item(0)->nodeValue;
1083                         }
1084
1085                         $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' key ')]", $vcard); // */
1086                         if ($search->length > 0) {
1087                                 $data["pubkey"] = $search->item(0)->nodeValue;
1088                                 if (strstr($data["pubkey"], 'RSA ')) {
1089                                         $data["pubkey"] = Crypto::rsaToPem($data["pubkey"]);
1090                                 }
1091                         }
1092
1093                         $search = $xpath->query("//*[@id='pod_location']", $vcard); // */
1094                         if ($search->length > 0) {
1095                                 $data["baseurl"] = trim($search->item(0)->nodeValue, "/");
1096                         }
1097                 }
1098
1099                 $avatar = [];
1100                 $photos = $xpath->query("//*[contains(concat(' ', @class, ' '), ' photo ') or contains(concat(' ', @class, ' '), ' avatar ')]", $vcard); // */
1101                 foreach ($photos as $photo) {
1102                         $attr = [];
1103                         foreach ($photo->attributes as $attribute) {
1104                                 $attr[$attribute->name] = trim($attribute->value);
1105                         }
1106
1107                         if (isset($attr["src"]) && isset($attr["width"])) {
1108                                 $avatar[$attr["width"]] = $attr["src"];
1109                         }
1110
1111                         // We don't have a width. So we just take everything that we got.
1112                         // This is a Hubzilla workaround which doesn't send a width.
1113                         if ((sizeof($avatar) == 0) && !empty($attr["src"])) {
1114                                 $avatar[] = $attr["src"];
1115                         }
1116                 }
1117
1118                 if (sizeof($avatar)) {
1119                         ksort($avatar);
1120                         $data["photo"] = self::fixAvatar(array_pop($avatar), $data["baseurl"]);
1121                 }
1122
1123                 if ($dfrn) {
1124                         // Poll DFRN specific data
1125                         $search = $xpath->query("//link[contains(concat(' ', @rel), ' dfrn-')]");
1126                         if ($search->length > 0) {
1127                                 foreach ($search as $link) {
1128                                         //$data["request"] = $search->item(0)->nodeValue;
1129                                         $attr = [];
1130                                         foreach ($link->attributes as $attribute) {
1131                                                 $attr[$attribute->name] = trim($attribute->value);
1132                                         }
1133
1134                                         $data[substr($attr["rel"], 5)] = $attr["href"];
1135                                 }
1136                         }
1137
1138                         // Older Friendica versions had used the "uid" field differently than newer versions
1139                         if ($data["nick"] == $data["guid"]) {
1140                                 unset($data["guid"]);
1141                         }
1142                 }
1143
1144
1145                 return $data;
1146         }
1147
1148         /**
1149          * @brief Check for Diaspora contact
1150          *
1151          * @param array $webfinger Webfinger data
1152          *
1153          * @return array Diaspora data
1154          */
1155         private static function diaspora($webfinger)
1156         {
1157                 $hcard_url = "";
1158                 $data = [];
1159                 foreach ($webfinger["links"] as $link) {
1160                         if (($link["rel"] == "http://microformats.org/profile/hcard") && ($link["href"] != "")) {
1161                                 $hcard_url = $link["href"];
1162                         } elseif (($link["rel"] == "http://joindiaspora.com/seed_location") && ($link["href"] != "")) {
1163                                 $data["baseurl"] = trim($link["href"], '/');
1164                         } elseif (($link["rel"] == "http://joindiaspora.com/guid") && ($link["href"] != "")) {
1165                                 $data["guid"] = $link["href"];
1166                         } elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") && ($link["type"] == "text/html") && ($link["href"] != "")) {
1167                                 $data["url"] = $link["href"];
1168                         } elseif (($link["rel"] == NAMESPACE_FEED) && ($link["href"] != "")) {
1169                                 $data["poll"] = $link["href"];
1170                         } elseif (($link["rel"] == NAMESPACE_POCO) && ($link["href"] != "")) {
1171                                 $data["poco"] = $link["href"];
1172                         } elseif (($link["rel"] == "salmon") && ($link["href"] != "")) {
1173                                 $data["notify"] = $link["href"];
1174                         } elseif (($link["rel"] == "diaspora-public-key") && ($link["href"] != "")) {
1175                                 $data["pubkey"] = base64_decode($link["href"]);
1176
1177                                 //if (strstr($data["pubkey"], 'RSA ') || ($link["type"] == "RSA"))
1178                                 if (strstr($data["pubkey"], 'RSA ')) {
1179                                         $data["pubkey"] = Crypto::rsaToPem($data["pubkey"]);
1180                                 }
1181                         }
1182                 }
1183
1184                 if (!isset($data["url"]) || ($hcard_url == "")) {
1185                         return false;
1186                 }
1187
1188                 if (is_array($webfinger["aliases"])) {
1189                         foreach ($webfinger["aliases"] as $alias) {
1190                                 if (normalise_link($alias) != normalise_link($data["url"]) && ! strstr($alias, "@")) {
1191                                         $data["alias"] = $alias;
1192                                 } elseif (substr($alias, 0, 5) == 'acct:') {
1193                                         $data["addr"] = substr($alias, 5);
1194                                 }
1195                         }
1196                 }
1197
1198                 if (!empty($webfinger["subject"]) && (substr($webfinger["subject"], 0, 5) == 'acct:')) {
1199                         $data["addr"] = substr($webfinger["subject"], 5);
1200                 }
1201
1202                 // Fetch further information from the hcard
1203                 $data = self::pollHcard($hcard_url, $data);
1204
1205                 if (!$data) {
1206                         return false;
1207                 }
1208
1209                 if (isset($data["url"])
1210                         && isset($data["guid"])
1211                         && isset($data["baseurl"])
1212                         && isset($data["pubkey"])
1213                         && ($hcard_url != "")
1214                 ) {
1215                         $data["network"] = NETWORK_DIASPORA;
1216
1217                         // The Diaspora handle must always be lowercase
1218                         $data["addr"] = strtolower($data["addr"]);
1219
1220                         // We have to overwrite the detected value for "notify" since Hubzilla doesn't send it
1221                         $data["notify"] = $data["baseurl"] . "/receive/users/" . $data["guid"];
1222                         $data["batch"]  = $data["baseurl"] . "/receive/public";
1223                 } else {
1224                         return false;
1225                 }
1226
1227                 return $data;
1228         }
1229
1230         /**
1231          * @brief Check for OStatus contact
1232          *
1233          * @param array $webfinger Webfinger data
1234          * @param bool  $short     Short detection mode
1235          *
1236          * @return array|bool OStatus data or "false" on error or "true" on short mode
1237          */
1238         private static function ostatus($webfinger, $short = false)
1239         {
1240                 $data = [];
1241
1242                 if (is_array($webfinger["aliases"])) {
1243                         foreach ($webfinger["aliases"] as $alias) {
1244                                 if (strstr($alias, "@") && !strstr(normalise_link($alias), "http://")) {
1245                                         $data["addr"] = str_replace('acct:', '', $alias);
1246                                 }
1247                         }
1248                 }
1249
1250                 if (is_string($webfinger["subject"]) && strstr($webfinger["subject"], "@")
1251                         && !strstr(normalise_link($webfinger["subject"]), "http://")
1252                 ) {
1253                         $data["addr"] = str_replace('acct:', '', $webfinger["subject"]);
1254                 }
1255
1256                 $pubkey = "";
1257                 if (is_array($webfinger["links"])) {
1258                         foreach ($webfinger["links"] as $link) {
1259                                 if (($link["rel"] == "http://webfinger.net/rel/profile-page")
1260                                         && ($link["type"] == "text/html")
1261                                         && ($link["href"] != "")
1262                                 ) {
1263                                         $data["url"] = $link["href"];
1264                                 } elseif (($link["rel"] == "salmon") && ($link["href"] != "")) {
1265                                         $data["notify"] = $link["href"];
1266                                 } elseif (($link["rel"] == NAMESPACE_FEED) && ($link["href"] != "")) {
1267                                         $data["poll"] = $link["href"];
1268                                 } elseif (($link["rel"] == "magic-public-key") && ($link["href"] != "")) {
1269                                         $pubkey = $link["href"];
1270
1271                                         if (substr($pubkey, 0, 5) === 'data:') {
1272                                                 if (strstr($pubkey, ',')) {
1273                                                         $pubkey = substr($pubkey, strpos($pubkey, ',') + 1);
1274                                                 } else {
1275                                                         $pubkey = substr($pubkey, 5);
1276                                                 }
1277                                         } elseif (normalise_link($pubkey) == 'http://') {
1278                                                 $ret = Network::curl($pubkey);
1279                                                 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
1280                                                         return false;
1281                                                 }
1282                                                 $pubkey = $ret['body'];
1283                                         }
1284
1285                                         $key = explode(".", $pubkey);
1286
1287                                         if (sizeof($key) >= 3) {
1288                                                 $m = base64url_decode($key[1]);
1289                                                 $e = base64url_decode($key[2]);
1290                                                 $data["pubkey"] = Crypto::meToPem($m, $e);
1291                                         }
1292                                 }
1293                         }
1294                 }
1295
1296                 if (isset($data["notify"]) && isset($data["pubkey"])
1297                         && isset($data["poll"])
1298                         && isset($data["url"])
1299                 ) {
1300                         $data["network"] = NETWORK_OSTATUS;
1301                 } else {
1302                         return false;
1303                 }
1304
1305                 if ($short) {
1306                         return true;
1307                 }
1308
1309                 // Fetch all additional data from the feed
1310                 $ret = Network::curl($data["poll"]);
1311                 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
1312                         return false;
1313                 }
1314                 $feed = $ret['body'];
1315                 $feed_data = Feed::import($feed, $dummy1, $dummy2, $dummy3, true);
1316                 if (!$feed_data) {
1317                         return false;
1318                 }
1319
1320                 if ($feed_data["header"]["author-name"] != "") {
1321                         $data["name"] = $feed_data["header"]["author-name"];
1322                 }
1323                 if ($feed_data["header"]["author-nick"] != "") {
1324                         $data["nick"] = $feed_data["header"]["author-nick"];
1325                 }
1326                 if ($feed_data["header"]["author-avatar"] != "") {
1327                         $data["photo"] = self::fixAvatar($feed_data["header"]["author-avatar"], $data["url"]);
1328                 }
1329                 if ($feed_data["header"]["author-id"] != "") {
1330                         $data["alias"] = $feed_data["header"]["author-id"];
1331                 }
1332                 if ($feed_data["header"]["author-location"] != "") {
1333                         $data["location"] = $feed_data["header"]["author-location"];
1334                 }
1335                 if ($feed_data["header"]["author-about"] != "") {
1336                         $data["about"] = $feed_data["header"]["author-about"];
1337                 }
1338                 // OStatus has serious issues when the the url doesn't fit (ssl vs. non ssl)
1339                 // So we take the value that we just fetched, although the other one worked as well
1340                 if ($feed_data["header"]["author-link"] != "") {
1341                         $data["url"] = $feed_data["header"]["author-link"];
1342                 }
1343
1344                 if (($data['poll'] == $data['url']) && ($data["alias"] != '')) {
1345                         $data['url'] = $data["alias"];
1346                         $data["alias"] = '';
1347                 }
1348
1349                 /// @todo Fetch location and "about" from the feed as well
1350                 return $data;
1351         }
1352
1353         /**
1354          * @brief Fetch data from a pump.io profile page
1355          *
1356          * @param string $profile_link Link to the profile page
1357          *
1358          * @return array profile data
1359          */
1360         private static function pumpioProfileData($profile_link)
1361         {
1362                 $doc = new DOMDocument();
1363                 if (!@$doc->loadHTMLFile($profile_link)) {
1364                         return false;
1365                 }
1366
1367                 $xpath = new DomXPath($doc);
1368
1369                 $data = [];
1370
1371                 $data["name"] = $xpath->query("//span[contains(@class, 'p-name')]")->item(0)->nodeValue;
1372
1373                 if ($data["name"] == '') {
1374                         // This is ugly - but pump.io doesn't seem to know a better way for it
1375                         $data["name"] = trim($xpath->query("//h1[@class='media-header']")->item(0)->nodeValue);
1376                         $pos = strpos($data["name"], chr(10));
1377                         if ($pos) {
1378                                 $data["name"] = trim(substr($data["name"], 0, $pos));
1379                         }
1380                 }
1381
1382                 $data["location"] = $xpath->query("//p[contains(@class, 'p-locality')]")->item(0)->nodeValue;
1383
1384                 if ($data["location"] == '') {
1385                         $data["location"] = $xpath->query("//p[contains(@class, 'location')]")->item(0)->nodeValue;
1386                 }
1387
1388                 $data["about"] = $xpath->query("//p[contains(@class, 'p-note')]")->item(0)->nodeValue;
1389
1390                 if ($data["about"] == '') {
1391                         $data["about"] = $xpath->query("//p[contains(@class, 'summary')]")->item(0)->nodeValue;
1392                 }
1393
1394                 $avatar = $xpath->query("//img[contains(@class, 'u-photo')]")->item(0);
1395                 if (!$avatar) {
1396                         $avatar = $xpath->query("//img[@class='img-rounded media-object']")->item(0);
1397                 }
1398                 if ($avatar) {
1399                         foreach ($avatar->attributes as $attribute) {
1400                                 if ($attribute->name == "src") {
1401                                         $data["photo"] = trim($attribute->value);
1402                                 }
1403                         }
1404                 }
1405
1406                 return $data;
1407         }
1408
1409         /**
1410          * @brief Check for pump.io contact
1411          *
1412          * @param array $webfinger Webfinger data
1413          *
1414          * @return array pump.io data
1415          */
1416         private static function pumpio($webfinger, $addr)
1417         {
1418                 $data = [];
1419                 foreach ($webfinger["links"] as $link) {
1420                         if (($link["rel"] == "http://webfinger.net/rel/profile-page")
1421                                 && ($link["type"] == "text/html")
1422                                 && ($link["href"] != "")
1423                         ) {
1424                                 $data["url"] = $link["href"];
1425                         } elseif (($link["rel"] == "activity-inbox") && ($link["href"] != "")) {
1426                                 $data["notify"] = $link["href"];
1427                         } elseif (($link["rel"] == "activity-outbox") && ($link["href"] != "")) {
1428                                 $data["poll"] = $link["href"];
1429                         } elseif (($link["rel"] == "dialback") && ($link["href"] != "")) {
1430                                 $data["dialback"] = $link["href"];
1431                         }
1432                 }
1433                 if (isset($data["poll"]) && isset($data["notify"])
1434                         && isset($data["dialback"])
1435                         && isset($data["url"])
1436                 ) {
1437                         // by now we use these fields only for the network type detection
1438                         // So we unset all data that isn't used at the moment
1439                         unset($data["dialback"]);
1440
1441                         $data["network"] = NETWORK_PUMPIO;
1442                 } else {
1443                         return false;
1444                 }
1445
1446                 $profile_data = self::pumpioProfileData($data["url"]);
1447
1448                 if (!$profile_data) {
1449                         return false;
1450                 }
1451
1452                 $data = array_merge($data, $profile_data);
1453
1454                 if (($addr != '') && ($data['name'] != '')) {
1455                         $name = trim(str_replace($addr, '', $data['name']));
1456                         if ($name != '') {
1457                                 $data['name'] = $name;
1458                         }
1459                 }
1460
1461                 return $data;
1462         }
1463
1464         /**
1465          * @brief Check page for feed link
1466          *
1467          * @param string $url Page link
1468          *
1469          * @return string feed link
1470          */
1471         private static function getFeedLink($url)
1472         {
1473                 $doc = new DOMDocument();
1474
1475                 if (!@$doc->loadHTMLFile($url)) {
1476                         return false;
1477                 }
1478
1479                 $xpath = new DomXPath($doc);
1480
1481                 //$feeds = $xpath->query("/html/head/link[@type='application/rss+xml']");
1482                 $feeds = $xpath->query("/html/head/link[@type='application/rss+xml' and @rel='alternate']");
1483                 if (!is_object($feeds)) {
1484                         return false;
1485                 }
1486
1487                 if ($feeds->length == 0) {
1488                         return false;
1489                 }
1490
1491                 $feed_url = "";
1492
1493                 foreach ($feeds as $feed) {
1494                         $attr = [];
1495                         foreach ($feed->attributes as $attribute) {
1496                                 $attr[$attribute->name] = trim($attribute->value);
1497                         }
1498
1499                         if ($feed_url == "") {
1500                                 $feed_url = $attr["href"];
1501                         }
1502                 }
1503
1504                 return $feed_url;
1505         }
1506
1507         /**
1508          * @brief Check for feed contact
1509          *
1510          * @param string  $url   Profile link
1511          * @param boolean $probe Do a probe if the page contains a feed link
1512          *
1513          * @return array feed data
1514          */
1515         private static function feed($url, $probe = true)
1516         {
1517                 $ret = Network::curl($url);
1518                 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
1519                         return false;
1520                 }
1521                 $feed = $ret['body'];
1522                 $feed_data = Feed::import($feed, $dummy1, $dummy2, $dummy3, true);
1523
1524                 if (!$feed_data) {
1525                         if (!$probe) {
1526                                 return false;
1527                         }
1528
1529                         $feed_url = self::getFeedLink($url);
1530
1531                         if (!$feed_url) {
1532                                 return false;
1533                         }
1534
1535                         return self::feed($feed_url, false);
1536                 }
1537
1538                 if ($feed_data["header"]["author-name"] != "") {
1539                         $data["name"] = $feed_data["header"]["author-name"];
1540                 }
1541
1542                 if ($feed_data["header"]["author-nick"] != "") {
1543                         $data["nick"] = $feed_data["header"]["author-nick"];
1544                 }
1545
1546                 if ($feed_data["header"]["author-avatar"] != "") {
1547                         $data["photo"] = $feed_data["header"]["author-avatar"];
1548                 }
1549
1550                 if ($feed_data["header"]["author-id"] != "") {
1551                         $data["alias"] = $feed_data["header"]["author-id"];
1552                 }
1553
1554                 $data["url"] = $url;
1555                 $data["poll"] = $url;
1556
1557                 if ($feed_data["header"]["author-link"] != "") {
1558                         $data["baseurl"] = $feed_data["header"]["author-link"];
1559                 } else {
1560                         $data["baseurl"] = $data["url"];
1561                 }
1562
1563                 $data["network"] = NETWORK_FEED;
1564
1565                 return $data;
1566         }
1567
1568         /**
1569          * @brief Check for mail contact
1570          *
1571          * @param string  $uri Profile link
1572          * @param integer $uid User ID
1573          *
1574          * @return array mail data
1575          */
1576         private static function mail($uri, $uid)
1577         {
1578                 if (!Network::isEmailDomainValid($uri)) {
1579                         return false;
1580                 }
1581
1582                 if ($uid == 0) {
1583                         return false;
1584                 }
1585
1586                 $x = q("SELECT `prvkey` FROM `user` WHERE `uid` = %d LIMIT 1", intval($uid));
1587
1588                 $r = q("SELECT * FROM `mailacct` WHERE `uid` = %d AND `server` != '' LIMIT 1", intval($uid));
1589
1590                 if (DBM::is_result($x) && DBM::is_result($r)) {
1591                         $mailbox = Email::constructMailboxName($r[0]);
1592                         $password = '';
1593                         openssl_private_decrypt(hex2bin($r[0]['pass']), $password, $x[0]['prvkey']);
1594                         $mbox = Email::connect($mailbox, $r[0]['user'], $password);
1595                         if (!$mbox) {
1596                                 return false;
1597                         }
1598                 }
1599
1600                 $msgs = Email::poll($mbox, $uri);
1601                 logger('searching '.$uri.', '.count($msgs).' messages found.', LOGGER_DEBUG);
1602
1603                 if (!count($msgs)) {
1604                         return false;
1605                 }
1606
1607                 $phost = substr($uri, strpos($uri, '@') + 1);
1608
1609                 $data = [];
1610                 $data["addr"]    = $uri;
1611                 $data["network"] = NETWORK_MAIL;
1612                 $data["name"]    = substr($uri, 0, strpos($uri, '@'));
1613                 $data["nick"]    = $data["name"];
1614                 $data["photo"]   = Network::lookupAvatarByEmail($uri);
1615                 $data["url"]     = 'mailto:'.$uri;
1616                 $data["notify"]  = 'smtp '.random_string();
1617                 $data["poll"]    = 'email '.random_string();
1618
1619                 $x = Email::messageMeta($mbox, $msgs[0]);
1620                 if (stristr($x[0]->from, $uri)) {
1621                         $adr = imap_rfc822_parse_adrlist($x[0]->from, '');
1622                 } elseif (stristr($x[0]->to, $uri)) {
1623                         $adr = imap_rfc822_parse_adrlist($x[0]->to, '');
1624                 }
1625                 if (isset($adr)) {
1626                         foreach ($adr as $feadr) {
1627                                 if ((strcasecmp($feadr->mailbox, $data["name"]) == 0)
1628                                         &&(strcasecmp($feadr->host, $phost) == 0)
1629                                         && (strlen($feadr->personal))
1630                                 ) {
1631                                         $personal = imap_mime_header_decode($feadr->personal);
1632                                         $data["name"] = "";
1633                                         foreach ($personal as $perspart) {
1634                                                 if ($perspart->charset != "default") {
1635                                                         $data["name"] .= iconv($perspart->charset, 'UTF-8//IGNORE', $perspart->text);
1636                                                 } else {
1637                                                         $data["name"] .= $perspart->text;
1638                                                 }
1639                                         }
1640
1641                                         $data["name"] = notags($data["name"]);
1642                                 }
1643                         }
1644                 }
1645                 if (!empty($mbox)) {
1646                         imap_close($mbox);
1647                 }
1648
1649                 return $data;
1650         }
1651
1652         /**
1653          * @brief Mix two paths together to possibly fix missing parts
1654          *
1655          * @param string $avatar Path to the avatar
1656          * @param string $base   Another path that is hopefully complete
1657          *
1658          * @return string fixed avatar path
1659          */
1660         public static function fixAvatar($avatar, $base)
1661         {
1662                 $base_parts = parse_url($base);
1663
1664                 // Remove all parts that could create a problem
1665                 unset($base_parts['path']);
1666                 unset($base_parts['query']);
1667                 unset($base_parts['fragment']);
1668
1669                 $avatar_parts = parse_url($avatar);
1670
1671                 // Now we mix them
1672                 $parts = array_merge($base_parts, $avatar_parts);
1673
1674                 // And put them together again
1675                 $scheme   = isset($parts['scheme'])   ? $parts['scheme'] . '://' : '';
1676                 $host     = isset($parts['host'])     ? $parts['host']           : '';
1677                 $port     = isset($parts['port'])     ? ':' . $parts['port']     : '';
1678                 $path     = isset($parts['path'])     ? $parts['path']           : '';
1679                 $query    = isset($parts['query'])    ? '?' . $parts['query']    : '';
1680                 $fragment = isset($parts['fragment']) ? '#' . $parts['fragment'] : '';
1681
1682                 $fixed = $scheme.$host.$port.$path.$query.$fragment;
1683
1684                 logger('Base: '.$base.' - Avatar: '.$avatar.' - Fixed: '.$fixed, LOGGER_DATA);
1685
1686                 return $fixed;
1687         }
1688 }