]> git.mxchange.org Git - friendica.git/blob - src/Network/Probe.php
efd58e2b363d2ee111b132a3be66180b1e546fff
[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\Logger;
16 use Friendica\Core\Protocol;
17 use Friendica\Core\System;
18 use Friendica\Database\DBA;
19 use Friendica\Model\Contact;
20 use Friendica\Model\Profile;
21 use Friendica\Protocol\Email;
22 use Friendica\Protocol\Feed;
23 use Friendica\Protocol\ActivityPub;
24 use Friendica\Util\Crypto;
25 use Friendica\Util\DateTimeFormat;
26 use Friendica\Util\Network;
27 use Friendica\Util\Strings;
28 use Friendica\Util\XML;
29 use DomXPath;
30
31 require_once 'include/dba.php';
32
33 /**
34  * @brief This class contain functions for probing URL
35  *
36  */
37 class Probe
38 {
39         private static $baseurl;
40
41         /**
42          * @brief Rearrange the array so that it always has the same order
43          *
44          * @param array $data Unordered data
45          *
46          * @return array Ordered data
47          */
48         private static function rearrangeData($data)
49         {
50                 $fields = ["name", "nick", "guid", "url", "addr", "alias",
51                                 "photo", "community", "keywords", "location", "about",
52                                 "batch", "notify", "poll", "request", "confirm", "poco",
53                                 "priority", "network", "pubkey", "baseurl"];
54
55                 $newdata = [];
56                 foreach ($fields as $field) {
57                         if (isset($data[$field])) {
58                                 $newdata[$field] = $data[$field];
59                         } else {
60                                 $newdata[$field] = "";
61                         }
62                 }
63
64                 // We don't use the "priority" field anymore and replace it with a dummy.
65                 $newdata["priority"] = 0;
66
67                 return $newdata;
68         }
69
70         /**
71          * @brief Check if the hostname belongs to the own server
72          *
73          * @param string $host The hostname that is to be checked
74          *
75          * @return bool Does the testes hostname belongs to the own server?
76          */
77         private static function ownHost($host)
78         {
79                 $own_host = get_app()->getHostName();
80
81                 $parts = parse_url($host);
82
83                 if (!isset($parts['scheme'])) {
84                         $parts = parse_url('http://'.$host);
85                 }
86
87                 if (!isset($parts['host'])) {
88                         return false;
89                 }
90                 return $parts['host'] == $own_host;
91         }
92
93         /**
94          * @brief Probes for webfinger path via "host-meta"
95          *
96          * We have to check if the servers in the future still will offer this.
97          * It seems as if it was dropped from the standard.
98          *
99          * @param string $host The host part of an url
100          *
101          * @return array with template and type of the webfinger template for JSON or XML
102          */
103         private static function hostMeta($host)
104         {
105                 // Reset the static variable
106                 self::$baseurl = '';
107
108                 $ssl_url = "https://".$host."/.well-known/host-meta";
109                 $url = "http://".$host."/.well-known/host-meta";
110
111                 $xrd_timeout = Config::get('system', 'xrd_timeout', 20);
112                 $redirects = 0;
113
114                 Logger::log("Probing for ".$host, Logger::DEBUG);
115                 $xrd = null;
116
117                 $curlResult = Network::curl($ssl_url, false, $redirects, ['timeout' => $xrd_timeout, 'accept_content' => 'application/xrd+xml']);
118                 if ($curlResult->isSuccess()) {
119                         $xml = $curlResult->getBody();
120                         $xrd = XML::parseString($xml, false);
121                         $host_url = 'https://'.$host;
122                 }
123
124                 if (!is_object($xrd)) {
125                         $curlResult = Network::curl($url, false, $redirects, ['timeout' => $xrd_timeout, 'accept_content' => 'application/xrd+xml']);
126                         if ($curlResult->isTimeout()) {
127                                 Logger::log("Probing timeout for " . $url, Logger::DEBUG);
128                                 return false;
129                         }
130                         $xml = $curlResult->getBody();
131                         $xrd = XML::parseString($xml, false);
132                         $host_url = 'http://'.$host;
133                 }
134                 if (!is_object($xrd)) {
135                         Logger::log("No xrd object found for ".$host, Logger::DEBUG);
136                         return [];
137                 }
138
139                 $links = XML::elementToArray($xrd);
140                 if (!isset($links["xrd"]["link"])) {
141                         Logger::log("No xrd data found for ".$host, Logger::DEBUG);
142                         return [];
143                 }
144
145                 $lrdd = [];
146                 // The following webfinger path is defined in RFC 7033 https://tools.ietf.org/html/rfc7033
147                 // Problem is that Hubzilla currently doesn't provide all data in the JSON webfinger
148                 // compared to the XML webfinger. So this is commented out by now.
149                 // $lrdd = array("application/jrd+json" => $host_url.'/.well-known/webfinger?resource={uri}');
150
151                 foreach ($links["xrd"]["link"] as $value => $link) {
152                         if (!empty($link["@attributes"])) {
153                                 $attributes = $link["@attributes"];
154                         } elseif ($value == "@attributes") {
155                                 $attributes = $link;
156                         } else {
157                                 continue;
158                         }
159
160                         if (($attributes["rel"] == "lrdd") && !empty($attributes["template"])) {
161                                 $type = (empty($attributes["type"]) ? '' : $attributes["type"]);
162
163                                 $lrdd[$type] = $attributes["template"];
164                         }
165                 }
166
167                 self::$baseurl = "http://".$host;
168
169                 Logger::log("Probing successful for ".$host, Logger::DEBUG);
170
171                 return $lrdd;
172         }
173
174         /**
175          * @brief Perform Webfinger lookup and return DFRN data
176          *
177          * Given an email style address, perform webfinger lookup and
178          * return the resulting DFRN profile URL, or if no DFRN profile URL
179          * is located, returns an OStatus subscription template (prefixed
180          * with the string 'stat:' to identify it as on OStatus template).
181          * If this isn't an email style address just return $webbie.
182          * Return an empty string if email-style addresses but webfinger fails,
183          * or if the resultant personal XRD doesn't contain a supported
184          * subscription/friend-request attribute.
185          *
186          * amended 7/9/2011 to return an hcard which could save potentially loading
187          * a lengthy content page to scrape dfrn attributes
188          *
189          * @param string $webbie    Address that should be probed
190          * @param string $hcard_url Link to the hcard - is returned by reference
191          *
192          * @return string profile link
193          */
194         public static function webfingerDfrn($webbie, &$hcard_url)
195         {
196                 $profile_link = '';
197
198                 $links = self::lrdd($webbie);
199                 Logger::log('webfingerDfrn: '.$webbie.':'.print_r($links, true), Logger::DATA);
200                 if (count($links)) {
201                         foreach ($links as $link) {
202                                 if ($link['@attributes']['rel'] === NAMESPACE_DFRN) {
203                                         $profile_link = $link['@attributes']['href'];
204                                 }
205                                 if (($link['@attributes']['rel'] === NAMESPACE_OSTATUSSUB) && ($profile_link == "")) {
206                                         $profile_link = 'stat:'.$link['@attributes']['template'];
207                                 }
208                                 if ($link['@attributes']['rel'] === 'http://microformats.org/profile/hcard') {
209                                         $hcard_url = $link['@attributes']['href'];
210                                 }
211                         }
212                 }
213                 return $profile_link;
214         }
215
216         /**
217          * @brief Check an URI for LRDD data
218          *
219          * this is a replacement for the "lrdd" function.
220          * It isn't used in this class and has some redundancies in the code.
221          * When time comes we can check the existing calls for "lrdd" if we can rework them.
222          *
223          * @param string $uri Address that should be probed
224          *
225          * @return array uri data
226          */
227         public static function lrdd($uri)
228         {
229                 $lrdd = self::hostMeta($uri);
230                 $webfinger = null;
231
232                 if (is_bool($lrdd)) {
233                         return [];
234                 }
235
236                 if (!$lrdd) {
237                         $parts = @parse_url($uri);
238                         if (!$parts || empty($parts["host"]) || empty($parts["path"])) {
239                                 return [];
240                         }
241
242                         $host = $parts["host"];
243                         if (!empty($parts["port"])) {
244                                 $host .= ':'.$parts["port"];
245                         }
246
247                         $path_parts = explode("/", trim($parts["path"], "/"));
248
249                         $nick = array_pop($path_parts);
250
251                         do {
252                                 $lrdd = self::hostMeta($host);
253                                 $host .= "/".array_shift($path_parts);
254                         } while (!$lrdd && (sizeof($path_parts) > 0));
255                 }
256
257                 if (!$lrdd) {
258                         Logger::log("No lrdd data found for ".$uri, Logger::DEBUG);
259                         return [];
260                 }
261
262                 foreach ($lrdd as $type => $template) {
263                         if ($webfinger) {
264                                 continue;
265                         }
266
267                         $path = str_replace('{uri}', urlencode($uri), $template);
268                         $webfinger = self::webfinger($path, $type);
269
270                         if (!$webfinger && (strstr($uri, "@"))) {
271                                 $path = str_replace('{uri}', urlencode("acct:".$uri), $template);
272                                 $webfinger = self::webfinger($path, $type);
273                         }
274
275                         // Special treatment for Mastodon
276                         // Problem is that Mastodon uses an URL format like http://domain.tld/@nick
277                         // But the webfinger for this format fails.
278                         if (!$webfinger && !empty($nick)) {
279                                 // Mastodon uses a "@" as prefix for usernames in their url format
280                                 $nick = ltrim($nick, '@');
281
282                                 $addr = $nick."@".$host;
283
284                                 $path = str_replace('{uri}', urlencode("acct:".$addr), $template);
285                                 $webfinger = self::webfinger($path, $type);
286                         }
287                 }
288
289                 if (!is_array($webfinger["links"])) {
290                         Logger::log("No webfinger links found for ".$uri, Logger::DEBUG);
291                         return false;
292                 }
293
294                 $data = [];
295
296                 foreach ($webfinger["links"] as $link) {
297                         $data[] = ["@attributes" => $link];
298                 }
299
300                 if (is_array($webfinger["aliases"])) {
301                         foreach ($webfinger["aliases"] as $alias) {
302                                 $data[] = ["@attributes" =>
303                                                         ["rel" => "alias",
304                                                                 "href" => $alias]];
305                         }
306                 }
307
308                 return $data;
309         }
310
311         /**
312          * @brief Fetch information (protocol endpoints and user information) about a given uri
313          *
314          * @param string  $uri     Address that should be probed
315          * @param string  $network Test for this specific network
316          * @param integer $uid     User ID for the probe (only used for mails)
317          * @param boolean $cache   Use cached values?
318          *
319          * @return array uri data
320          */
321         public static function uri($uri, $network = "", $uid = -1, $cache = true)
322         {
323                 if ($cache) {
324                         $result = Cache::get("Probe::uri:".$network.":".$uri);
325                         if (!is_null($result)) {
326                                 return $result;
327                         }
328                 }
329
330                 if ($uid == -1) {
331                         $uid = local_user();
332                 }
333
334                 if ($network != Protocol::ACTIVITYPUB) {
335                         $data = self::detect($uri, $network, $uid);
336                 } else {
337                         $data = null;
338                 }
339
340                 $ap_profile = ActivityPub::probeProfile($uri);
341
342                 if (!empty($ap_profile) && (defaults($data, 'network', '') != Protocol::DFRN)) {
343                         $data = $ap_profile;
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-300.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::log('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::log('No XRD data was found for '.$uri, Logger::DEBUG);
636                                 return self::mail($uri, $uid);
637                         }
638                         $addr = $uri;
639                 } else {
640                         Logger::log("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::log("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::log($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                 $curlResult = Network::curl($url, false, $redirects, ['timeout' => $xrd_timeout, 'accept_content' => $type]);
748                 if ($curlResult->isTimeout()) {
749                         return false;
750                 }
751                 $data = $curlResult->getBody();
752
753                 $webfinger = json_decode($data, true);
754                 if (is_array($webfinger)) {
755                         if (!isset($webfinger["links"])) {
756                                 Logger::log("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::log("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::log("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                 $curlResult = Network::curl($noscrape_url);
815                 if ($curlResult->isTimeout()) {
816                         return false;
817                 }
818                 $content = $curlResult->getBody();
819                 if (!$content) {
820                         Logger::log("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::log("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::log("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"] = defaults($data, 'request', null);
959                 $prof_data["dfrn-confirm"] = defaults($data, 'confirm', null);
960                 $prof_data["dfrn-notify"]  = defaults($data, 'notify' , null);
961                 $prof_data["dfrn-poll"]    = defaults($data, 'poll'   , null);
962                 $prof_data["photo"]        = defaults($data, 'photo'  , null);
963                 $prof_data["fn"]           = defaults($data, 'name'   , null);
964                 $prof_data["key"]          = defaults($data, 'pubkey' , null);
965
966                 Logger::log("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                 $curlResult = Network::curl($hcard_url);
1060                 if ($curlResult->isTimeout()) {
1061                         return false;
1062                 }
1063                 $content = $curlResult->getBody();
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                                                 $curlResult = Network::curl($pubkey);
1307                                                 if ($curlResult->isTimeout()) {
1308                                                         return false;
1309                                                 }
1310                                                 $pubkey = $curlResult['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                 $curlResult = Network::curl($data["poll"]);
1339                 if ($curlResult->isTimeout()) {
1340                         return false;
1341                 }
1342                 $feed = $curlResult->getBody();
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                 $curlResult = Network::curl($url);
1549                 if ($curlResult->isTimeout()) {
1550                         return false;
1551                 }
1552                 $feed = $curlResult->getBody();
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::log('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 ' . Strings::getRandomHex();
1653                 $data["poll"]    = 'email ' . Strings::getRandomHex();
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"] = Strings::removeTags($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::log('Base: '.$base.' - Avatar: '.$avatar.' - Fixed: '.$fixed, Logger::DATA);
1720
1721                 return $fixed;
1722         }
1723 }