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