]> git.mxchange.org Git - friendica.git/blob - include/Probe.php
8d4103aff1d3154b99fc83437b3e0829935db7a1
[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 (protocol endpoints and user 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 Fetch information (protocol endpoints and user information) about a given uri
283          *
284          * This function is only called by the "uri" function that adds caching and rearranging of data.
285          *
286          * @param string $uri Address that should be probed
287          * @param string $network Test for this specific network
288          * @param integer $uid User ID for the probe (only used for mails)
289          *
290          * @return array uri data
291          */
292         private function detect($uri, $network, $uid) {
293                 if (strstr($uri, '@')) {
294                         // If the URI starts with "mailto:" then jump directly to the mail detection
295                         if (strpos($url,'mailto:') !== false) {
296                                 $uri = str_replace('mailto:', '', $url);
297                                 return self::mail($uri, $uid);
298                         }
299
300                         if ($network == NETWORK_MAIL)
301                                 return self::mail($uri, $uid);
302
303                         // Remove "acct:" from the URI
304                         $uri = str_replace('acct:', '', $uri);
305
306                         $host = substr($uri,strpos($uri, '@') + 1);
307                         $nick = substr($uri,0, strpos($uri, '@'));
308
309                         if (strpos($uri, '@twitter.com'))
310                                 return array("network" => NETWORK_TWITTER);
311
312                         $lrdd = self::xrd($host);
313                         if (!$lrdd)
314                                 return self::mail($uri, $uid);
315
316                         $addr = $uri;
317                 } else {
318                         $parts = parse_url($uri);
319                         if (!isset($parts["scheme"]) OR
320                                 !isset($parts["host"]) OR
321                                 !isset($parts["path"]))
322                                 return false;
323
324                         // todo: Ports?
325                         $host = $parts["host"];
326
327                         if ($host == 'twitter.com')
328                                 return array("network" => NETWORK_TWITTER);
329
330                         $lrdd = self::xrd($host);
331
332                         $path_parts = explode("/", trim($parts["path"], "/"));
333
334                         while (!$lrdd AND (sizeof($path_parts) > 1)) {
335                                 $host .= "/".array_shift($path_parts);
336                                 $lrdd = self::xrd($host);
337                         }
338                         if (!$lrdd)
339                                 return self::feed($uri);
340
341                         $nick = array_pop($path_parts);
342                         $addr = $nick."@".$host;
343                 }
344                 $webfinger = false;
345
346                 /// @todo Do we need the prefix "acct:" or "acct://"?
347
348                 foreach ($lrdd AS $key => $link) {
349                         if ($webfinger)
350                                 continue;
351
352                         if (!in_array($key, array("lrdd", "lrdd-xml", "lrdd-json")))
353                                 continue;
354
355                         // Try webfinger with the address (user@domain.tld)
356                         $path = str_replace('{uri}', urlencode($addr), $link);
357                         $webfinger = self::webfinger($path);
358
359                         // If webfinger wasn't successful then try it with the URL - possibly in the format https://...
360                         if (!$webfinger AND ($uri != $addr)) {
361                                 $path = str_replace('{uri}', urlencode($uri), $link);
362                                 $webfinger = self::webfinger($path);
363
364                                 // Since the detection with the address wasn't successful, we delete it.
365                                 if ($webfinger) {
366                                         $nick = "";
367                                         $addr = "";
368                                 }
369                         }
370
371                 }
372                 if (!$webfinger)
373                         return self::feed($uri);
374
375                 $result = false;
376
377                 logger("Probing ".$uri, LOGGER_DEBUG);
378
379                 if (in_array($network, array("", NETWORK_DFRN)))
380                         $result = self::dfrn($webfinger);
381                 if ((!$result AND ($network == "")) OR ($network == NETWORK_DIASPORA))
382                         $result = self::diaspora($webfinger);
383                 if ((!$result AND ($network == "")) OR ($network == NETWORK_OSTATUS))
384                         $result = self::ostatus($webfinger);
385                 if ((!$result AND ($network == "")) OR ($network == NETWORK_PUMPIO))
386                         $result = self::pumpio($webfinger);
387                 if ((!$result AND ($network == "")) OR ($network == NETWORK_FEED))
388                         $result = self::feed($uri);
389                 else {
390                         // We overwrite the detected nick with our try if the previois routines hadn't detected it.
391                         // Additionally it is overwritten when the nickname doesn't make sense (contains spaces).
392                         if ((!isset($result["nick"]) OR ($result["nick"] == "") OR (strstr($result["nick"], " "))) AND ($nick != ""))
393                                 $result["nick"] = $nick;
394
395                         if ((!isset($result["addr"]) OR ($result["addr"] == "")) AND ($addr != ""))
396                                 $result["addr"] = $addr;
397                 }
398
399                 logger($uri." is ".$result["network"], LOGGER_DEBUG);
400
401                 if (!isset($result["baseurl"]) OR ($result["baseurl"] == "")) {
402                         $pos = strpos($result["url"], $host);
403                         if ($pos)
404                                 $result["baseurl"] = substr($result["url"], 0, $pos).$host;
405                 }
406
407                 return $result;
408         }
409
410         /**
411          * @brief Do a webfinger request. For details see RFC 7033: <https://tools.ietf.org/html/rfc7033>
412          *
413          * @param string $url Address that should be probed
414          *
415          * @return array webfinger data
416          */
417         private function webfinger($url) {
418
419                 $xrd_timeout = Config::get('system','xrd_timeout', 20);
420                 $redirects = 0;
421
422                 $data = fetch_url($url, false, $redirects, $xrd_timeout, "application/xrd+xml");
423                 $xrd = parse_xml_string($data, false);
424
425                 if (!is_object($xrd)) {
426                         // If it is not XML, maybe it is JSON
427                         $webfinger = json_decode($data, true);
428
429                         if (!isset($webfinger["links"]))
430                                 return false;
431
432                         return $webfinger;
433                 }
434
435                 $xrd_arr = xml::element_to_array($xrd);
436                 if (!isset($xrd_arr["xrd"]["link"]))
437                         return false;
438
439                 $webfinger = array();
440
441                 if (isset($xrd_arr["xrd"]["subject"]))
442                         $webfinger["subject"] = $xrd_arr["xrd"]["subject"];
443
444                 if (isset($xrd_arr["xrd"]["alias"]))
445                         $webfinger["aliases"] = $xrd_arr["xrd"]["alias"];
446
447                 $webfinger["links"] = array();
448
449                 foreach ($xrd_arr["xrd"]["link"] AS $value => $data) {
450                         if (isset($data["@attributes"]))
451                                 $attributes = $data["@attributes"];
452                         elseif ($value == "@attributes")
453                                 $attributes = $data;
454                         else
455                                 continue;
456
457                         $webfinger["links"][] = $attributes;
458                 }
459                 return $webfinger;
460         }
461
462         /**
463          * @brief Poll the noscrape page (Friendica specific)
464          *
465          * "noscrape" is a faster alternative to fetching the data from the hcard.
466          *
467          * @param string $noscrape Link to the noscrape page
468          * @param array $data The already fetched data
469          *
470          * @return array noscrape data
471          */
472         private function poll_noscrape($noscrape, $data) {
473                 $content = fetch_url($noscrape);
474                 if (!$content)
475                         return false;
476
477                 $json = json_decode($content, true);
478                 if (!is_array($json))
479                         return false;
480
481                 if (isset($json["fn"]))
482                         $data["name"] = $json["fn"];
483
484                 if (isset($json["addr"]))
485                         $data["addr"] = $json["addr"];
486
487                 if (isset($json["nick"]))
488                         $data["nick"] = $json["nick"];
489
490                 if (isset($json["comm"]))
491                         $data["community"] = $json["comm"];
492
493                 if (isset($json["tags"])) {
494                         $keywords = implode(" ", $json["tags"]);
495                         if ($keywords != "")
496                                 $data["keywords"] = $keywords;
497                 }
498
499                 $location = formatted_location($json);
500                 if ($location)
501                         $data["location"] = $location;
502
503                 if (isset($json["about"]))
504                         $data["about"] = $json["about"];
505
506                 if (isset($json["key"]))
507                         $data["pubkey"] = $json["key"];
508
509                 if (isset($json["photo"]))
510                         $data["photo"] = $json["photo"];
511
512                 if (isset($json["dfrn-request"]))
513                         $data["request"] = $json["dfrn-request"];
514
515                 if (isset($json["dfrn-confirm"]))
516                         $data["confirm"] = $json["dfrn-confirm"];
517
518                 if (isset($json["dfrn-notify"]))
519                         $data["notify"] = $json["dfrn-notify"];
520
521                 if (isset($json["dfrn-poll"]))
522                         $data["poll"] = $json["dfrn-poll"];
523
524                 return $data;
525         }
526
527         /**
528          * @brief Check for valid DFRN data
529          *
530          * @param array $data DFRN data
531          *
532          * @return int Number of errors
533          */
534         public static function valid_dfrn($data) {
535                 $errors = 0;
536                 if(!isset($data['key']))
537                         $errors ++;
538                 if(!isset($data['dfrn-request']))
539                         $errors ++;
540                 if(!isset($data['dfrn-confirm']))
541                         $errors ++;
542                 if(!isset($data['dfrn-notify']))
543                         $errors ++;
544                 if(!isset($data['dfrn-poll']))
545                         $errors ++;
546                 return $errors;
547         }
548
549         /**
550          * @brief Fetch data from a DFRN profile page and via "noscrape"
551          *
552          * @param string $profile Link to the profile page
553          *
554          * @return array profile data
555          */
556         public static function profile($profile) {
557
558                 $data = array();
559
560                 // Fetch data via noscrape - this is faster
561                 $noscrape = str_replace(array("/hcard/", "/profile/"), "/noscrape/", $profile);
562                 $data = self::poll_noscrape($noscrape, $data);
563
564                 if (!isset($data["notify"]) OR !isset($data["confirm"]) OR
565                         !isset($data["request"]) OR !isset($data["poll"]) OR
566                         !isset($data["poco"]) OR !isset($data["name"]) OR
567                         !isset($data["photo"]))
568                         $data = self::poll_hcard($profile, $data, true);
569
570                 $prof_data = array();
571                 $prof_data["addr"] = $data["addr"];
572                 $prof_data["nick"] = $data["nick"];
573                 $prof_data["dfrn-request"] = $data["request"];
574                 $prof_data["dfrn-confirm"] = $data["confirm"];
575                 $prof_data["dfrn-notify"] = $data["notify"];
576                 $prof_data["dfrn-poll"] = $data["poll"];
577                 $prof_data["dfrn-poco"] = $data["poco"];
578                 $prof_data["photo"] = $data["photo"];
579                 $prof_data["fn"] = $data["name"];
580                 $prof_data["key"] = $data["pubkey"];
581
582                 return $prof_data;
583         }
584
585         /**
586          * @brief Check for DFRN contact
587          *
588          * @param array $webfinger Webfinger data
589          *
590          * @return array DFRN data
591          */
592         private function dfrn($webfinger) {
593
594                 $hcard = "";
595                 $data = array();
596                 foreach ($webfinger["links"] AS $link) {
597                         if (($link["rel"] == NAMESPACE_DFRN) AND ($link["href"] != ""))
598                                 $data["network"] = NETWORK_DFRN;
599                         elseif (($link["rel"] == NAMESPACE_FEED) AND ($link["href"] != ""))
600                                 $data["poll"] = $link["href"];
601                         elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") AND
602                                 ($link["type"] == "text/html") AND ($link["href"] != ""))
603                                 $data["url"] = $link["href"];
604                         elseif (($link["rel"] == "http://microformats.org/profile/hcard") AND ($link["href"] != ""))
605                                 $hcard = $link["href"];
606                         elseif (($link["rel"] == NAMESPACE_POCO) AND ($link["href"] != ""))
607                                 $data["poco"] = $link["href"];
608                         elseif (($link["rel"] == "http://webfinger.net/rel/avatar") AND ($link["href"] != ""))
609                                 $data["photo"] = $link["href"];
610
611                         elseif (($link["rel"] == "http://joindiaspora.com/seed_location") AND ($link["href"] != ""))
612                                 $data["baseurl"] = trim($link["href"], '/');
613                         elseif (($link["rel"] == "http://joindiaspora.com/guid") AND ($link["href"] != ""))
614                                 $data["guid"] = $link["href"];
615                         elseif (($link["rel"] == "diaspora-public-key") AND ($link["href"] != "")) {
616                                 $data["pubkey"] = base64_decode($link["href"]);
617
618                                 //if (strstr($data["pubkey"], 'RSA ') OR ($link["type"] == "RSA"))
619                                 if (strstr($data["pubkey"], 'RSA '))
620                                         $data["pubkey"] = rsatopem($data["pubkey"]);
621                         }
622                 }
623
624                 if (!isset($data["network"]) OR ($hcard == ""))
625                         return false;
626
627                 // Fetch data via noscrape - this is faster
628                 $noscrape = str_replace("/hcard/", "/noscrape/", $hcard);
629                 $data = self::poll_noscrape($noscrape, $data);
630
631                 if (isset($data["notify"]) AND isset($data["confirm"]) AND isset($data["request"]) AND
632                         isset($data["poll"]) AND isset($data["name"]) AND isset($data["photo"]))
633                         return $data;
634
635                 $data = self::poll_hcard($hcard, $data, true);
636
637                 return $data;
638         }
639
640         /**
641          * @brief Poll the hcard page (Diaspora and Friendica specific)
642          *
643          * @param string $hcard Link to the hcard page
644          * @param array $data The already fetched data
645          * @param boolean $dfrn Poll DFRN specific data
646          *
647          * @return array hcard data
648          */
649         private function poll_hcard($hcard, $data, $dfrn = false) {
650
651                 $doc = new DOMDocument();
652                 if (!@$doc->loadHTMLFile($hcard))
653                         return false;
654
655                 $xpath = new DomXPath($doc);
656
657                 $vcards = $xpath->query("//div[contains(concat(' ', @class, ' '), ' vcard ')]");
658                 if (!is_object($vcards))
659                         return false;
660
661                 if ($vcards->length == 0)
662                         return false;
663
664                 $vcard = $vcards->item(0);
665
666                 // We have to discard the guid from the hcard in favour of the guid from lrdd
667                 // Reason: Hubzilla doesn't use the value "uid" in the hcard like Diaspora does.
668                 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' uid ')]", $vcard); // */
669                 if (($search->length > 0) AND ($data["guid"] == ""))
670                         $data["guid"] = $search->item(0)->nodeValue;
671
672                 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' nickname ')]", $vcard); // */
673                 if ($search->length > 0)
674                         $data["nick"] = $search->item(0)->nodeValue;
675
676                 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' fn ')]", $vcard); // */
677                 if ($search->length > 0)
678                         $data["name"] = $search->item(0)->nodeValue;
679
680                 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' searchable ')]", $vcard); // */
681                 if ($search->length > 0)
682                         $data["searchable"] = $search->item(0)->nodeValue;
683
684                 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' key ')]", $vcard); // */
685                 if ($search->length > 0) {
686                         $data["pubkey"] = $search->item(0)->nodeValue;
687                         if (strstr($data["pubkey"], 'RSA '))
688                                 $data["pubkey"] = rsatopem($data["pubkey"]);
689                 }
690
691                 $search = $xpath->query("//*[@id='pod_location']", $vcard); // */
692                 if ($search->length > 0)
693                         $data["baseurl"] = trim($search->item(0)->nodeValue, "/");
694
695                 $avatar = array();
696                 $photos = $xpath->query("//*[contains(concat(' ', @class, ' '), ' photo ') or contains(concat(' ', @class, ' '), ' avatar ')]", $vcard); // */
697                 foreach ($photos AS $photo) {
698                         $attr = array();
699                         foreach ($photo->attributes as $attribute)
700                                 $attr[$attribute->name] = trim($attribute->value);
701
702                         if (isset($attr["src"]) AND isset($attr["width"]))
703                                 $avatar[$attr["width"]] = $attr["src"];
704                 }
705
706                 if (sizeof($avatar)) {
707                         ksort($avatar);
708                         $data["photo"] = array_pop($avatar);
709                 }
710
711                 if ($dfrn) {
712                         // Poll DFRN specific data
713                         $search = $xpath->query("//link[contains(concat(' ', @rel), ' dfrn-')]");
714                         if ($search->length > 0) {
715                                 foreach ($search AS $link) {
716                                         //$data["request"] = $search->item(0)->nodeValue;
717                                         $attr = array();
718                                         foreach ($link->attributes as $attribute)
719                                                 $attr[$attribute->name] = trim($attribute->value);
720
721                                         $data[substr($attr["rel"], 5)] = $attr["href"];
722                                 }
723                         }
724
725                         // Older Friendica versions had used the "uid" field differently than newer versions
726                         if ($data["nick"] == $data["guid"])
727                                 unset($data["guid"]);
728                 }
729
730
731                 return $data;
732         }
733
734         /**
735          * @brief Check for Diaspora contact
736          *
737          * @param array $webfinger Webfinger data
738          *
739          * @return array Diaspora data
740          */
741         private function diaspora($webfinger) {
742
743                 $hcard = "";
744                 $data = array();
745                 foreach ($webfinger["links"] AS $link) {
746                         if (($link["rel"] == "http://microformats.org/profile/hcard") AND ($link["href"] != ""))
747                                 $hcard = $link["href"];
748                         elseif (($link["rel"] == "http://joindiaspora.com/seed_location") AND ($link["href"] != ""))
749                                 $data["baseurl"] = trim($link["href"], '/');
750                         elseif (($link["rel"] == "http://joindiaspora.com/guid") AND ($link["href"] != ""))
751                                 $data["guid"] = $link["href"];
752                         elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") AND
753                                 ($link["type"] == "text/html") AND ($link["href"] != ""))
754                                 $data["url"] = $link["href"];
755                         elseif (($link["rel"] == NAMESPACE_FEED) AND ($link["href"] != ""))
756                                 $data["poll"] = $link["href"];
757                         elseif (($link["rel"] == NAMESPACE_POCO) AND ($link["href"] != ""))
758                                 $data["poco"] = $link["href"];
759                         elseif (($link["rel"] == "salmon") AND ($link["href"] != ""))
760                                 $data["notify"] = $link["href"];
761                         elseif (($link["rel"] == "diaspora-public-key") AND ($link["href"] != "")) {
762                                 $data["pubkey"] = base64_decode($link["href"]);
763
764                                 //if (strstr($data["pubkey"], 'RSA ') OR ($link["type"] == "RSA"))
765                                 if (strstr($data["pubkey"], 'RSA '))
766                                         $data["pubkey"] = rsatopem($data["pubkey"]);
767                         }
768                 }
769
770                 if (!isset($data["url"]) OR ($hcard == ""))
771                         return false;
772
773                 if (is_array($webfinger["aliases"]))
774                         foreach ($webfinger["aliases"] AS $alias)
775                                 if (normalise_link($alias) != normalise_link($data["url"]) AND !strstr($alias, "@"))
776                                         $data["alias"] = $alias;
777
778                 // Fetch further information from the hcard
779                 $data = self::poll_hcard($hcard, $data);
780
781                 if (!$data)
782                         return false;
783
784                 if (isset($data["url"]) AND isset($data["guid"]) AND isset($data["baseurl"]) AND
785                         isset($data["pubkey"]) AND ($hcard != "")) {
786                         $data["network"] = NETWORK_DIASPORA;
787
788                         // We have to overwrite the detected value for "notify" since Hubzilla doesn't send it
789                         $data["notify"] = $data["baseurl"]."/receive/users/".$data["guid"];
790                         $data["batch"] = $data["baseurl"]."/receive/public";
791                 } else
792                         return false;
793
794                 return $data;
795         }
796
797         /**
798          * @brief Check for OStatus contact
799          *
800          * @param array $webfinger Webfinger data
801          *
802          * @return array OStatus data
803          */
804         private function ostatus($webfinger) {
805
806                 $data = array();
807                 if (is_array($webfinger["aliases"]))
808                         foreach($webfinger["aliases"] AS $alias)
809                                 if (strstr($alias, "@"))
810                                         $data["addr"] = str_replace('acct:', '', $alias);
811
812                 $pubkey = "";
813                 foreach ($webfinger["links"] AS $link) {
814                         if (($link["rel"] == "http://webfinger.net/rel/profile-page") AND
815                                 ($link["type"] == "text/html") AND ($link["href"] != ""))
816                                 $data["url"] = $link["href"];
817                         elseif (($link["rel"] == "salmon") AND ($link["href"] != ""))
818                                 $data["notify"] = $link["href"];
819                         elseif (($link["rel"] == NAMESPACE_FEED) AND ($link["href"] != ""))
820                                 $data["poll"] = $link["href"];
821                         elseif (($link["rel"] == "magic-public-key") AND ($link["href"] != "")) {
822                                 $pubkey = $link["href"];
823
824                                 if (substr($pubkey, 0, 5) === 'data:') {
825                                         if (strstr($pubkey, ','))
826                                                 $pubkey = substr($pubkey, strpos($pubkey, ',') + 1);
827                                         else
828                                                 $pubkey = substr($pubkey, 5);
829                                 } else
830                                         $pubkey = fetch_url($pubkey);
831
832                                 $key = explode(".", $pubkey);
833
834                                 if (sizeof($key) >= 3) {
835                                         $m = base64url_decode($key[1]);
836                                         $e = base64url_decode($key[2]);
837                                         $data["pubkey"] = metopem($m,$e);
838                                 }
839
840                         }
841                 }
842
843                 if (isset($data["notify"]) AND isset($data["pubkey"]) AND
844                         isset($data["poll"]) AND isset($data["url"])) {
845                         $data["network"] = NETWORK_OSTATUS;
846                 } else
847                         return false;
848
849                 // Fetch all additional data from the feed
850                 $feed = fetch_url($data["poll"]);
851                 $feed_data = feed_import($feed,$dummy1,$dummy2, $dummy3, true);
852                 if (!$feed_data)
853                         return false;
854
855                 if ($feed_data["header"]["author-name"] != "")
856                         $data["name"] = $feed_data["header"]["author-name"];
857
858                 if ($feed_data["header"]["author-nick"] != "")
859                         $data["nick"] = $feed_data["header"]["author-nick"];
860
861                 if ($feed_data["header"]["author-avatar"] != "")
862                         $data["photo"] = $feed_data["header"]["author-avatar"];
863
864                 if ($feed_data["header"]["author-id"] != "")
865                         $data["alias"] = $feed_data["header"]["author-id"];
866
867                 if ($feed_data["header"]["author-location"] != "")
868                         $data["location"] = $feed_data["header"]["author-location"];
869
870                 if ($feed_data["header"]["author-about"] != "")
871                         $data["about"] = $feed_data["header"]["author-about"];
872
873                 // OStatus has serious issues when the the url doesn't fit (ssl vs. non ssl)
874                 // So we take the value that we just fetched, although the other one worked as well
875                 if ($feed_data["header"]["author-link"] != "")
876                         $data["url"] = $feed_data["header"]["author-link"];
877
878                 /// @todo Fetch location and "about" from the feed as well
879                 return $data;
880         }
881
882         /**
883          * @brief Fetch data from a pump.io profile page
884          *
885          * @param string $profile Link to the profile page
886          *
887          * @return array profile data
888          */
889         private function pumpio_profile_data($profile) {
890
891                 $doc = new DOMDocument();
892                 if (!@$doc->loadHTMLFile($profile))
893                         return false;
894
895                 $xpath = new DomXPath($doc);
896
897                 $data = array();
898
899                 // This is ugly - but pump.io doesn't seem to know a better way for it
900                 $data["name"] = trim($xpath->query("//h1[@class='media-header']")->item(0)->nodeValue);
901                 $pos = strpos($data["name"], chr(10));
902                 if ($pos)
903                         $data["name"] = trim(substr($data["name"], 0, $pos));
904
905                 $avatar = $xpath->query("//img[@class='img-rounded media-object']")->item(0);
906                 if ($avatar)
907                         foreach ($avatar->attributes as $attribute)
908                                 if ($attribute->name == "src")
909                                         $data["photo"] = trim($attribute->value);
910
911                 $data["location"] = $xpath->query("//p[@class='location']")->item(0)->nodeValue;
912                 $data["about"] = $xpath->query("//p[@class='summary']")->item(0)->nodeValue;
913
914                 return $data;
915         }
916
917         /**
918          * @brief Check for pump.io contact
919          *
920          * @param array $webfinger Webfinger data
921          *
922          * @return array pump.io data
923          */
924         private function pumpio($webfinger) {
925
926                 $data = array();
927                 foreach ($webfinger["links"] AS $link) {
928                         if (($link["rel"] == "http://webfinger.net/rel/profile-page") AND
929                                 ($link["type"] == "text/html") AND ($link["href"] != ""))
930                                 $data["url"] = $link["href"];
931                         elseif (($link["rel"] == "activity-inbox") AND ($link["href"] != ""))
932                                 $data["notify"] = $link["href"];
933                         elseif (($link["rel"] == "activity-outbox") AND ($link["href"] != ""))
934                                 $data["poll"] = $link["href"];
935                         elseif (($link["rel"] == "dialback") AND ($link["href"] != ""))
936                                 $data["dialback"] = $link["href"];
937                 }
938                 if (isset($data["poll"]) AND isset($data["notify"]) AND
939                         isset($data["dialback"]) AND isset($data["url"])) {
940
941                         // by now we use these fields only for the network type detection
942                         // So we unset all data that isn't used at the moment
943                         unset($data["dialback"]);
944
945                         $data["network"] = NETWORK_PUMPIO;
946                 } else
947                         return false;
948
949                 $profile_data = self::pumpio_profile_data($data["url"]);
950
951                 if (!$profile_data)
952                         return false;
953
954                 $data = array_merge($data, $profile_data);
955
956                 return $data;
957         }
958
959         /**
960          * @brief Check page for feed link
961          *
962          * @param string $url Page link
963          *
964          * @return string feed link
965          */
966         private function get_feed_link($url) {
967                 $doc = new DOMDocument();
968
969                 if (!@$doc->loadHTMLFile($url))
970                         return false;
971
972                 $xpath = new DomXPath($doc);
973
974                 //$feeds = $xpath->query("/html/head/link[@type='application/rss+xml']");
975                 $feeds = $xpath->query("/html/head/link[@type='application/rss+xml' and @rel='alternate']");
976                 if (!is_object($feeds))
977                         return false;
978
979                 if ($feeds->length == 0)
980                         return false;
981
982                 $feed_url = "";
983
984                 foreach ($feeds AS $feed) {
985                         $attr = array();
986                         foreach ($feed->attributes as $attribute)
987                         $attr[$attribute->name] = trim($attribute->value);
988
989                         if ($feed_url == "")
990                                 $feed_url = $attr["href"];
991                 }
992
993                 return $feed_url;
994         }
995
996         /**
997          * @brief Check for feed contact
998          *
999          * @param string $url Profile link
1000          * @param boolean $probe Do a probe if the page contains a feed link
1001          *
1002          * @return array feed data
1003          */
1004         private function feed($url, $probe = true) {
1005                 $feed = fetch_url($url);
1006                 $feed_data = feed_import($feed, $dummy1, $dummy2, $dummy3, true);
1007
1008                 if (!$feed_data) {
1009                         if (!$probe)
1010                                 return false;
1011
1012                         $feed_url = self::get_feed_link($url);
1013
1014                         if (!$feed_url)
1015                                 return false;
1016
1017                         return self::feed($feed_url, false);
1018                 }
1019
1020                 if ($feed_data["header"]["author-name"] != "")
1021                         $data["name"] = $feed_data["header"]["author-name"];
1022
1023                 if ($feed_data["header"]["author-nick"] != "")
1024                         $data["nick"] = $feed_data["header"]["author-nick"];
1025
1026                 if ($feed_data["header"]["author-avatar"] != "")
1027                         $data["photo"] = $feed_data["header"]["author-avatar"];
1028
1029                 if ($feed_data["header"]["author-id"] != "")
1030                         $data["alias"] = $feed_data["header"]["author-id"];
1031
1032                 $data["url"] = $url;
1033                 $data["poll"] = $url;
1034
1035                 if ($feed_data["header"]["author-link"] != "")
1036                         $data["baseurl"] = $feed_data["header"]["author-link"];
1037                 else
1038                         $data["baseurl"] = $data["url"];
1039
1040                 $data["network"] = NETWORK_FEED;
1041
1042                 return $data;
1043         }
1044
1045         /**
1046          * @brief Check for mail contact
1047          *
1048          * @param string $uri Profile link
1049          * @param integer $uid User ID
1050          *
1051          * @return array mail data
1052          */
1053         private function mail($uri, $uid) {
1054
1055                 if (!validate_email($uri))
1056                         return false;
1057
1058                 $x = q("SELECT `prvkey` FROM `user` WHERE `uid` = %d LIMIT 1", intval($uid));
1059
1060                 $r = q("SELECT * FROM `mailacct` WHERE `uid` = %d AND `server` != '' LIMIT 1", intval($uid));
1061
1062                 if(count($x) && count($r)) {
1063                         $mailbox = construct_mailbox_name($r[0]);
1064                         $password = '';
1065                         openssl_private_decrypt(hex2bin($r[0]['pass']), $password,$x[0]['prvkey']);
1066                         $mbox = email_connect($mailbox,$r[0]['user'], $password);
1067                         if(!mbox)
1068                                 return false;
1069                 }
1070
1071                 $msgs = email_poll($mbox, $uri);
1072                 logger('searching '.$uri.', '.count($msgs).' messages found.', LOGGER_DEBUG);
1073
1074                 if (!count($msgs))
1075                         return false;
1076
1077                 $data = array();
1078
1079                 $data["addr"] = $uri;
1080                 $data["network"] = NETWORK_MAIL;
1081                 $data["name"] = substr($uri, 0, strpos($uri,'@'));
1082                 $data["nick"] = $data["name"];
1083                 $data["photo"] = avatar_img($uri);
1084
1085                 $phost = substr($uri, strpos($uri,'@') + 1);
1086                 $data["url"] = 'http://'.$phost."/".$data["nick"];
1087                 $data["notify"] = 'smtp '.random_string();
1088                 $data["poll"] = 'email '.random_string();
1089
1090                 $x = email_msg_meta($mbox, $msgs[0]);
1091                 if(stristr($x[0]->from, $uri))
1092                         $adr = imap_rfc822_parse_adrlist($x[0]->from, '');
1093                 elseif(stristr($x[0]->to, $uri))
1094                         $adr = imap_rfc822_parse_adrlist($x[0]->to, '');
1095                 if(isset($adr)) {
1096                         foreach($adr as $feadr) {
1097                                 if((strcasecmp($feadr->mailbox, $data["name"]) == 0)
1098                                         &&(strcasecmp($feadr->host, $phost) == 0)
1099                                         && (strlen($feadr->personal))) {
1100
1101                                         $personal = imap_mime_header_decode($feadr->personal);
1102                                         $data["name"] = "";
1103                                         foreach($personal as $perspart)
1104                                                 if ($perspart->charset != "default")
1105                                                         $data["name"] .= iconv($perspart->charset, 'UTF-8//IGNORE', $perspart->text);
1106                                                 else
1107                                                         $data["name"] .= $perspart->text;
1108
1109                                         $data["name"] = notags($data["name"]);
1110                                 }
1111                         }
1112                 }
1113                 imap_close($mbox);
1114
1115                 return $data;
1116         }
1117 }
1118 ?>