aboutsummaryrefslogtreecommitdiffstats
path: root/Zotlabs/Lib/ZotURL.php
blob: db0071f72a74caa4b8065b74fb2f8d72ba681d1c (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
<?php

namespace Zotlabs\Lib;

use Zotlabs\Web\HTTPSig;


class ZotURL {

	static public function fetch($url,$channel) {

		$ret = [ 'success' => false ];

		if(strpos($url,'x-zot:') !== 0) {
			return $ret;
		}


		if(! $url) {
			return $ret;
		}

		$portable_url = substr($url,6);
		$u = explode('/',$portable_url);
		$portable_id = $u[0];
		$hosts = self::lookup($portable_id);

		if(! $hosts) {
			return $ret;
		}

		foreach($hosts as $h) {
			$newurl = $h . '/id/' . $portable_url;

			$m = parse_url($newurl);

			$data = json_encode([ 'zot_token' => random_string() ]);

			if($channel && $m) {

				$headers = [
					'Accept'           => 'application/x-zot+json',
					'Content-Type'     => 'application/x-zot+json',
					'X-Zot-Token'      => random_string(),
					'Digest'           => HTTPSig::generate_digest_header($data),
					'Host'             => $m['host'],
					'(request-target)' => 'post ' . get_request_string($newurl)
				];
				$h = HTTPSig::create_sig($headers,$channel['channel_prvkey'],channel_url($channel),false);
			}
			else {
				$h = [ 'Accept: application/x-zot+json' ];
			}

			$result = [];

			$redirects = 0;
			$x = z_post_url($newurl,$data,$redirects, [ 'headers' => $h  ] );
			if($x['success']) {
				return $x;
			}
		}

		return $ret;

	}

	static public function is_zoturl($url) {

		if(strpos($url,'x-zot:') === 0) {
			return true;
		}
		return false;
	}


	static public function lookup($portable_id) {

		$r = q("select * from hubloc left join site on hubloc_url = site_url where hubloc_hash = '%s' and site_dead = 0 order by hubloc_primary desc",
			dbesc($portable_id)
		);

		if(! $r) {
			// extend to network lookup
			return false;
		}
		return ids_to_array($r,'hubloc_url');
	}

}