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