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