Squid report generator (MySQL storage, reports/graphs online).
[squid-reports.git] / web / api.php
1 <?
2
3   require_once("config.php");
4   
5   header("Access-Control-Allow-Orgin: *");
6   header("Access-Control-Allow-Methods: *");
7   header("Content-Type: application/json");
8
9   $requestUri = explode('/', trim($_SERVER['REQUEST_URI'],'/'));
10   $requestParams = $_REQUEST;
11
12   $method = $_SERVER['REQUEST_METHOD'];  
13
14   function requestStatus($code) {
15     $status = array(
16         200 => 'OK',
17         404 => 'Not Found',
18         405 => 'Method Not Allowed',
19         500 => 'Internal Server Error',
20       );
21     return ($status[$code])?$status[$code]:$status[500];
22   } 
23   
24   function response($data, $status = 500) {
25     header("HTTP/1.1 " . $status . " " . requestStatus($status));
26     print json_encode($data);
27   }
28
29   function connect_db() {
30   
31     global $db,$mysql_host,$mysql_port,$mysql_schema,$mysql_user,$mysql_pwd;
32   
33     if (! ($db = new PDO("mysql:host=$mysql_host;port=$mysql_port;dbname=$mysql_schema",$mysql_user,$mysql_pwd,array( PDO::ATTR_PERSISTENT => false)))) {
34       die($err);
35     }  
36     $db -> exec('SET CHARACTER SET utf8');
37
38     return $db;
39
40   }
41
42   function exec_query($sql) {
43
44     global $db;
45
46     $q = $db -> prepare( $sql );
47     $q -> bindParam(':s',$auth_token,PDO::PARAM_INT);
48     $q -> execute();
49
50     return $q -> fetchall(PDO::FETCH_ASSOC);
51
52   }
53
54   $api = $requestParams["method"];
55
56   $data = Array();
57   $code = 200;
58   switch ($api) {
59     case "get-base-config":
60
61       $data["site-header"] = $site_header;
62       
63       connect_db();   
64       
65       $cats = exec_query("select mnemo,name,description from rep_cat");
66
67       foreach ($cats as $cat => $value) {
68         
69         $cmnemo = $cats[$cat]["mnemo"];
70         $reps = exec_query("select mnemo,name,description,graph_x,graph_y,graph_series from rep where cat_mnemo='$cmnemo'");
71         $cats[$cat]["reps"] = $reps;
72       
73       }
74       
75       $data["cats"] = $cats;
76       $data["templates"] = exec_query("select mnemo,body from web_templates");
77       $data["columns"] = exec_query("select * from column_names");
78       $users = exec_query("select id,username as name,alias from users");
79       $hosts = exec_query("select id,hostname as name,alias from hosts");
80       $data["dictionaries"] = Array( "user_id" => $users, "host_id" => $hosts);
81
82       break;
83
84     case "report":
85     
86       $mnemo = $requestParams["mnemo"];
87       
88       connect_db();    
89       
90       $rec = exec_query("select has_total,query from rep where mnemo='$mnemo'")[0];
91       $sql = $rec["query"];
92       $data["has_total"] = $rec["has_total"];
93
94       $filter_str = "";
95       $filter = Array();
96       
97       foreach ($requestParams as $name => $value) {
98       
99         if (($name == "mnemo") || ($name == "method")) { continue; }
100         if ($name == "date_from") { $filter_str = $filter_str." and access_date>='$value'"; }
101         elseif ($name == "date_to") { $filter_str = $filter_str." and access_date<date_add('$value',interval 1 day)"; }
102         else { $filter_str = $filter_str." and $name = '$value'"; $filter[$name] = $value; }
103       }
104
105       if ($filter_str) {
106         $sql = preg_replace('/\$FILTER;/',$filter_str,$sql);
107       }
108
109       if ($filter) {
110         $data["filter"] = $filter;
111       }
112       $result = exec_query($sql);
113       if ($result) {
114         $data["dictionary"] = array_keys($result[0]);
115         $data["data"] = $result;
116       } else {
117         $data["sql"] = $sql;
118       }
119     
120       break;
121
122     case "online":
123     
124       if($squid_passwd != "") { $pwd.="cachemgr:$cachemgr_passwd@"; } else { $pwd = ""; }
125       $url = "http://".$pwd.$squid_host.":".$squid_port."/squid-internal-mgr/active_requests";
126
127       $ch = curl_init($url);
128   
129       $options = array(
130         CURLOPT_RETURNTRANSFER => true,   // return web page
131         CURLOPT_HEADER         => false,  // don't return headers
132         CURLOPT_FOLLOWLOCATION => false,   // follow redirects
133         CURLOPT_MAXREDIRS      => 0,     // stop after 10 redirects
134         CURLOPT_ENCODING       => "",     // handle compressed
135         CURLOPT_USERAGENT      => "web", // name of client
136         CURLOPT_AUTOREFERER    => true,   // set referrer on redirect
137         CURLOPT_CONNECTTIMEOUT => 3,    // time-out on connect
138         CURLOPT_TIMEOUT        => 5,    // time-out on response
139       );
140
141       curl_setopt_array($ch, $options);
142
143       $reply = curl_exec($ch);
144       $retcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
145
146       // 400 means not found, 200 means found.
147       curl_close($ch);
148
149       if($retcode == 200) {
150
151         $data["active"] = Array();
152         
153         if(preg_match("/HTTP/1.0 200 OK/",$ptmp)){
154           $code = 500;
155           $data=Array("error" => "No connection to Squid");
156         } else {
157           preg_match_all("/username(.+)/",$reply,$user);
158           preg_match_all("/(peer|remote):(.+)/",$reply,$remote);
159           preg_match_all("/uri(.+)/",$reply,$uri);
160           preg_match_all("/out\.size(.+)/",$reply,$size);
161           preg_match_all("/\((.+)seconds/",$reply,$sec);
162           $sess = Array();
163           for ($i=0; $i< count($user[1]); $i++) {
164             $ip=trim($remote[2][$i]);
165             $reversedParts = explode(':', strrev($ip), 2);
166             $ip = strrev($reversedParts[1]);
167             $port = strrev($reversedParts[0]);
168             if (preg_match('/\[(.*)\]/',$ip,$matches)) {
169               $ip = $matches[1];
170             }
171             $host = gethostbyaddr($ip);
172             if (!$host) { $host = $ip; } 
173             $username=trim($user[1][$i]);
174             $site=trim($uri[1][$i]);
175             $datasize=trim($size[1][$i]);
176             $seconds = trim($sec[1][$i]);
177             $record = Array("_user" => $username, "_ip" => $ip, "_port"=> $port, "host" => $host, "uri" => $site, "bytes" => $datasize, "seconds" => $seconds);
178             $sess[] = $record;
179           }
180           $data["data"] = $sess;
181           $data["dictionary"] = Array("_user","_ip","_port","host","uri","bytes","seconds");
182         } 
183       
184       }
185     
186       break;
187
188     default: 
189       $data["error"] = "Method not found";
190       $data["method"] = $api;
191       $code = 404;
192   }
193   
194   response($data,$code);
195    
196 ?>