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