-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathroute.php
100 lines (88 loc) · 2.59 KB
/
route.php
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
<?php
add_action('rest_api_init', function () {
register_rest_route('partytown/pr', 'getPR', array(
'methods' => 'GET',
'callback' => __NAMESPACE__ . '\getPR',
// control nonce
'permission_callback' => function (\WP_REST_Request $request) {
$nonce = $request->get_param('pt_nonce');
return wp_verify_nonce($nonce, 'partytown_proxy');
}
));
});
function reformat($headers)
{
foreach ($headers as $name => $value) {
if ($value !== '') {
yield "$name: $value";
}
}
}
function getPR(\WP_REST_Request $request)
{
$method = $request->get_method();
// url in param
$urlRaw = $request->get_param('url');
// extract url
$url_components = parse_url($urlRaw);
parse_str($url_components['query'], $params);
if (!array_key_exists('url', $params)) {
return '';
}
$proxied_url = esc_url($params['url']);
$proxied_host = parse_url($proxied_url)['host'];
// init curl
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
curl_setopt($ch, CURLOPT_URL, $proxied_url);
// transfer header
$h = $request->get_headers();
foreach ($h as $key => $value) {
if (
$key !== 'host'
&& $key !== 'cookie'
) {
$request_headers[$key] = $value[0];
}
}
// set to host the service
$request_headers['Host'] = $proxied_host;
// website host
$request_headers['X-Forwarded-Host'] = $_SERVER['SERVER_NAME'];
// header from request
$request_headers = iterator_to_array(reformat($request_headers));
curl_setopt($ch, CURLOPT_HTTPHEADER, $request_headers);
// set cookies
curl_setopt($ch, CURLOPT_HTTPHEADER, $h['cookie']);
// message body
$request_body = file_get_contents('php://input');
curl_setopt($ch, CURLOPT_POSTFIELDS, $request_body);
$response_headers = [];
// catch header from response
curl_setopt(
$ch,
CURLOPT_HEADERFUNCTION,
function ($curl, $header) use (&$response_headers) {
$len = strlen($header);
$header = explode(':', $header, 2);
// ignore invalid headers
if (count($header) < 2)
return $len;
$response_headers[strtolower(trim($header[0]))][] = trim($header[1]);
return $len;
}
);
$response_body = curl_exec($ch);
$response_code = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
curl_close($ch);
// return header from curl response
http_response_code($response_code);
foreach ($response_headers as $name => $values) {
foreach ($values as $value) {
header("$name: $value", false);
}
}
echo $response_body;
}