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: /images, Method: GET |
---|
81 | * @param no |
---|
82 | * @return JSON array with imagename, file size |
---|
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 T", @stat($file)['mtime']); |
---|
99 | $response['images'][$i]['mode'] = substr(decoct(@stat($file)['mode']), -4); |
---|
100 | } |
---|
101 | // Complete image in OUs information. |
---|
102 | for ($j=0; $j<sizeof(@$response['ous']); $j++) { |
---|
103 | for ($i=0; $i<sizeof(@$response['ous'][$j]['images']); $i++) { |
---|
104 | $img=$response['ous'][$j]['images'][$i]; |
---|
105 | $file=$imgPath."/".$response['ous'][$j]['subdir']."/".($img['type']==="dir" ? $img["name"] : $img["name"].".".$img["type"]); |
---|
106 | $response['ous'][$j]['images'][$i]['size'] = @stat($file)['size']; |
---|
107 | $response['ous'][$j]['images'][$i]['modified'] = date("Y-m-d H:i:s T", @stat($file)['mtime']); |
---|
108 | $response['ous'][$j]['images'][$i]['mode'] = substr(decoct(@stat($file)['mode']), -4); |
---|
109 | } |
---|
110 | } |
---|
111 | // Retrieve disk information. |
---|
112 | $total=disk_total_space($imgPath); |
---|
113 | $free=disk_free_space($imgPath); |
---|
114 | $response['disk']['total']=humanSize($total); |
---|
115 | $response['disk']['used']=humanSize($total - $free); |
---|
116 | $response['disk']['free']=humanSize($free); |
---|
117 | $response['disk']['percent']=floor(100 * $free / $total) . " %"; |
---|
118 | // JSON response. |
---|
119 | jsonResponse(200, $response); |
---|
120 | } else { |
---|
121 | // Print error message. |
---|
122 | $response['message'] = 'Images directory not found'; |
---|
123 | jsonResponse(404, $response); |
---|
124 | } |
---|
125 | $app->stop(); |
---|
126 | } |
---|
127 | ); |
---|
128 | |
---|
129 | |
---|
130 | /** |
---|
131 | * @brief Power on a pc or group of pcs with the MAC specified in POST parameters |
---|
132 | * @note Route: /poweron, Method: POST |
---|
133 | * @param macs OU id. |
---|
134 | * @return JSON string ok if the power on command was sent |
---|
135 | */ |
---|
136 | $app->post('/repository/poweron', 'validateRepositoryApiKey', |
---|
137 | function() { |
---|
138 | $app = \Slim\Slim::getInstance(); |
---|
139 | // Debe venir el parametro macs en el post (objeto JSON con array de MACs) |
---|
140 | $data = $app->request()->post(); |
---|
141 | if(empty($data->macs)){ |
---|
142 | // Print error message. |
---|
143 | $response['message'] = 'Required param macs not found'; |
---|
144 | jsonResponse(400, $response); |
---|
145 | } |
---|
146 | else{ |
---|
147 | $macs = $data->macs; |
---|
148 | $strMacs = ""; |
---|
149 | foreach($macs as $mac){ |
---|
150 | $strMacs .= " ".$mac; |
---|
151 | } |
---|
152 | // Ejecutar comando wakeonlan, debe estar disponible en el sistema operativo |
---|
153 | if(commandExist("wakeonlan")){ |
---|
154 | $response["output"] = "Executing wakeonlan ".trim($strMacs)."\n"; |
---|
155 | $response["output"] .= shell_exec("wakeonlan ".trim($strMacs)); |
---|
156 | // Comprobar si el comando se ejecutórrectamente |
---|
157 | jsonResponse(200, $response); |
---|
158 | } |
---|
159 | else{ |
---|
160 | // Print error message. |
---|
161 | $response['message'] = 'Wakeonlan command not found in this repository'; |
---|
162 | jsonResponse(404, $response); |
---|
163 | } |
---|
164 | } |
---|
165 | } |
---|
166 | ); |
---|
167 | |
---|
168 | ?> |
---|