forked from ColinWaddell/CurrantPi
-
Notifications
You must be signed in to change notification settings - Fork 0
/
api.php
104 lines (93 loc) · 2.54 KB
/
api.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
101
102
103
104
<?php
namespace CurrantPi;
/**
* api.php.
*
* Currant Pi - Raspberry Pi Status
*
* @author Colin Waddell
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link https://github.com/ColinWaddell/CurrantPi
*/
/*
* Libraries and helper function
*/
include('lib/CurrantModule.php');
include('lib/StringHelpers.php');
/*
* List of content sources
*/
$sources = [
// Directory Name => Name of Class
'footer' => 'FooterData',
'hardware' => 'HardwareData',
'load_average' => 'LoadAverageData',
'memory' => 'MemoryData',
'network' => 'NetworkData',
'storage' => 'StorageData',
];
function getModule($dir, $class)
{
// Load a module as defined in $sources
include 'content/'.$dir.'/'.$class.'.php';
$class_name = 'CurrantPi\\'.$class;
// Instantiate a version of the
// module, grab its data then
// append it to $server_info
$data_class = new $class_name;
return $data_class->getData();
}
/*
* Find out the URI which was given
* in order to access this page.
* non-existing uri's always will
* load everything
*/
$request_uri = null;
if (filter_has_var(INPUT_SERVER, "REQUEST_URI")) {
$request_uri = filter_input(INPUT_SERVER, "REQUEST_URI", FILTER_UNSAFE_RAW, FILTER_NULL_ON_FAILURE);
} elseif (isset($_SERVER["REQUEST_URI"])) {
$request_uri = filter_var($_SERVER["REQUEST_URI"], FILTER_UNSAFE_RAW, FILTER_NULL_ON_FAILURE);
}
$request_uri = explode('?', $request_uri);
$sourceRequest = end($request_uri);
if (empty($sourceRequest) || count($request_uri)<=1) {
/*
* No specific requests for the
* api so show everything.
*/
$modules = array_keys($sources);
} else {
$modules = explode(',', $sourceRequest);
}
/*
* Use $server_info to accumulate
* information about the server
* Always give an error if one of the modules
* isn't found for reliance
*/
$server_info = new \stdClass();
$error = null;
// Get all the variables or only specific; less loading time
foreach ($modules as $module) {
if (!isset($sources[$module])) {
$error = 'Module \'' . $module . '\' not available';
break;
}
$data = getModule($module, $sources[$module]);
$server_info->$module = $data;
}
/*
* Return a json formatted copy
* of the server information.
*/
header('Content-Type: application/json;');
if ($error) {
header("HTTP/1.0 400 Error");
$response = ['error' => $error];
} else {
$response = ['server_info' => $server_info];
header("HTTP/1.0 200 OK");
}
echo json_encode($response);