]> git.mxchange.org Git - friendica.git/blob - include/Probe.php
df2246f2064b91a88371e436f4cb3e9e03833248
[friendica.git] / include / Probe.php
1 <?php
2 /**
3  * @file include/Probe.php
4  * @brief Functions for probing URL
5  *
6  */
7
8 use \Friendica\Core\Config;
9 use \Friendica\Core\PConfig;
10
11 require_once("include/feed.php");
12 require_once('include/email.php');
13 require_once('include/network.php');
14
15 /**
16  * @brief This class contain functions for probing URL
17  *
18  */
19 class Probe {
20
21         /**
22          * @brief Rearrange the array so that it always has the same order
23          *
24          * @param array $data Unordered data
25          *
26          * @return array Ordered data
27          */
28         private function rearrange_data($data) {
29                 $fields = array("name", "nick", "guid", "url", "addr", "alias",
30                                 "photo", "community", "keywords", "location", "about",
31                                 "batch", "notify", "poll", "request", "confirm", "poco",
32                                 "priority", "network", "pubkey", "baseurl");
33
34                 $newdata = array();
35                 foreach ($fields AS $field)
36                         if (isset($data[$field]))
37                                 $newdata[$field] = $data[$field];
38                         else
39                                 $newdata[$field] = "";
40
41                 // We don't use the "priority" field anymore and replace it with a dummy.
42                 $newdata["priority"] = 0;
43
44                 return $newdata;
45         }
46
47         /**
48          * @brief Probes for XRD data
49          *
50          * @return array
51          *      'lrdd' => Link to LRDD endpoint
52          *      'lrdd-xml' => Link to LRDD endpoint in XML format
53          *      'lrdd-json' => Link to LRDD endpoint in JSON format
54          */
55         private function xrd($host) {
56
57                 $ssl_url = "https://".$host."/.well-known/host-meta";
58                 $url = "http://".$host."/.well-known/host-meta";
59
60                 $xrd_timeout = Config::get('system','xrd_timeout', 20);
61                 $redirects = 0;
62
63                 $xml = fetch_url($ssl_url, false, $redirects, $xrd_timeout, "application/xrd+xml");
64                 $xrd = parse_xml_string($xml, false);
65
66                 if (!is_object($xrd)) {
67                         $xml = fetch_url($url, false, $redirects, $xrd_timeout, "application/xrd+xml");
68                         $xrd = parse_xml_string($xml, false);
69                 }
70                 if (!is_object($xrd))
71                         return false;
72
73                 $links = xml::element_to_array($xrd);
74                 if (!isset($links["xrd"]["link"]))
75                         return false;
76
77                 $xrd_data = array();
78
79                 foreach ($links["xrd"]["link"] AS $value => $link) {
80                         if (isset($link["@attributes"]))
81                                 $attributes = $link["@attributes"];
82                         elseif ($value == "@attributes")
83                                 $attributes = $link;
84                         else
85                                 continue;
86
87                         if (($attributes["rel"] == "lrdd") AND
88                                 ($attributes["type"] == "application/xrd+xml"))
89                                 $xrd_data["lrdd-xml"] = $attributes["template"];
90                         elseif (($attributes["rel"] == "lrdd") AND
91                                 ($attributes["type"] == "application/json"))
92                                 $xrd_data["lrdd-json"] = $attributes["template"];
93                         elseif ($attributes["rel"] == "lrdd")
94                                 $xrd_data["lrdd"] = $attributes["template"];
95                 }
96                 return $xrd_data;
97         }
98
99         /**
100          * @brief Perform Webfinger lookup and return DFRN data
101          *
102          * Given an email style address, perform webfinger lookup and
103          * return the resulting DFRN profile URL, or if no DFRN profile URL
104          * is located, returns an OStatus subscription template (prefixed
105          * with the string 'stat:' to identify it as on OStatus template).
106          * If this isn't an email style address just return $webbie.
107          * Return an empty string if email-style addresses but webfinger fails,
108          * or if the resultant personal XRD doesn't contain a supported
109          * subscription/friend-request attribute.
110          *
111          * amended 7/9/2011 to return an hcard which could save potentially loading
112          * a lengthy content page to scrape dfrn attributes
113          *
114          * @param string $webbie Address that should be probed
115          * @param string $hcard Link to the hcard - is returned by reference
116          *
117          * @return string profile link
118          */
119
120         public static function webfinger_dfrn($webbie, &$hcard) {
121                 if (!strstr($webbie, '@'))
122                         return $webbie;
123
124                 $profile_link = '';
125
126                 $links = self::webfinger($webbie);
127                 logger('webfinger_dfrn: '.$webbie.':'.print_r($links,true), LOGGER_DATA);
128                 if (count($links)) {
129                         foreach ($links as $link) {
130                                 if ($link['@attributes']['rel'] === NAMESPACE_DFRN)
131                                         $profile_link = $link['@attributes']['href'];
132                                 if ($link['@attributes']['rel'] === NAMESPACE_OSTATUSSUB)
133                                         $profile_link = 'stat:'.$link['@attributes']['template'];
134                                 if ($link['@attributes']['rel'] === 'http://microformats.org/profile/hcard')
135                                         $hcard = $link['@attributes']['href'];
136                         }
137                 }
138                 return $profile_link;
139         }
140
141         /**
142          * @brief Check an URI for LRDD data
143          *
144          * this is a replacement for the "lrdd" function in include/network.php.
145          * It isn't used in this class and has some redundancies in the code.
146          * When time comes we can check the existing calls for "lrdd" if we can rework them.
147          *
148          * @param string $uri Address that should be probed
149          *
150          * @return array uri data
151          */
152         public static function lrdd($uri) {
153
154                 $lrdd = self::xrd($uri);
155
156                 if (!$lrdd) {
157                         $parts = @parse_url($uri);
158                         if (!$parts)
159                                 return array();
160
161                         $host = $parts["host"];
162
163                         $path_parts = explode("/", trim($parts["path"], "/"));
164
165                         do {
166                                 $lrdd = self::xrd($host);
167                                 $host .= "/".array_shift($path_parts);
168                         } while (!$lrdd AND (sizeof($path_parts) > 0));
169                 }
170
171                 if (!$lrdd)
172                         return array();
173
174                 foreach ($lrdd AS $key => $link) {
175                         if ($webfinger)
176                                 continue;
177
178                         if (!in_array($key, array("lrdd", "lrdd-xml", "lrdd-json")))
179                                 continue;
180
181                         $path = str_replace('{uri}', urlencode($uri), $link);
182                         $webfinger = self::webfinger($path);
183                 }
184
185                 if (!is_array($webfinger["links"]))
186                         return false;
187
188                 $data = array();
189
190                 foreach ($webfinger["links"] AS $link)
191                         $data[] = array("@attributes" => $link);
192
193                 if (is_array($webfinger["aliases"]))
194                         foreach ($webfinger["aliases"] AS $alias)
195                                 $data[] = array("@attributes" =>
196                                                         array("rel" => "alias",
197                                                                 "href" => $alias));
198
199                 return $data;
200         }
201
202         /**
203          * @brief Fetch information about a given uri
204          *
205          * @param string $uri Address that should be probed
206          * @param string $network Test for this specific network
207          * @param integer $uid User ID for the probe (only used for mails)
208          * @param boolean $cache Use cached values?
209          *
210          * @return array uri data
211          */
212         public static function uri($uri, $network = "", $uid = 0, $cache = true) {
213
214                 if ($cache) {
215                         $result = Cache::get("probe_url:".$network.":".$uri);
216                         if (!is_null($result)) {
217                                 $result = unserialize($result);
218                                 return $result;
219                         }
220                 }
221
222                 if ($uid == 0)
223                         $uid = local_user();
224
225                 $data = self::detect($uri, $network, $uid);
226
227                 if (!isset($data["url"]))
228                         $data["url"] = $uri;
229
230                 if ($data["photo"] != "")
231                         $data["baseurl"] = matching_url(normalise_link($data["baseurl"]), normalise_link($data["photo"]));
232                 else
233                         $data["photo"] = App::get_baseurl().'/images/person-175.jpg';
234
235                 if (!isset($data["name"]) OR ($data["name"] == "")) {
236                         if (isset($data["nick"]))
237                                 $data["name"] = $data["nick"];
238
239                         if ($data["name"] == "")
240                                 $data["name"] = $data["url"];
241                 }
242
243                 if (!isset($data["nick"]) OR ($data["nick"] == "")) {
244                         $data["nick"] = strtolower($data["name"]);
245
246                         if (strpos($data['nick'], ' '))
247                                 $data['nick'] = trim(substr($data['nick'], 0, strpos($data['nick'], ' ')));
248                 }
249
250                 if (!isset($data["network"]))
251                         $data["network"] = NETWORK_PHANTOM;
252
253                 $data = self::rearrange_data($data);
254
255                 // Only store into the cache if the value seems to be valid
256                 if (!in_array($data['network'], array(NETWORK_PHANTOM, NETWORK_MAIL))) {
257                         Cache::set("probe_url:".$network.":".$uri,serialize($data), CACHE_DAY);
258
259                         /// @todo temporary fix - we need a real contact update function that updates only changing fields
260                         /// The biggest problem is the avatar picture that could have a reduced image size.
261                         /// It should only be updated if the existing picture isn't existing anymore.
262                         if (($data['network'] != NETWORK_FEED) AND ($mode == PROBE_NORMAL) AND
263                                 $data["name"] AND $data["nick"] AND $data["url"] AND $data["addr"] AND $data["poll"])
264                                 q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `url` = '%s', `addr` = '%s',
265                                                 `notify` = '%s', `poll` = '%s', `alias` = '%s', `success_update` = '%s'
266                                         WHERE `nurl` = '%s' AND NOT `self` AND `uid` = 0",
267                                         dbesc($data["name"]),
268                                         dbesc($data["nick"]),
269                                         dbesc($data["url"]),
270                                         dbesc($data["addr"]),
271                                         dbesc($data["notify"]),
272                                         dbesc($data["poll"]),
273                                         dbesc($data["alias"]),
274                                         dbesc(datetime_convert()),
275                                         dbesc(normalise_link($data['url']))
276                         );
277                 }
278                 return $data;
279         }
280
281         /**
282          * @brief Detect information about a given uri
283          *
284          * @param string $uri Address that should be probed
285          * @param string $network Test for this specific network
286          * @param integer $uid User ID for the probe (only used for mails)
287          *
288          * @return array uri data
289          */
290         private function detect($uri, $network, $uid) {
291                 if (strstr($uri, '@')) {
292                         // If the URI starts with "mailto:" then jum directly to the mail detection
293                         if (strpos($url,'mailto:') !== false) {
294                                 $uri = str_replace('mailto:', '', $url);
295                                 return self::mail($uri, $uid);
296                         }
297
298                         if ($network == NETWORK_MAIL)
299                                 return self::mail($uri, $uid);
300
301                         // Remove "acct:" from the URI
302                         $uri = str_replace('acct:', '', $uri);
303
304                         $host = substr($uri,strpos($uri, '@') + 1);
305                         $nick = substr($uri,0, strpos($uri, '@'));
306
307                         if (strpos($uri, '@twitter.com'))
308                                 return array("network" => NETWORK_TWITTER);
309
310                         $lrdd = self::xrd($host);
311                         if (!$lrdd)
312                                 return self::mail($uri, $uid);
313
314                         $addr = $uri;
315                 } else {
316                         $parts = parse_url($uri);
317                         if (!isset($parts["scheme"]) OR
318                                 !isset($parts["host"]) OR
319                                 !isset($parts["path"]))
320                                 return false;
321
322                         // todo: Ports?
323                         $host = $parts["host"];
324
325                         if ($host == 'twitter.com')
326                                 return array("network" => NETWORK_TWITTER);
327
328                         $lrdd = self::xrd($host);
329
330                         $path_parts = explode("/", trim($parts["path"], "/"));
331
332                         while (!$lrdd AND (sizeof($path_parts) > 1)) {
333                                 $host .= "/".array_shift($path_parts);
334                                 $lrdd = self::xrd($host);
335                         }
336                         if (!$lrdd)
337                                 return self::feed($uri);
338
339                         $nick = array_pop($path_parts);
340                         $addr = $nick."@".$host;
341                 }
342                 $webfinger = false;
343
344                 /// @todo Do we need the prefix "acct:" or "acct://"?
345
346                 foreach ($lrdd AS $key => $link) {
347                         if ($webfinger)
348                                 continue;
349
350                         if (!in_array($key, array("lrdd", "lrdd-xml", "lrdd-json")))
351                                 continue;
352
353                         // Try webfinger with the address (user@domain.tld)
354                         $path = str_replace('{uri}', urlencode($addr), $link);
355                         $webfinger = self::webfinger($path);
356
357                         // If webfinger wasn't successful then try it with the URL - possibly in the format https://...
358                         if (!$webfinger AND ($uri != $addr)) {
359                                 $path = str_replace('{uri}', urlencode($uri), $link);
360                                 $webfinger = self::webfinger($path);
361
362                                 // Since the detection with the address wasn't successful, we delete it.
363                                 if ($webfinger) {
364                                         $nick = "";
365                                         $addr = "";
366                                 }
367                         }
368
369                 }
370                 if (!$webfinger)
371                         return self::feed($uri);
372
373                 $result = false;
374
375                 logger("Probing ".$uri, LOGGER_DEBUG);
376
377                 if (in_array($network, array("", NETWORK_DFRN)))
378                         $result = self::dfrn($webfinger);
379                 if ((!$result AND ($network == "")) OR ($network == NETWORK_DIASPORA))
380                         $result = self::diaspora($webfinger);
381                 if ((!$result AND ($network == "")) OR ($network == NETWORK_OSTATUS))
382                         $result = self::ostatus($webfinger);
383                 if ((!$result AND ($network == "")) OR ($network == NETWORK_PUMPIO))
384                         $result = self::pumpio($webfinger);
385                 if ((!$result AND ($network == "")) OR ($network == NETWORK_FEED))
386                         $result = self::feed($uri);
387                 else {
388                         // We overwrite the detected nick with our try if the previois routines hadn't detected it.
389                         // Additionally it is overwritten when the nickname doesn't make sense (contains spaces).
390                         if ((!isset($result["nick"]) OR ($result["nick"] == "") OR (strstr($result["nick"], " "))) AND ($nick != ""))
391                                 $result["nick"] = $nick;
392
393                         if ((!isset($result["addr"]) OR ($result["addr"] == "")) AND ($addr != ""))
394                                 $result["addr"] = $addr;
395                 }
396
397                 logger($uri." is ".$result["network"], LOGGER_DEBUG);
398
399                 if (!isset($result["baseurl"]) OR ($result["baseurl"] == "")) {
400                         $pos = strpos($result["url"], $host);
401                         if ($pos)
402                                 $result["baseurl"] = substr($result["url"], 0, $pos).$host;
403                 }
404
405                 return $result;
406         }
407
408         /**
409          * @brief Do a webfinger request
410          *
411          * @param string $url Address that should be probed
412          *
413          * @return array webfinger data
414          */
415         private function webfinger($url) {
416
417                 $xrd_timeout = Config::get('system','xrd_timeout', 20);
418                 $redirects = 0;
419
420                 $data = fetch_url($url, false, $redirects, $xrd_timeout, "application/xrd+xml");
421                 $xrd = parse_xml_string($data, false);
422
423                 if (!is_object($xrd)) {
424                         // If it is not XML, maybe it is JSON
425                         $webfinger = json_decode($data, true);
426
427                         if (!isset($webfinger["links"]))
428                                 return false;
429
430                         return $webfinger;
431                 }
432
433                 $xrd_arr = xml::element_to_array($xrd);
434                 if (!isset($xrd_arr["xrd"]["link"]))
435                         return false;
436
437                 $webfinger = array();
438
439                 if (isset($xrd_arr["xrd"]["subject"]))
440                         $webfinger["subject"] = $xrd_arr["xrd"]["subject"];
441
442                 if (isset($xrd_arr["xrd"]["alias"]))
443                         $webfinger["aliases"] = $xrd_arr["xrd"]["alias"];
444
445                 $webfinger["links"] = array();
446
447                 foreach ($xrd_arr["xrd"]["link"] AS $value => $data) {
448                         if (isset($data["@attributes"]))
449                                 $attributes = $data["@attributes"];
450                         elseif ($value == "@attributes")
451                                 $attributes = $data;
452                         else
453                                 continue;
454
455                         $webfinger["links"][] = $attributes;
456                 }
457                 return $webfinger;
458         }
459
460         /**
461          * @brief Poll the noscrape page (Friendica specific)
462          *
463          * @param string $noscrape Link to the noscrape page
464          * @param array $data The already fetched data
465          *
466          * @return array noscrape data
467          */
468         private function poll_noscrape($noscrape, $data) {
469                 $content = fetch_url($noscrape);
470                 if (!$content)
471                         return false;
472
473                 $json = json_decode($content, true);
474                 if (!is_array($json))
475                         return false;
476
477                 if (isset($json["fn"]))
478                         $data["name"] = $json["fn"];
479
480                 if (isset($json["addr"]))
481                         $data["addr"] = $json["addr"];
482
483                 if (isset($json["nick"]))
484                         $data["nick"] = $json["nick"];
485
486                 if (isset($json["comm"]))
487                         $data["community"] = $json["comm"];
488
489                 if (isset($json["tags"])) {
490                         $keywords = implode(" ", $json["tags"]);
491                         if ($keywords != "")
492                                 $data["keywords"] = $keywords;
493                 }
494
495                 $location = formatted_location($json);
496                 if ($location)
497                         $data["location"] = $location;
498
499                 if (isset($json["about"]))
500                         $data["about"] = $json["about"];
501
502                 if (isset($json["key"]))
503                         $data["pubkey"] = $json["key"];
504
505                 if (isset($json["photo"]))
506                         $data["photo"] = $json["photo"];
507
508                 if (isset($json["dfrn-request"]))
509                         $data["request"] = $json["dfrn-request"];
510
511                 if (isset($json["dfrn-confirm"]))
512                         $data["confirm"] = $json["dfrn-confirm"];
513
514                 if (isset($json["dfrn-notify"]))
515                         $data["notify"] = $json["dfrn-notify"];
516
517                 if (isset($json["dfrn-poll"]))
518                         $data["poll"] = $json["dfrn-poll"];
519
520                 return $data;
521         }
522
523         /**
524          * @brief Check for valid DFRN data
525          *
526          * @param array $data DFRN data
527          *
528          * @return int Number of errors
529          */
530         public static function valid_dfrn($data) {
531                 $errors = 0;
532                 if(!isset($data['key']))
533                         $errors ++;
534                 if(!isset($data['dfrn-request']))
535                         $errors ++;
536                 if(!isset($data['dfrn-confirm']))
537                         $errors ++;
538                 if(!isset($data['dfrn-notify']))
539                         $errors ++;
540                 if(!isset($data['dfrn-poll']))
541                         $errors ++;
542                 return $errors;
543         }
544
545         /**
546          * @brief Fetch data from a DFRN profile page
547          *
548          * @param string $profile Link to the profile page
549          *
550          * @return array profile data
551          */
552         public static function profile($profile) {
553
554                 $data = array();
555
556                 // Fetch data via noscrape - this is faster
557                 $noscrape = str_replace(array("/hcard/", "/profile/"), "/noscrape/", $profile);
558                 $data = self::poll_noscrape($noscrape, $data);
559
560                 if (!isset($data["notify"]) OR !isset($data["confirm"]) OR
561                         !isset($data["request"]) OR !isset($data["poll"]) OR
562                         !isset($data["poco"]) OR !isset($data["name"]) OR
563                         !isset($data["photo"]))
564                         $data = self::poll_hcard($profile, $data, true);
565
566                 $prof_data = array();
567                 $prof_data["addr"] = $data["addr"];
568                 $prof_data["nick"] = $data["nick"];
569                 $prof_data["dfrn-request"] = $data["request"];
570                 $prof_data["dfrn-confirm"] = $data["confirm"];
571                 $prof_data["dfrn-notify"] = $data["notify"];
572                 $prof_data["dfrn-poll"] = $data["poll"];
573                 $prof_data["dfrn-poco"] = $data["poco"];
574                 $prof_data["photo"] = $data["photo"];
575                 $prof_data["fn"] = $data["name"];
576                 $prof_data["key"] = $data["pubkey"];
577
578                 return $prof_data;
579         }
580
581         /**
582          * @brief Check for DFRN contact
583          *
584          * @param array $webfinger Webfinger data
585          *
586          * @return array DFRN data
587          */
588         private function dfrn($webfinger) {
589
590                 $hcard = "";
591                 $data = array();
592                 foreach ($webfinger["links"] AS $link) {
593                         if (($link["rel"] == NAMESPACE_DFRN) AND ($link["href"] != ""))
594                                 $data["network"] = NETWORK_DFRN;
595                         elseif (($link["rel"] == NAMESPACE_FEED) AND ($link["href"] != ""))
596                                 $data["poll"] = $link["href"];
597                         elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") AND
598                                 ($link["type"] == "text/html") AND ($link["href"] != ""))
599                                 $data["url"] = $link["href"];
600                         elseif (($link["rel"] == "http://microformats.org/profile/hcard") AND ($link["href"] != ""))
601                                 $hcard = $link["href"];
602                         elseif (($link["rel"] == NAMESPACE_POCO) AND ($link["href"] != ""))
603                                 $data["poco"] = $link["href"];
604                         elseif (($link["rel"] == "http://webfinger.net/rel/avatar") AND ($link["href"] != ""))
605                                 $data["photo"] = $link["href"];
606
607                         elseif (($link["rel"] == "http://joindiaspora.com/seed_location") AND ($link["href"] != ""))
608                                 $data["baseurl"] = trim($link["href"], '/');
609                         elseif (($link["rel"] == "http://joindiaspora.com/guid") AND ($link["href"] != ""))
610                                 $data["guid"] = $link["href"];
611                         elseif (($link["rel"] == "diaspora-public-key") AND ($link["href"] != "")) {
612                                 $data["pubkey"] = base64_decode($link["href"]);
613
614                                 //if (strstr($data["pubkey"], 'RSA ') OR ($link["type"] == "RSA"))
615                                 if (strstr($data["pubkey"], 'RSA '))
616                                         $data["pubkey"] = rsatopem($data["pubkey"]);
617                         }
618                 }
619
620                 if (!isset($data["network"]) OR ($hcard == ""))
621                         return false;
622
623                 // Fetch data via noscrape - this is faster
624                 $noscrape = str_replace("/hcard/", "/noscrape/", $hcard);
625                 $data = self::poll_noscrape($noscrape, $data);
626
627                 if (isset($data["notify"]) AND isset($data["confirm"]) AND isset($data["request"]) AND
628                         isset($data["poll"]) AND isset($data["name"]) AND isset($data["photo"]))
629                         return $data;
630
631                 $data = self::poll_hcard($hcard, $data, true);
632
633                 return $data;
634         }
635
636         /**
637          * @brief Poll the hcard page (Diaspora and Friendica specific)
638          *
639          * @param string $hcard Link to the hcard page
640          * @param array $data The already fetched data
641          * @param boolean $dfrn Poll DFRN specific data
642          *
643          * @return array hcard data
644          */
645         private function poll_hcard($hcard, $data, $dfrn = false) {
646
647                 $doc = new DOMDocument();
648                 if (!@$doc->loadHTMLFile($hcard))
649                         return false;
650
651                 $xpath = new DomXPath($doc);
652
653                 $vcards = $xpath->query("//div[contains(concat(' ', @class, ' '), ' vcard ')]");
654                 if (!is_object($vcards))
655                         return false;
656
657                 if ($vcards->length == 0)
658                         return false;
659
660                 $vcard = $vcards->item(0);
661
662                 // We have to discard the guid from the hcard in favour of the guid from lrdd
663                 // Reason: Hubzilla doesn't use the value "uid" in the hcard like Diaspora does.
664                 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' uid ')]", $vcard); // */
665                 if (($search->length > 0) AND ($data["guid"] == ""))
666                         $data["guid"] = $search->item(0)->nodeValue;
667
668                 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' nickname ')]", $vcard); // */
669                 if ($search->length > 0)
670                         $data["nick"] = $search->item(0)->nodeValue;
671
672                 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' fn ')]", $vcard); // */
673                 if ($search->length > 0)
674                         $data["name"] = $search->item(0)->nodeValue;
675
676                 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' searchable ')]", $vcard); // */
677                 if ($search->length > 0)
678                         $data["searchable"] = $search->item(0)->nodeValue;
679
680                 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' key ')]", $vcard); // */
681                 if ($search->length > 0) {
682                         $data["pubkey"] = $search->item(0)->nodeValue;
683                         if (strstr($data["pubkey"], 'RSA '))
684                                 $data["pubkey"] = rsatopem($data["pubkey"]);
685                 }
686
687                 $search = $xpath->query("//*[@id='pod_location']", $vcard); // */
688                 if ($search->length > 0)
689                         $data["baseurl"] = trim($search->item(0)->nodeValue, "/");
690
691                 $avatar = array();
692                 $photos = $xpath->query("//*[contains(concat(' ', @class, ' '), ' photo ') or contains(concat(' ', @class, ' '), ' avatar ')]", $vcard); // */
693                 foreach ($photos AS $photo) {
694                         $attr = array();
695                         foreach ($photo->attributes as $attribute)
696                                 $attr[$attribute->name] = trim($attribute->value);
697
698                         if (isset($attr["src"]) AND isset($attr["width"]))
699                                 $avatar[$attr["width"]] = $attr["src"];
700                 }
701
702                 if (sizeof($avatar)) {
703                         ksort($avatar);
704                         $data["photo"] = array_pop($avatar);
705                 }
706
707                 if ($dfrn) {
708                         // Poll DFRN specific data
709                         $search = $xpath->query("//link[contains(concat(' ', @rel), ' dfrn-')]");
710                         if ($search->length > 0) {
711                                 foreach ($search AS $link) {
712                                         //$data["request"] = $search->item(0)->nodeValue;
713                                         $attr = array();
714                                         foreach ($link->attributes as $attribute)
715                                                 $attr[$attribute->name] = trim($attribute->value);
716
717                                         $data[substr($attr["rel"], 5)] = $attr["href"];
718                                 }
719                         }
720
721                         // Older Friendica versions had used the "uid" field differently than newer versions
722                         if ($data["nick"] == $data["guid"])
723                                 unset($data["guid"]);
724                 }
725
726
727                 return $data;
728         }
729
730         /**
731          * @brief Check for Diaspora contact
732          *
733          * @param array $webfinger Webfinger data
734          *
735          * @return array Diaspora data
736          */
737         private function diaspora($webfinger) {
738
739                 $hcard = "";
740                 $data = array();
741                 foreach ($webfinger["links"] AS $link) {
742                         if (($link["rel"] == "http://microformats.org/profile/hcard") AND ($link["href"] != ""))
743                                 $hcard = $link["href"];
744                         elseif (($link["rel"] == "http://joindiaspora.com/seed_location") AND ($link["href"] != ""))
745                                 $data["baseurl"] = trim($link["href"], '/');
746                         elseif (($link["rel"] == "http://joindiaspora.com/guid") AND ($link["href"] != ""))
747                                 $data["guid"] = $link["href"];
748                         elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") AND
749                                 ($link["type"] == "text/html") AND ($link["href"] != ""))
750                                 $data["url"] = $link["href"];
751                         elseif (($link["rel"] == NAMESPACE_FEED) AND ($link["href"] != ""))
752                                 $data["poll"] = $link["href"];
753                         elseif (($link["rel"] == NAMESPACE_POCO) AND ($link["href"] != ""))
754                                 $data["poco"] = $link["href"];
755                         elseif (($link["rel"] == "salmon") AND ($link["href"] != ""))
756                                 $data["notify"] = $link["href"];
757                         elseif (($link["rel"] == "diaspora-public-key") AND ($link["href"] != "")) {
758                                 $data["pubkey"] = base64_decode($link["href"]);
759
760                                 //if (strstr($data["pubkey"], 'RSA ') OR ($link["type"] == "RSA"))
761                                 if (strstr($data["pubkey"], 'RSA '))
762                                         $data["pubkey"] = rsatopem($data["pubkey"]);
763                         }
764                 }
765
766                 if (!isset($data["url"]) OR ($hcard == ""))
767                         return false;
768
769                 if (is_array($webfinger["aliases"]))
770                         foreach ($webfinger["aliases"] AS $alias)
771                                 if (normalise_link($alias) != normalise_link($data["url"]) AND !strstr($alias, "@"))
772                                         $data["alias"] = $alias;
773
774                 // Fetch further information from the hcard
775                 $data = self::poll_hcard($hcard, $data);
776
777                 if (!$data)
778                         return false;
779
780                 if (isset($data["url"]) AND isset($data["guid"]) AND isset($data["baseurl"]) AND
781                         isset($data["pubkey"]) AND ($hcard != "")) {
782                         $data["network"] = NETWORK_DIASPORA;
783
784                         // We have to overwrite the detected value for "notify" since Hubzilla doesn't send it
785                         $data["notify"] = $data["baseurl"]."/receive/users/".$data["guid"];
786                         $data["batch"] = $data["baseurl"]."/receive/public";
787                 } else
788                         return false;
789
790                 return $data;
791         }
792
793         /**
794          * @brief Check for OStatus contact
795          *
796          * @param array $webfinger Webfinger data
797          *
798          * @return array OStatus data
799          */
800         private function ostatus($webfinger) {
801
802                 $data = array();
803                 if (is_array($webfinger["aliases"]))
804                         foreach($webfinger["aliases"] AS $alias)
805                                 if (strstr($alias, "@"))
806                                         $data["addr"] = str_replace('acct:', '', $alias);
807
808                 $pubkey = "";
809                 foreach ($webfinger["links"] AS $link) {
810                         if (($link["rel"] == "http://webfinger.net/rel/profile-page") AND
811                                 ($link["type"] == "text/html") AND ($link["href"] != ""))
812                                 $data["url"] = $link["href"];
813                         elseif (($link["rel"] == "salmon") AND ($link["href"] != ""))
814                                 $data["notify"] = $link["href"];
815                         elseif (($link["rel"] == NAMESPACE_FEED) AND ($link["href"] != ""))
816                                 $data["poll"] = $link["href"];
817                         elseif (($link["rel"] == "magic-public-key") AND ($link["href"] != "")) {
818                                 $pubkey = $link["href"];
819
820                                 if (substr($pubkey, 0, 5) === 'data:') {
821                                         if (strstr($pubkey, ','))
822                                                 $pubkey = substr($pubkey, strpos($pubkey, ',') + 1);
823                                         else
824                                                 $pubkey = substr($pubkey, 5);
825                                 } else
826                                         $pubkey = fetch_url($pubkey);
827
828                                 $key = explode(".", $pubkey);
829
830                                 if (sizeof($key) >= 3) {
831                                         $m = base64url_decode($key[1]);
832                                         $e = base64url_decode($key[2]);
833                                         $data["pubkey"] = metopem($m,$e);
834                                 }
835
836                         }
837                 }
838
839                 if (isset($data["notify"]) AND isset($data["pubkey"]) AND
840                         isset($data["poll"]) AND isset($data["url"])) {
841                         $data["network"] = NETWORK_OSTATUS;
842                 } else
843                         return false;
844
845                 // Fetch all additional data from the feed
846                 $feed = fetch_url($data["poll"]);
847                 $feed_data = feed_import($feed,$dummy1,$dummy2, $dummy3, true);
848                 if (!$feed_data)
849                         return false;
850
851                 if ($feed_data["header"]["author-name"] != "")
852                         $data["name"] = $feed_data["header"]["author-name"];
853
854                 if ($feed_data["header"]["author-nick"] != "")
855                         $data["nick"] = $feed_data["header"]["author-nick"];
856
857                 if ($feed_data["header"]["author-avatar"] != "")
858                         $data["photo"] = $feed_data["header"]["author-avatar"];
859
860                 if ($feed_data["header"]["author-id"] != "")
861                         $data["alias"] = $feed_data["header"]["author-id"];
862
863                 if ($feed_data["header"]["author-location"] != "")
864                         $data["location"] = $feed_data["header"]["author-location"];
865
866                 if ($feed_data["header"]["author-about"] != "")
867                         $data["about"] = $feed_data["header"]["author-about"];
868
869                 // OStatus has serious issues when the the url doesn't fit (ssl vs. non ssl)
870                 // So we take the value that we just fetched, although the other one worked as well
871                 if ($feed_data["header"]["author-link"] != "")
872                         $data["url"] = $feed_data["header"]["author-link"];
873
874                 /// @todo Fetch location and "about" from the feed as well
875                 return $data;
876         }
877
878         /**
879          * @brief Fetch data from a pump.io profile page
880          *
881          * @param string $profile Link to the profile page
882          *
883          * @return array profile data
884          */
885         private function pumpio_profile_data($profile) {
886
887                 $doc = new DOMDocument();
888                 if (!@$doc->loadHTMLFile($profile))
889                         return false;
890
891                 $xpath = new DomXPath($doc);
892
893                 $data = array();
894
895                 // This is ugly - but pump.io doesn't seem to know a better way for it
896                 $data["name"] = trim($xpath->query("//h1[@class='media-header']")->item(0)->nodeValue);
897                 $pos = strpos($data["name"], chr(10));
898                 if ($pos)
899                         $data["name"] = trim(substr($data["name"], 0, $pos));
900
901                 $avatar = $xpath->query("//img[@class='img-rounded media-object']")->item(0);
902                 if ($avatar)
903                         foreach ($avatar->attributes as $attribute)
904                                 if ($attribute->name == "src")
905                                         $data["photo"] = trim($attribute->value);
906
907                 $data["location"] = $xpath->query("//p[@class='location']")->item(0)->nodeValue;
908                 $data["about"] = $xpath->query("//p[@class='summary']")->item(0)->nodeValue;
909
910                 return $data;
911         }
912
913         /**
914          * @brief Check for pump.io contact
915          *
916          * @param array $webfinger Webfinger data
917          *
918          * @return array pump.io data
919          */
920         private function pumpio($webfinger) {
921
922                 $data = array();
923                 foreach ($webfinger["links"] AS $link) {
924                         if (($link["rel"] == "http://webfinger.net/rel/profile-page") AND
925                                 ($link["type"] == "text/html") AND ($link["href"] != ""))
926                                 $data["url"] = $link["href"];
927                         elseif (($link["rel"] == "activity-inbox") AND ($link["href"] != ""))
928                                 $data["notify"] = $link["href"];
929                         elseif (($link["rel"] == "activity-outbox") AND ($link["href"] != ""))
930                                 $data["poll"] = $link["href"];
931                         elseif (($link["rel"] == "dialback") AND ($link["href"] != ""))
932                                 $data["dialback"] = $link["href"];
933                 }
934                 if (isset($data["poll"]) AND isset($data["notify"]) AND
935                         isset($data["dialback"]) AND isset($data["url"])) {
936
937                         // by now we use these fields only for the network type detection
938                         // So we unset all data that isn't used at the moment
939                         unset($data["dialback"]);
940
941                         $data["network"] = NETWORK_PUMPIO;
942                 } else
943                         return false;
944
945                 $profile_data = self::pumpio_profile_data($data["url"]);
946
947                 if (!$profile_data)
948                         return false;
949
950                 $data = array_merge($data, $profile_data);
951
952                 return $data;
953         }
954
955         /**
956          * @brief Check page for feed link
957          *
958          * @param string $url Page link
959          *
960          * @return string feed link
961          */
962         private function get_feed_link($url) {
963                 $doc = new DOMDocument();
964
965                 if (!@$doc->loadHTMLFile($url))
966                         return false;
967
968                 $xpath = new DomXPath($doc);
969
970                 //$feeds = $xpath->query("/html/head/link[@type='application/rss+xml']");
971                 $feeds = $xpath->query("/html/head/link[@type='application/rss+xml' and @rel='alternate']");
972                 if (!is_object($feeds))
973                         return false;
974
975                 if ($feeds->length == 0)
976                         return false;
977
978                 $feed_url = "";
979
980                 foreach ($feeds AS $feed) {
981                         $attr = array();
982                         foreach ($feed->attributes as $attribute)
983                         $attr[$attribute->name] = trim($attribute->value);
984
985                         if ($feed_url == "")
986                                 $feed_url = $attr["href"];
987                 }
988
989                 return $feed_url;
990         }
991
992         /**
993          * @brief Check for feed contact
994          *
995          * @param string $url Profile link
996          * @param boolean $probe Do a probe if the page contains a feed link
997          *
998          * @return array feed data
999          */
1000         private function feed($url, $probe = true) {
1001                 $feed = fetch_url($url);
1002                 $feed_data = feed_import($feed, $dummy1, $dummy2, $dummy3, true);
1003
1004                 if (!$feed_data) {
1005                         if (!$probe)
1006                                 return false;
1007
1008                         $feed_url = self::get_feed_link($url);
1009
1010                         if (!$feed_url)
1011                                 return false;
1012
1013                         return self::feed($feed_url, false);
1014                 }
1015
1016                 if ($feed_data["header"]["author-name"] != "")
1017                         $data["name"] = $feed_data["header"]["author-name"];
1018
1019                 if ($feed_data["header"]["author-nick"] != "")
1020                         $data["nick"] = $feed_data["header"]["author-nick"];
1021
1022                 if ($feed_data["header"]["author-avatar"] != "")
1023                         $data["photo"] = $feed_data["header"]["author-avatar"];
1024
1025                 if ($feed_data["header"]["author-id"] != "")
1026                         $data["alias"] = $feed_data["header"]["author-id"];
1027
1028                 $data["url"] = $url;
1029                 $data["poll"] = $url;
1030
1031                 if ($feed_data["header"]["author-link"] != "")
1032                         $data["baseurl"] = $feed_data["header"]["author-link"];
1033                 else
1034                         $data["baseurl"] = $data["url"];
1035
1036                 $data["network"] = NETWORK_FEED;
1037
1038                 return $data;
1039         }
1040
1041         /**
1042          * @brief Check for mail contact
1043          *
1044          * @param string $uri Profile link
1045          * @param integer $uid User ID
1046          *
1047          * @return array mail data
1048          */
1049         private function mail($uri, $uid) {
1050
1051                 if (!validate_email($uri))
1052                         return false;
1053
1054                 $x = q("SELECT `prvkey` FROM `user` WHERE `uid` = %d LIMIT 1", intval($uid));
1055
1056                 $r = q("SELECT * FROM `mailacct` WHERE `uid` = %d AND `server` != '' LIMIT 1", intval($uid));
1057
1058                 if(count($x) && count($r)) {
1059                         $mailbox = construct_mailbox_name($r[0]);
1060                         $password = '';
1061                         openssl_private_decrypt(hex2bin($r[0]['pass']), $password,$x[0]['prvkey']);
1062                         $mbox = email_connect($mailbox,$r[0]['user'], $password);
1063                         if(!mbox)
1064                                 return false;
1065                 }
1066
1067                 $msgs = email_poll($mbox, $uri);
1068                 logger('searching '.$uri.', '.count($msgs).' messages found.', LOGGER_DEBUG);
1069
1070                 if (!count($msgs))
1071                         return false;
1072
1073                 $data = array();
1074
1075                 $data["addr"] = $uri;
1076                 $data["network"] = NETWORK_MAIL;
1077                 $data["name"] = substr($uri, 0, strpos($uri,'@'));
1078                 $data["nick"] = $data["name"];
1079                 $data["photo"] = avatar_img($uri);
1080
1081                 $phost = substr($uri, strpos($uri,'@') + 1);
1082                 $data["url"] = 'http://'.$phost."/".$data["nick"];
1083                 $data["notify"] = 'smtp '.random_string();
1084                 $data["poll"] = 'email '.random_string();
1085
1086                 $x = email_msg_meta($mbox, $msgs[0]);
1087                 if(stristr($x[0]->from, $uri))
1088                         $adr = imap_rfc822_parse_adrlist($x[0]->from, '');
1089                 elseif(stristr($x[0]->to, $uri))
1090                         $adr = imap_rfc822_parse_adrlist($x[0]->to, '');
1091                 if(isset($adr)) {
1092                         foreach($adr as $feadr) {
1093                                 if((strcasecmp($feadr->mailbox, $data["name"]) == 0)
1094                                         &&(strcasecmp($feadr->host, $phost) == 0)
1095                                         && (strlen($feadr->personal))) {
1096
1097                                         $personal = imap_mime_header_decode($feadr->personal);
1098                                         $data["name"] = "";
1099                                         foreach($personal as $perspart)
1100                                                 if ($perspart->charset != "default")
1101                                                         $data["name"] .= iconv($perspart->charset, 'UTF-8//IGNORE', $perspart->text);
1102                                                 else
1103                                                         $data["name"] .= $perspart->text;
1104
1105                                         $data["name"] = notags($data["name"]);
1106                                 }
1107                         }
1108                 }
1109                 imap_close($mbox);
1110
1111                 return $data;
1112         }
1113 }
1114 ?>