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