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