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