-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtry.php
More file actions
210 lines (194 loc) · 9.1 KB
/
Copy pathtry.php
File metadata and controls
210 lines (194 loc) · 9.1 KB
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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
<?php
// Simple, minimal PHP wrapper to run the existing Python script and show its output.
// Location: /home/asher/public_html/try.php
// Usage examples:
// /try.php?mode=AUTO
// /try.php?city=Moscow&country=Russia&mode=ADDRESS
// /try.php?lat=55.7558&lon=37.6176&mode=COORDS
// Optional: &fajr=18.0&isha=18.0&madhab=hanafi
//
// Security notes:
// - Script path and python binary are fixed below (no user-controlled exec).
// - Inputs are validated and escaped before being placed into environment variables.
// - A system timeout is used to avoid long-running processes.
$SCRIPT_PATH = '/home/asher/github/triangle/try.py';
$PYTHON = '/usr/bin/python3'; // adjust if python3 is elsewhere
$TIMEOUT_SECONDS = 30;
// allowed simple values
$allowed_modes = ['AUTO', 'ADDRESS', 'COORDS', ''];
$allowed_madhab = ['hanafi', 'shafi', '']; // adjust if you support more
// collect and sanitize inputs
$get = function($k){
return isset($_GET[$k]) ? trim($_GET[$k]) : '';
};
$mode = strtoupper($get('mode'));
$mode = in_array($mode, $allowed_modes, true) ? $mode : '';
$city = substr($get('city'), 0, 200);
$state = substr($get('state'), 0, 200);
$country = substr($get('country'), 0, 200);
$lat = $get('lat'); $lon = $get('lon');
$fajr = $get('fajr'); $isha = $get('isha');
$madhab = strtolower($get('madhab'));
$madhab = in_array($madhab, $allowed_madhab, true) ? $madhab : '';
// numeric validation
if ($lat !== '' && !is_numeric($lat)) $lat = '';
if ($lon !== '' && !is_numeric($lon)) $lon = '';
if ($fajr !== '' && !is_numeric($fajr)) $fajr = '';
if ($isha !== '' && !is_numeric($isha)) $isha = '';
// --- new: attempt to detect client IP and lookup lat/lon if not provided ---
function get_client_ip() {
// Prefer X-Forwarded-For (choose the first public IP), then Client-IP, then REMOTE_ADDR
if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$parts = array_map('trim', explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']));
// pick the first public IP in the list
foreach ($parts as $p) {
if ($p && !is_private_ip($p)) return $p;
}
// fallback to first entry if all are private
if (!empty($parts[0])) return $parts[0];
}
if (!empty($_SERVER['HTTP_CLIENT_IP']) && !is_private_ip($_SERVER['HTTP_CLIENT_IP'])) {
return trim($_SERVER['HTTP_CLIENT_IP']);
}
return isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '';
}
function is_private_ip($ip) {
if (!filter_var($ip, FILTER_VALIDATE_IP)) return true;
// IPv4 private ranges
if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
$long = ip2long($ip);
$private_ranges = [
['start' => ip2long('10.0.0.0'), 'end' => ip2long('10.255.255.255')],
['start' => ip2long('172.16.0.0'), 'end' => ip2long('172.31.255.255')],
['start' => ip2long('192.168.0.0'), 'end' => ip2long('192.168.255.255')],
['start' => ip2long('127.0.0.0'), 'end' => ip2long('127.255.255.255')],
];
foreach ($private_ranges as $r) {
if ($long >= $r['start'] && $long <= $r['end']) return true;
}
return false;
}
// IPv6 loopback or unique local address (fc00::/7)
if (strpos($ip, '::1') !== false) return true;
if (stripos($ip, 'fc') === 0 || stripos($ip, 'fd') === 0) return true;
return false;
}
$detected_ip = get_client_ip();
$geo_lookup_note = '';
// Only attempt lookup if user did not supply lat/lon and IP appears public
if (($lat === '' || $lon === '') && $detected_ip !== '' && !is_private_ip($detected_ip)) {
// Prefer an HTTPS GeoIP provider (ipinfo.io) with a short timeout; fallback to ip-api.com
$tried = [];
$succeeded = false;
// ipinfo.io (HTTPS) - free tier has limits but is more reliable/secure
$url1 = 'https://ipinfo.io/' . rawurlencode($detected_ip) . '/json';
$ctx1 = stream_context_create(['http' => ['timeout' => 2], 'ssl' => ['verify_peer' => true, 'verify_peer_name' => true]]);
$json = @file_get_contents($url1, false, $ctx1);
$tried[] = $url1;
if ($json !== false) {
$data = json_decode($json, true);
if (is_array($data) && !empty($data['loc'])) {
// ipinfo returns "loc" as "lat,lon"
$parts = explode(',', $data['loc']);
if (count($parts) === 2) {
if ($lat === '' && is_numeric($parts[0])) $lat = $parts[0];
if ($lon === '' && is_numeric($parts[1])) $lon = $parts[1];
$geo_lookup_note = 'GeoIP (ipinfo) succeeded for ' . ($data['ip'] ?? $detected_ip);
$succeeded = true;
}
} elseif (is_array($data) && isset($data['error'])) {
$geo_lookup_note = 'GeoIP ipinfo error: ' . json_encode($data['error']);
}
}
if (!$succeeded) {
// fallback to ip-api.com (HTTP) with short timeout
$url2 = 'http://ip-api.com/json/' . rawurlencode($detected_ip) . '?fields=status,message,lat,lon,query';
$ctx2 = stream_context_create(['http' => ['timeout' => 2]]); // 2s timeout
$json2 = @file_get_contents($url2, false, $ctx2);
$tried[] = $url2;
if ($json2 !== false) {
$data2 = json_decode($json2, true);
if (is_array($data2) && isset($data2['status']) && $data2['status'] === 'success') {
if ($lat === '' && isset($data2['lat'])) $lat = $data2['lat'];
if ($lon === '' && isset($data2['lon'])) $lon = $data2['lon'];
$geo_lookup_note = 'GeoIP (ip-api) succeeded for ' . ($data2['query'] ?? $detected_ip);
$succeeded = true;
} else {
$geo_lookup_note = 'GeoIP ip-api failed: ' . ($data2['message'] ?? 'unknown');
}
} else {
if (!$succeeded) {
$geo_lookup_note = 'GeoIP attempts failed: ' . implode(' ; ', $tried);
}
}
}
} elseif ($detected_ip !== '' && is_private_ip($detected_ip)) {
$geo_lookup_note = 'Client IP is private/local, skipping GeoIP lookup';
} else {
// nothing to do or lat/lon already provided
}
// ensure script exists and is readable
if (!is_file($SCRIPT_PATH) || !is_readable($SCRIPT_PATH)) {
http_response_code(500);
header('Content-Type: text/plain; charset=utf-8');
echo "Error: Python script not found or not readable at {$SCRIPT_PATH}\n";
exit;
}
// build environment variables (only the keys the Python script expects)
$env = [];
if ($mode !== '') $env['LOCATION_MODE'] = $mode;
if ($city !== '') $env['CITY'] = $city;
if ($state !== '') $env['STATE'] = $state;
if ($country !== '') $env['COUNTRY'] = $country;
// Always set LATITUDE/LONGITUDE env keys (empty strings are acceptable and try.py handles fallbacks)
$env['LATITUDE'] = $lat;
$env['LONGITUDE'] = $lon;
if ($fajr !== '') $env['PRAYER_METHOD_ANGLES_FAJR'] = $fajr; // optional mapping
if ($isha !== '') $env['PRAYER_METHOD_ANGLES_ISHA'] = $isha;
if ($madhab !== '') $env['MADHAB'] = $madhab;
// include debug info about detected IP / geo lookup
if ($detected_ip !== '') $env['GEOIP_DETECTED_IP'] = $detected_ip;
if ($geo_lookup_note !== '') $env['GEOIP_NOTE'] = $geo_lookup_note;
// map simple env keys to ones used by try.py (try.py expects PRAYER_METHOD_ANGLES dict; we provide numeric env fallbacks)
$env_parts = [];
foreach ($env as $k => $v) {
// permit only A-Z0-9_ in env names
$k_safe = preg_replace('/[^A-Z0-9_]/', '', strtoupper($k));
$env_parts[] = $k_safe . '=' . escapeshellarg($v);
}
$env_str = implode(' ', $env_parts);
// build command safely
$python_cmd = escapeshellcmd($PYTHON);
$script_arg = escapeshellarg($SCRIPT_PATH);
$timeout_cmd = 'timeout ' . intval($TIMEOUT_SECONDS) . 's'; // requires coreutils timeout on the server
$full_cmd = trim($env_str . ' ' . $timeout_cmd . ' ' . $python_cmd . ' ' . $script_arg . ' 2>&1');
// run command and capture output
// shell_exec is simple; we already prevented user-controlled execables/paths in $PYTHON and $SCRIPT_PATH
$output = shell_exec($full_cmd);
if ($output === null) $output = "Error: command failed or timed out.";
// return a minimal HTML page with preformatted output
header('Content-Type: text/html; charset=utf-8');
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>try.py output</title>
<style>body{font-family:system-ui,Segoe UI,Arial;margin:20px}pre{background:#f5f5f5;padding:12px;border-radius:6px;overflow:auto}</style>
</head>
<body>
<h3>try.py output</h3>
<p><strong>Command run (for debugging):</strong></p>
<pre><?php echo htmlspecialchars($full_cmd, ENT_QUOTES|ENT_SUBSTITUTE, 'UTF-8'); ?></pre>
<p><strong>Script output:</strong></p>
<pre><?php echo htmlspecialchars($output, ENT_QUOTES|ENT_SUBSTITUTE, 'UTF-8'); ?></pre>
<?php if ($detected_ip !== ''): ?>
<p><strong>Detected client IP:</strong> <?php echo htmlspecialchars($detected_ip, ENT_QUOTES|ENT_SUBSTITUTE, 'UTF-8'); ?></p>
<?php endif; ?>
<?php if ($geo_lookup_note !== ''): ?>
<p><strong>GeoIP note:</strong> <?php echo htmlspecialchars($geo_lookup_note, ENT_QUOTES|ENT_SUBSTITUTE, 'UTF-8'); ?></p>
<?php endif; ?>
<hr>
<p>Usage: append query params like ?mode=AUTO or ?city=Moscow&country=Russia or ?lat=55.7558&lon=37.6176</p>
</body>
</html>