<?

  require_once("config.php");
  
  header("Access-Control-Allow-Orgin: *");
  header("Access-Control-Allow-Methods: *");
  header("Content-Type: application/json");

  $requestUri = explode('/', trim($_SERVER['REQUEST_URI'],'/'));
  $requestParams = $_REQUEST;

  $method = $_SERVER['REQUEST_METHOD'];  

  function requestStatus($code) {
    $status = array(
        200 => 'OK',
        404 => 'Not Found',
        405 => 'Method Not Allowed',
        500 => 'Internal Server Error',
      );
    return ($status[$code])?$status[$code]:$status[500];
  } 
  
  function response($data, $status = 500) {
    header("HTTP/1.1 " . $status . " " . requestStatus($status));
    print json_encode($data);
  }

  function connect_db() {
  
    global $db,$mysql_host,$mysql_port,$mysql_schema,$mysql_user,$mysql_pwd;
  
    if (! ($db = new PDO("mysql:host=$mysql_host;port=$mysql_port;dbname=$mysql_schema",$mysql_user,$mysql_pwd,array( PDO::ATTR_PERSISTENT => false)))) {
      die($err);
    }  
    $db -> exec('SET CHARACTER SET utf8');

    return $db;

  }

  function exec_query($sql) {

    global $db;

    $q = $db -> prepare( $sql );
    $q -> bindParam(':s',$auth_token,PDO::PARAM_INT);
    $q -> execute();

    return $q -> fetchall(PDO::FETCH_ASSOC);

  }

  $api = $requestParams["method"];

  $data = Array();
  $code = 200;
  switch ($api) {
    case "get-base-config":

      $data["site-header"] = $site_header;
      
      connect_db();   
      
      $cats = exec_query("select mnemo,name,description from rep_cat");

      foreach ($cats as $cat => $value) {
        
        $cmnemo = $cats[$cat]["mnemo"];
        $reps = exec_query("select mnemo,name,description,graph_x,graph_y,graph_series from rep where cat_mnemo='$cmnemo'");
        $cats[$cat]["reps"] = $reps;
      
      }
      
      $data["cats"] = $cats;
      $data["templates"] = exec_query("select mnemo,body from web_templates");
      $data["columns"] = exec_query("select * from column_names");
      $users = exec_query("select id,username as name,alias from users");
      $hosts = exec_query("select id,hostname as name,alias from hosts");
      $data["dictionaries"] = Array( "user_id" => $users, "host_id" => $hosts);
      $data["online_refresh"] = $online_refresh;
      $data["online_history"] = $online_history;

      break;

    case "report":
    
      $mnemo = $requestParams["mnemo"];
      
      connect_db();    
      
      $rec = exec_query("select has_total,query from rep where mnemo='$mnemo'")[0];
      $sql = $rec["query"];
      $data["has_total"] = $rec["has_total"];

      $filter_str = "";
      $filter = Array();
      
      foreach ($requestParams as $name => $value) {
      
        if (($name == "mnemo") || ($name == "method")) { continue; }
        if ($name == "date_from") { $filter_str = $filter_str." and access_date>='$value'"; }
        elseif ($name == "date_to") { $filter_str = $filter_str." and access_date<date_add('$value',interval 1 day)"; }
        else { $filter_str = $filter_str." and $name = '$value'"; $filter[$name] = $value; }
      }

      if ($filter_str) {
        $sql = preg_replace('/\$FILTER;/',$filter_str,$sql);
      }

      if ($filter) {
        $data["filter"] = $filter;
      }
      $result = exec_query($sql);
      if ($result) {
        $data["dictionary"] = array_keys($result[0]);
        $data["data"] = $result;
      } else {
        $data["sql"] = $sql;
      }
    
      break;

    case "online":
    
      if($squid_passwd != "") { $pwd.="cachemgr:$cachemgr_passwd@"; } else { $pwd = ""; }
      $url = "http://".$pwd.$squid_host.":".$squid_port."/squid-internal-mgr/active_requests";

      $ch = curl_init($url);
  
      $options = array(
        CURLOPT_RETURNTRANSFER => true,   // return web page
        CURLOPT_HEADER         => false,  // don't return headers
        CURLOPT_FOLLOWLOCATION => false,   // follow redirects
        CURLOPT_MAXREDIRS      => 0,     // stop after 10 redirects
        CURLOPT_ENCODING       => "",     // handle compressed
        CURLOPT_USERAGENT      => "web", // name of client
        CURLOPT_AUTOREFERER    => true,   // set referrer on redirect
        CURLOPT_CONNECTTIMEOUT => 3,    // time-out on connect
        CURLOPT_TIMEOUT        => 5,    // time-out on response
      );

      curl_setopt_array($ch, $options);

      $reply = curl_exec($ch);
      $retcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

      // 400 means not found, 200 means found.
      curl_close($ch);

      if($retcode == 200) {

        $data["active"] = Array();
        
        if(preg_match("/HTTP/1.0 200 OK/",$ptmp)){
          $code = 500;
          $data=Array("error" => "No connection to Squid");
        } else {
          preg_match_all("/username(.+)/",$reply,$user);
          preg_match_all("/(peer|remote):(.+)/",$reply,$remote);
          preg_match_all("/uri(.+)/",$reply,$uri);
          preg_match_all("/out\.size(.+)/",$reply,$size);
          preg_match_all("/\((.+)seconds/",$reply,$sec);
          $sess = Array();
          for ($i=0; $i< count($user[1]); $i++) {
            $ip=trim($remote[2][$i]);
            $reversedParts = explode(':', strrev($ip), 2);
            $ip = strrev($reversedParts[1]);
            $port = strrev($reversedParts[0]);
            if (preg_match('/\[(.*)\]/',$ip,$matches)) {
              $ip = $matches[1];
            }
            $host = gethostbyaddr($ip);
            if (!$host) { $host = $ip; } 
            $username=trim($user[1][$i]);
            $site=trim($uri[1][$i]);
            $datasize=trim($size[1][$i]);
            $seconds = trim($sec[1][$i]);
            $record = Array("_user" => $username, "_ip" => $ip, "_port"=> $port, "host" => $host, "uri" => $site, "bytes" => $datasize, "seconds" => $seconds);
            $sess[] = $record;
          }
          $data["data"] = $sess;
          $data["dictionary"] = Array("_user","_ip","_port","host","uri","bytes","seconds");
        } 
      
      }
    
      break;

    default: 
      $data["error"] = "Method not found";
      $data["method"] = $api;
      $code = 404;
  }
  
  response($data,$code);
   
?>