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