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