aboutsummaryrefslogtreecommitdiffstats
path: root/Zotlabs/Lib/Webfinger.php
blob: 8484fb79761682ecca315b982f60ab4e3def7d5c (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
<?php

namespace Zotlabs\Lib;

/**
 * @brief Fetch and return a webfinger for a resource
 *
 * @param string $resource - The resource
 * @return boolean|string false or associative array from result JSON
 */

class Webfinger {

	static private $server   = EMPTY_STR;
	static private $resource = EMPTY_STR;

	static function exec($resource) {

		if(! $resource) {
			return false;
		}

		self::parse_resource($resource);

		if(! ( self::$server && self::$resource)) {
			return false;
		}

		if(! check_siteallowed(self::$server)) {
			logger('blacklisted: ' . self::$server);
			return false;
		}

		btlogger('fetching resource: ' . self::$resource . ' from ' . self::$server, LOGGER_DEBUG, LOG_INFO);

		$url = 'https://' . self::$server . '/.well-known/webfinger?f=&resource=' . self::$resource ;

		$counter = 0;
		$s = z_fetch_url($url, false, $counter, [ 'headers' => [ 'Accept: application/jrd+json, */*' ] ]);

		if($s['success']) {
			$j = json_decode($s['body'], true);
			return($j);
		}

		return false;
	}

	static function parse_resource($resource) {

		self::$resource = urlencode($resource);

		if(strpos($resource,'http') === 0) {
			$m = parse_url($resource);
			if($m) {
				if($m['scheme'] !== 'https') {
					return false;
				}
				self::$server = $m['host'] . ((isset($m['port'])) ? ':' . $m['port'] : '');
			}
			else {
				return false;
			}
		}
		elseif(strpos($resource,'tag:') === 0) {
			$arr = explode(':',$resource); // split the tag
			$h = explode(',',$arr[1]); // split the host,date
			self::$server = $h[0];
		}
		else {
			$x = explode('@',$resource);
			$username = $x[0];
			if(count($x) > 1) {
				self::$server = $x[1];
			}
			else {
				return false;
			}
			if(strpos($resource,'acct:') !== 0) {
				self::$resource = urlencode('acct:' . $resource);
			}
		}

	}

	/**
	 * @brief fetch a webfinger resource and return a zot6 discovery url if present
	 *
	 */

	static function zot_url($resource) {

		$arr = self::exec($resource);

		if(is_array($arr) && array_key_exists('links',$arr)) {
			foreach($arr['links'] as $link) {
				if(array_key_exists('rel',$link) && $link['rel'] === PROTOCOL_ZOT6) {
					if(array_key_exists('href',$link) && $link['href'] !== EMPTY_STR) {
						return $link['href'];
					}
				}
			}
		}
		return false;
	}



}