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