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