1 | <?php |
---|
2 | /** |
---|
3 | * @file repository.php |
---|
4 | * @brief OpenGnsys Repository REST API manager. |
---|
5 | * @warning All input and output messages are formatted in JSON. |
---|
6 | * @note Some ideas are based on article "How to create REST API for Android app using PHP, Slim and MySQL" by Ravi Tamada, thanx. |
---|
7 | * @license GNU GPLv3+ |
---|
8 | * @author Juan Manuel Bardallo SIC Universidad de Huelva |
---|
9 | * @version 1.0 |
---|
10 | * @date 2016-04-06 |
---|
11 | */ |
---|
12 | |
---|
13 | // Auxiliar functions. |
---|
14 | /** |
---|
15 | * @brief Validate API key included in "Authorization" HTTP header. |
---|
16 | * @return JSON response on error. |
---|
17 | */ |
---|
18 | function validateRepositoryApiKey() { |
---|
19 | $response = array(); |
---|
20 | $app = \Slim\Slim::getInstance(); |
---|
21 | |
---|
22 | // Read Authorization HTTP header. |
---|
23 | $headers = apache_request_headers(); |
---|
24 | if (! empty($headers['Authorization'])) { |
---|
25 | // Assign user id. that match this key to global variable. |
---|
26 | $apikey = htmlspecialchars($headers['Authorization']); |
---|
27 | // El repositorio recupera el token desde el fichero de configuracion ogAdmRepo.cfg |
---|
28 | $confFile = fopen("../../etc/ogAdmRepo.cfg", "r"); |
---|
29 | |
---|
30 | // Leemos cada linea hasta encontrar la clave "ApiToken" |
---|
31 | if ($confFile) { |
---|
32 | $found = false; |
---|
33 | while(!feof($confFile)){ |
---|
34 | $line = fgets($confFile); |
---|
35 | $key = strtok($line,"="); |
---|
36 | if($key == "ApiToken"){ |
---|
37 | $token = trim(strtok("=")); |
---|
38 | if(strcmp($apikey,$token) == 0){ |
---|
39 | $found = true; |
---|
40 | } |
---|
41 | } |
---|
42 | } |
---|
43 | if (!$found){ |
---|
44 | // Credentials error. |
---|
45 | $response['message'] = 'Login failed. Incorrect credentials'; |
---|
46 | jsonResponse(401, $response); |
---|
47 | $app->stop(); |
---|
48 | } |
---|
49 | } else { |
---|
50 | // Access error. |
---|
51 | $response['message'] = "An error occurred, please try again"; |
---|
52 | jsonResponse(500, $response); |
---|
53 | } |
---|
54 | } else { |
---|
55 | // Error: missing API key. |
---|
56 | $response['message'] = 'Missing Repository API key'; |
---|
57 | jsonResponse(400, $response); |
---|
58 | $app->stop(); |
---|
59 | } |
---|
60 | } |
---|
61 | |
---|
62 | function commandExist($cmd) { |
---|
63 | $returnVal = shell_exec("which $cmd"); |
---|
64 | return (empty($returnVal) ? false : true); |
---|
65 | } |
---|
66 | |
---|
67 | function humanSize($bytes) |
---|
68 | { |
---|
69 | $si_prefix = array( 'B', 'KB', 'MB', 'GB', 'TB', 'EB', 'ZB', 'YB' ); |
---|
70 | $base = 1024; |
---|
71 | $class = min((int)log($bytes , $base) , count($si_prefix) - 1); |
---|
72 | return sprintf('%1.2f' , $bytes / pow($base,$class)) . ' ' . $si_prefix[$class]; |
---|
73 | } |
---|
74 | |
---|
75 | // Define REST routes. |
---|
76 | |
---|
77 | |
---|
78 | /** |
---|
79 | * @brief List all images in the repository |
---|
80 | * @note Route: /repository/images, Method: GET |
---|
81 | * @param no |
---|
82 | * @return JSON object with directory, images array, ous array and disk data. |
---|
83 | */ |
---|
84 | $app->get('/repository/images(/)', 'validateRepositoryApiKey', |
---|
85 | function() use ($app) { |
---|
86 | $response = array(); |
---|
87 | // Read repository information file. |
---|
88 | $cfgFile = '/opt/opengnsys/etc/repoinfo.json'; |
---|
89 | $response = json_decode(@file_get_contents($cfgFile), true); |
---|
90 | // Check if directory exists. |
---|
91 | $imgPath = @$response['directory']; |
---|
92 | if (is_dir($imgPath)) { |
---|
93 | // Complete global image information. |
---|
94 | for ($i=0; $i<sizeof(@$response['images']); $i++) { |
---|
95 | $img = $response['images'][$i]; |
---|
96 | $file = $imgPath."/".($img['type']==="dir" ? $img["name"] : $img["name"].".".$img["type"]); |
---|
97 | $response['images'][$i]['size'] = @stat($file)['size']; |
---|
98 | $response['images'][$i]['modified'] = date("Y-m-d H:i:s", @stat($file)['mtime']); |
---|
99 | $response['images'][$i]['mode'] = substr(decoct(@stat($file)['mode']), -4); |
---|
100 | $backupfile = $file.".ant"; |
---|
101 | if (file_exists($backupfile)) { |
---|
102 | $response['images'][$i]['backedup'] = true; |
---|
103 | $response['images'][$i]['backupsize'] = @stat($backupfile)['size']; |
---|
104 | } else { |
---|
105 | $response['images'][$i]['backedup'] = false; |
---|
106 | } |
---|
107 | } |
---|
108 | // Complete image in OUs information. |
---|
109 | for ($j=0; $j<sizeof(@$response['ous']); $j++) { |
---|
110 | for ($i=0; $i<sizeof(@$response['ous'][$j]['images']); $i++) { |
---|
111 | $img = $response['ous'][$j]['images'][$i]; |
---|
112 | $file = $imgPath."/".$response['ous'][$j]['subdir']."/".($img['type']==="dir" ? $img["name"] : $img["name"].".".$img["type"]); |
---|
113 | $response['ous'][$j]['images'][$i]['size'] = @stat($file)['size']; |
---|
114 | $response['ous'][$j]['images'][$i]['modified'] = date("Y-m-d H:i:s", @stat($file)['mtime']); |
---|
115 | $response['ous'][$j]['images'][$i]['mode'] = substr(decoct(@stat($file)['mode']), -4); |
---|
116 | } |
---|
117 | } |
---|
118 | // Retrieve disk information. |
---|
119 | $total = disk_total_space($imgPath); |
---|
120 | $free = disk_free_space($imgPath); |
---|
121 | $response['disk']['total'] = humanSize($total); |
---|
122 | $response['disk']['used'] = humanSize($total - $free); |
---|
123 | $response['disk']['free'] = humanSize($free); |
---|
124 | $response['disk']['percent'] = 100 - floor(100 * $free / $total) . " %"; |
---|
125 | // JSON response. |
---|
126 | jsonResponse(200, $response); |
---|
127 | } else { |
---|
128 | // Print error message. |
---|
129 | $response['message'] = 'Images directory not found'; |
---|
130 | jsonResponse(404, $response); |
---|
131 | } |
---|
132 | $app->stop(); |
---|
133 | } |
---|
134 | ); |
---|
135 | |
---|
136 | |
---|
137 | /** |
---|
138 | * @brief Power on a pc or group of pcs with the MAC specified in POST parameters |
---|
139 | * @note Route: /poweron, Method: POST |
---|
140 | * @param macs OU id. |
---|
141 | * @return JSON string ok if the power on command was sent |
---|
142 | */ |
---|
143 | $app->post('/repository/poweron', 'validateRepositoryApiKey', |
---|
144 | function() { |
---|
145 | $app = \Slim\Slim::getInstance(); |
---|
146 | // Debe venir el parametro macs en el post (objeto JSON con array de MACs) |
---|
147 | $data = $app->request()->post(); |
---|
148 | if(empty($data->macs)){ |
---|
149 | // Print error message. |
---|
150 | $response['message'] = 'Required param macs not found'; |
---|
151 | jsonResponse(400, $response); |
---|
152 | } |
---|
153 | else{ |
---|
154 | $macs = $data->macs; |
---|
155 | $strMacs = ""; |
---|
156 | foreach($macs as $mac){ |
---|
157 | $strMacs .= " ".$mac; |
---|
158 | } |
---|
159 | // Ejecutar comando wakeonlan, debe estar disponible en el sistema operativo |
---|
160 | if(commandExist("wakeonlan")){ |
---|
161 | $response["output"] = "Executing wakeonlan ".trim($strMacs)."\n"; |
---|
162 | $response["output"] .= shell_exec("wakeonlan ".trim($strMacs)); |
---|
163 | // Comprobar si el comando se ejecutórrectamente |
---|
164 | jsonResponse(200, $response); |
---|
165 | } |
---|
166 | else{ |
---|
167 | // Print error message. |
---|
168 | $response['message'] = 'Wakeonlan command not found in this repository'; |
---|
169 | jsonResponse(404, $response); |
---|
170 | } |
---|
171 | } |
---|
172 | } |
---|
173 | ); |
---|
174 | |
---|
175 | ?> |
---|