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