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