forked from emoncms/emoncms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcore.php
More file actions
499 lines (453 loc) · 15.3 KB
/
Copy pathcore.php
File metadata and controls
499 lines (453 loc) · 15.3 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
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
<?php
/*
All Emoncms code is released under the GNU Affero General Public License.
See COPYRIGHT.txt and LICENSE.txt.
---------------------------------------------------------------------
Emoncms - open source energy visualisation
Part of the OpenEnergyMonitor project:
http://openenergymonitor.org
*/
// no direct access
defined('EMONCMS_EXEC') or die('Restricted access');
/**
* Returns true if the TCP connection originates from a trusted proxy —
* i.e. localhost or a private (RFC 1918) address. This means forwarded
* headers (X-Forwarded-Host, X-Forwarded-Proto, etc.) were set by a local
* process such as nginx, a Dataplicity/ngrok tunnel agent, or Home Assistant
* ingress — not injected by a remote attacker.
*/
function is_trusted_proxy()
{
$remote = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '';
if ($remote === '127.0.0.1' || $remote === '::1') {
return true;
}
// FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE causes
// filter_var to return false for private/reserved ranges, true for public.
// So a private/loopback address returns false here, meaning is_trusted_proxy() = true.
return filter_var(
$remote,
FILTER_VALIDATE_IP,
FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE
) === false;
}
function is_https()
{
// Detect if we are running HTTPS or proxied HTTPS
if (server('HTTPS') == 'on') {
// Web server is running native HTTPS
return true;
} elseif (is_trusted_proxy() && server('HTTP_X_FORWARDED_PROTO') == "https") {
// Web server is running behind a trusted local proxy which is running HTTPS
return true;
} elseif (is_trusted_proxy() && server('HTTP_X_FORWARDED_PORT') == 443) {
// Web server is running behind a trusted local proxy which is running HTTPS
return true;
} elseif (is_trusted_proxy() && request_header('HTTP_X_FORWARDED_PROTO') == "https") {
return true;
}
return false;
}
function get_application_path($manual_domain = false)
{
if (is_https()) {
$proto = "https";
} else {
$proto = "http";
}
if ($manual_domain) {
return "$proto://".$manual_domain."/";
}
if (isset($_SERVER['HTTP_X_FORWARDED_HOST']) && is_trusted_proxy()) {
// X-Forwarded-Host is only trusted when the connection comes from a local
// proxy (localhost or LAN), e.g. nginx, Dataplicity, ngrok, HA ingress.
// A remote attacker cannot spoof this as their REMOTE_ADDR will be public.
$filepath = "$proto://" . server('HTTP_X_FORWARDED_HOST');
if (isset($_SERVER['HTTP_X_INGRESS_PATH'])) {
// web server is running in ingress mode in home assistant
$filepath .= server('HTTP_X_INGRESS_PATH');
}
$filepath .= server('SCRIPT_NAME');
$path = dirname($filepath) . "/";
} else {
$path = dirname("$proto://" . server('HTTP_HOST') . server('SCRIPT_NAME')) . "/";
}
return $path;
}
function db_check($mysqli, $database)
{
$stmt = $mysqli->prepare("SELECT count(table_schema) FROM information_schema.tables WHERE table_schema = ?");
$stmt->bind_param("s", $database);
$stmt->execute();
$stmt->bind_result($count);
$stmt->fetch();
$stmt->close();
return $count > 0;
}
function controller($controller_name)
{
$output = array('content'=>EMPTY_ROUTE);
if ($controller_name) {
$controller = $controller_name."_controller";
$controllerScript = "Modules/".$controller_name."/".$controller.".php";
if (is_file($controllerScript)) {
load_language_files("Modules/".$controller_name."/locale");
require_once $controllerScript;
$output = $controller();
if (!is_array($output) || !isset($output["content"])) {
$output = array("content"=>$output);
}
$output['is_controller'] = true;
} else {
$output['is_controller'] = false;
}
}
return $output;
}
function view($filepath, array $args = array())
{
global $path;
$args['path'] = $path;
$content = '';
if (file_exists($filepath)) {
unset($args['filepath']);
extract($args);
ob_start();
include "$filepath";
$content = ob_get_clean();
}
return $content;
}
/**
* strip slashes from GET values or null if not set
*
* @param string $index name of $_GET item
*
**/
function get($index, $error_if_missing = false, $default = null)
{
$val = $default;
if (isset($_GET[$index])) {
$val = rawurldecode($_GET[$index]);
} elseif ($error_if_missing) {
header('Content-Type: text/plain');
die("missing $index parameter");
}
if (!is_null($val)) {
$val = stripslashes($val);
}
return $val;
}
/**
* strip slashes from POST values or null if not set
*
* @param string $index name of $_POST item
*
**/
function post($index, $error_if_missing = false, $default = null)
{
$val = $default;
if (isset($_POST[$index])) {
// PHP automatically converts POST names with brackets `field[]` to type array
if (!is_array($_POST[$index])) {
$val = rawurldecode($_POST[$index]); // does not decode the plus symbol into spaces
} else {
$val = htmlspecialchars(json_encode($_POST[$index]));
}
} elseif ($error_if_missing) {
header('Content-Type: text/plain');
die("missing $index parameter");
}
if (!is_null($val)) {
if (is_array($val)) {
$val = array_map("stripslashes", $val);
} else {
$val = stripslashes($val);
}
}
return $val;
}
/**
* strip slashes from POST or GET values or null if not set
*
* @param string $index name of $_POST or $_GET item
*
**/
function prop($index, $error_if_missing = false, $default = null)
{
$val = $default;
if (isset($_GET[$index])) {
$val = $_GET[$index];
} elseif (isset($_POST[$index])) {
$val = $_POST[$index];
} elseif ($error_if_missing) {
header('Content-Type: text/plain');
die("missing $index parameter");
}
if (!is_null($val)) {
if (is_array($val)) {
$val = array_map("stripslashes", $val);
} else {
$val = stripslashes($val);
}
}
return $val;
}
function request_header($index)
{
$val = null;
$headers = apache_request_headers();
if (isset($headers[$index])) {
$val = $headers[$index];
}
return $val;
}
function server($index)
{
$val = null;
if (isset($_SERVER[$index])) {
$val = $_SERVER[$index];
}
return $val;
}
function delete($index)
{
parse_str(file_get_contents("php://input"), $_DELETE);//create array with posted (DELETE) method) values
$val = null;
if (isset($_DELETE[$index])) {
$val = $_DELETE[$index];
}
if (is_array($val)) {
$val = array_map("stripslashes", $val);
} else {
$val = stripslashes($val);
}
return $val;
}
function put($index)
{
parse_str(file_get_contents("php://input"), $_PUT);//create array with posted (PUT method) values
$val = null;
if (isset($_PUT[$index])) {
$val = $_PUT[$index];
}
if (is_array($val)) {
$val = array_map("stripslashes", $val);
} else {
$val = stripslashes($val);
}
return $val;
}
function version()
{
$version_file = json_decode(file_get_contents('./version.json'));
return $version_file->version;
}
function load_db_schema()
{
$schema = array();
$dir = scandir("Modules");
for ($i=2; $i<count($dir); $i++) {
if (filetype("Modules/".$dir[$i])=='dir' || filetype("Modules/".$dir[$i])=='link') {
if (is_file("Modules/".$dir[$i]."/".$dir[$i]."_schema.php")) {
require "Modules/".$dir[$i]."/".$dir[$i]."_schema.php";
}
}
}
return $schema;
}
/**
* binds the gettext translations to the correct file and domain/type
*
* @param string $path path to the directory containing the .mo files for each language
* @param [string] $domain
* @return void
*/
function load_language_files($path, $context = false)
{
// Determine current language
$lang = isset($GLOBALS['language']) ? $GLOBALS['language'] : 'en_GB'; // Default to English if not set
// Skip if $lang is en_GB
if ($lang == 'en_GB') {
// No need to load English translations, they are the default
return;
}
//echo "Loading language files for $lang in $path with domain $context<br>";
// Build path to JSON translation file
$json_file = rtrim($path, '/')."/$lang.json";
if (file_exists($json_file)) {
$translations = json_decode(file_get_contents($json_file), true);
if (is_array($translations)) {
if (!$context) {
// If domain is messages, we can use the translations directly
$GLOBALS['translations'] = $translations;
} else {
// For other context specific translations:
if (!isset($GLOBALS['context_translations'])) {
$GLOBALS['context_translations'] = array();
}
$GLOBALS['context_translations'][$context] = $translations;
}
}
}
}
function tr($text)
{
return isset($GLOBALS['translations'][$text]) && $GLOBALS['translations'][$text] !== ''
? $GLOBALS['translations'][$text]
: $text;
}
function ctx_tr($context, $text)
{
if ($context && isset($GLOBALS['context_translations'][$context]) && isset($GLOBALS['context_translations'][$context][$text])) {
// If context is set and translation exists in context, return it
return $GLOBALS['context_translations'][$context][$text];
}
return $text;
}
function load_menu()
{
global $menu;
$dir = scandir("Modules");
for ($i=2; $i<count($dir); $i++) {
if (filetype("Modules/".$dir[$i])=='dir' || filetype("Modules/".$dir[$i])=='link') {
if (is_file("Modules/".$dir[$i]."/".$dir[$i]."_menu.php")) {
// Language file gets loaded here but immediately over-written by the next
// Perhaps consider some form of caching or a different loading strategy
load_language_files("Modules/".$dir[$i]."/locale");
require "Modules/".$dir[$i]."/".$dir[$i]."_menu.php";
}
}
}
}
function http_request($method, $url, $data)
{
$options = array();
if ($method=="GET") {
$urlencoded = http_build_query($data);
$url = "$url?$urlencoded";
} elseif ($method=="POST") {
$options[CURLOPT_POST] = 1;
$options[CURLOPT_POSTFIELDS] = $data;
}
$options[CURLOPT_URL] = $url;
$options[CURLOPT_RETURNTRANSFER] = 1;
$options[CURLOPT_CONNECTTIMEOUT] = 2;
$options[CURLOPT_TIMEOUT] = 5;
$curl = curl_init();
curl_setopt_array($curl, $options);
$resp = curl_exec($curl);
if (PHP_VERSION_ID < 80000) {
// phpcs:ignore Generic.PHP.DeprecatedFunctions.Deprecated
curl_close($curl);
}
return $resp;
}
function emoncms_error($message)
{
return array("success"=>false, "message"=>$message);
}
function call_hook($function_name, $args)
{
// @todo: make args parameter optional
$dir = scandir("Modules");
for ($i=2; $i<count($dir); $i++) {
if (filetype("Modules/".$dir[$i])=='dir' || filetype("Modules/".$dir[$i])=='link') {
if (is_file("Modules/".$dir[$i]."/".$dir[$i]."_hooks.php")) {
require "Modules/".$dir[$i]."/".$dir[$i]."_hooks.php";
if (function_exists($dir[$i].'_'.$function_name)==true) {
$hook = $dir[$i].'_'.$function_name;
return $hook($args);
}
}
}
}
}
// ---------------------------------------------------------------------------------------------------------
/**
* return ip address of requesting machine
* the ip address can be stored in different variables by the system.
* which variable name may change dependant on different system setups.
* this function *should return an acceptible value in most cases
* @todo: more testing on different hardware/opperating systems/proxy servers etc.
*
* @return string
*/
function get_client_ip_env()
{
$ipaddress = filter_var(getenv('REMOTE_ADDR'), FILTER_VALIDATE_IP);
if (empty($ipaddress)) {
$ipaddress = '';
}
return $ipaddress;
}
// ---------------------------------------------------------------------------------------------------------
// Generate secure key
// ---------------------------------------------------------------------------------------------------------
function generate_secure_key($length)
{
if (function_exists('random_bytes')) {
return bin2hex(random_bytes($length));
} else {
return bin2hex(openssl_random_pseudo_bytes($length));
}
}
// ---------------------------------------------------------------------------------------------------------
// Generate a 16 bytes (128 bits) UUID - RFC 4122 compliant Version 4
// ---------------------------------------------------------------------------------------------------------
function guidv4()
{
if (function_exists('random_bytes')) {
$data = random_bytes(16);
} else {
$data = openssl_random_pseudo_bytes(16);
}
// Set version to 0100
$data[6] = chr(ord($data[6]) & 0x0f | 0x40);
// Set bits 6-7 to 10
$data[8] = chr(ord($data[8]) & 0x3f | 0x80);
// Output the 36 character UUID.
return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4));
}
// ---------------------------------------------------------------------------------------------------------
// Load JavaScript and CSS files with optional cache busting based on file modification time
// ---------------------------------------------------------------------------------------------------------
function load_js(string $file_path, bool $filemtime = true, $module = false): void {
global $path;
$version_string = "";
if ($filemtime && file_exists($file_path)) {
$version_string = "?v=" . filemtime($file_path);
}
$safe_path = htmlspecialchars($file_path, ENT_QUOTES, 'UTF-8');
if ($module) {
$module_str = 'type="module"';
} else {
$module_str = '';
}
echo '<script '.$module_str.' src="' . $path . $safe_path . $version_string . '"></script>' . "\n";
}
function load_css(string $file_path, bool $filemtime = true): void {
global $path;
$version_string = "";
if ($filemtime && file_exists($file_path)) {
$version_string = "?v=" . filemtime($file_path);
}
$safe_path = htmlspecialchars($file_path, ENT_QUOTES, 'UTF-8');
echo '<link rel="stylesheet" href="' . $path . $safe_path . $version_string . '">' . "\n";
}
function js_import_map(string $base, array $files): void {
global $path;
$imports = [];
foreach ($files as $file) {
$file_path = $base . $file;
$version_string = "";
if (file_exists($file_path)) {
$version_string = "?v=" . filemtime($file_path);
}
$specifier = $path . $file_path;
$url = htmlspecialchars($path . $file_path . $version_string, ENT_QUOTES, 'UTF-8');
$imports[$specifier] = $url;
}
$json = json_encode(['imports' => $imports]);
echo "<script type=\"importmap\">{$json}</script>\n";
}