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