<?php
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
require("includes/logincheck.php");
require("config.php");
require("includes/functions.php");
require("includes/settings.php");

/* if(count($_POST) > 0){
  var_dump($_POST);
  exit();
  } */

$conn = @mysql_connect($dbhost, $dbuser, $dbpass) or die(mysql_error());
mysql_select_db($dbname);
$SQL = "SELECT name,url_ip,porta FROM cmum_profiles";
if ($_SESSION['adminlevel'] != "0") {
    $perfis_pm = implode(",", unserialize($_SESSION["_profiles_pm"]));
    $SQL .= " WHERE id IN ({$perfis_pm})";
}
$rs = mysql_query($SQL);
$perfis = array();
while ($row = mysql_fetch_assoc($rs)) {
    $perfis[$row["url_ip"]] = $row;
}
$url_perfis = array_keys($perfis);
$SQL = "SELECT id,ip_serv,desc_serv FROM cmum_csp_config WHERE 1=1 AND (";

foreach ($url_perfis as $url_csp) {
    $SQL .= "ip_serv LIKE '%{$url_csp}%' OR ";
}
$SQL = substr($SQL, 0, -4);
$SQL .= ")";
$rs = mysql_query($SQL);
$csps = array();
while ($row = mysql_fetch_assoc($rs)) {
    if ($row['ip_serv'] == $perfis[$row['ip_serv']]["url_ip"]) {
        $csps[$perfis[$row['ip_serv']]['name']] = $row;
    }
}
if (isset($_POST['id_serv']) && is_numeric($_POST['id_serv'])) {
    $id_serv = $_POST['id_serv'];
    $login = $_GET["login"];
    $SQL = "SELECT * FROM cmum_csp_config WHERE id='{$id_serv}'";
    $rs = mysql_query($SQL);
    $dados_serv = mysql_fetch_assoc($rs);
    //$url = "http://{$dados_serv["ip_serv"]}:{$dados_serv["porta_serv"]}/xmlHandler?command=login-failures";
    $url = "http://{$dados_serv["ip_serv"]}:{$dados_serv["porta_serv"]}/xmlHandler?command=login-failures";
    // conectando
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_USERPWD, $dados_serv["user_serv"] . ":" . $dados_serv["senha_serv"]);
    curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_UNRESTRICTED_AUTH, 1);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30); // TIME OUT is 5 seconds
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    if ($httpCode == 200) {
        $xml = simplexml_load_string($response);
    } else {
        echo "Erro: " . $httpCode;
        exit();
    }
    $param = json_decode(base64_decode($_POST['p']));
    $total_retorno = (Int) $xml->{"login-failures"}->attributes()->count;
    $dados_falha = array();
    $i = 0;
    //var_dump($param);
    if ($param->id == "0" && $_SESSION['adminlevel'] == "0") {
        if ($total_retorno > 0) {
            foreach ($xml->{"login-failures"}->{"entry"} as $falha) {
                $login = (String) $falha->attributes()->name;
                $time_first_failure = (Int) strtotime($falha->attributes()->{"first-failure"});
                $time_last_failure = (Int) strtotime($falha->attributes()->{"last-failure"});

                if (isset($_POST["sel-opc-busca"]) && $_POST["sel-opc-busca"] == 1) {
                    $busca_login = $_POST["busca_login"];
                    if (!preg_match("/{$busca_login}/i", $login)) {
                        continue;
                    }
                }
                if (isset($_POST["sel-opc-busca"]) && $_POST["sel-opc-busca"] == 2) {
                    if ($_POST["data_inicial"] != "" && $_POST["data_final"] != "") {
                        $data_inicial = strtotime(str_replace("/", "-", $_POST["data_inicial"]));
                        $data_final = strtotime(str_replace("/", "-", $_POST["data_final"]));
                        if(($time_first_failure < $data_inicial) || $time_first_failure > $data_final){
                            continue;                            
                        }
                    }
                }
                 if (isset($_POST["sel-opc-busca"]) && $_POST["sel-opc-busca"] == 3) {
                    if ($_POST["data_inicial"] != "" && $_POST["data_final"] != "") {
                        $data_inicial = strtotime(str_replace("/", "-", $_POST["data_inicial"]));
                        $data_final = strtotime(str_replace("/", "-", $_POST["data_final"]));
                        if(($time_last_failure < $data_inicial) || $time_last_failure > $data_final){
                            continue;                            
                        }
                    }
                }
                $dados_falha[$i]["login"] = $login;
                $dados_falha[$i]["porta_perfil"] = (String) $falha->attributes()->context;
                $dados_falha[$i]["inicio_falha"] = date('d/m/Y H:i:s', $time_first_failure);
                $dados_falha[$i]["ultima_falha"] = date('d/m/Y H:i:s', $time_last_failure);
                $dados_falha[$i]["ip"] = (String) $falha->attributes()->host;
                $dados_falha[$i]["obs"] = (String) $falha->attributes()->reason;
                $dados_falha[$i]["total_erros"] = (String) $falha->attributes()->{"failure-count"};
                $i++;
            }
        }
    } else {
        $conn = @mysql_connect($dbhost, $dbuser, $dbpass) or die(mysql_error());
        mysql_select_db($dbname);

        if ($_SESSION['adminlevel'] == "0") {
            $SQL = "SELECT name FROM cmum_udb WHERE addedby='{$param->id}'";
        } elseif ($param->id == "0") {
            $SQL = "SELECT name FROM cmum_udb WHERE addedby='{$_SESSION['adminid']}'";
        } else {
            $SQL = "SELECT name FROM cmum_udb WHERE addedby='{$param->id}'";
        }

        if ($param->id == "0") {
            $_arvore = arvoreRevendas2();
            $arvore = $_arvore[$_SESSION["adminid"]];
            if (!is_null($arvore)) {

                function listaLoginsRenvendasSub($_arv) {
                    global $SQL;
                    //var_dump($arvore);
                    foreach ($_arv as $folha) {
                        $SQL .= " UNION ALL SELECT name FROM cmum_udb WHERE addedby ='{$folha->id}'";
                        if (isset($folha->filhos)) {
                            listaLoginsRenvendasSub($folha->filhos);
                        }
                    }
                }

                listaLoginsRenvendasSub($arvore);
                //$SQL = substr($SQL, 0, -11);
            }
        }
        //var_dump($SQL);
        //exit();

        $rs = mysql_query($SQL);
        $logins = array();
        while ($row = mysql_fetch_assoc($rs)) {
            $logins[$row["name"]] = $row;
        }
        if ($total_retorno > 0) {
            foreach ($xml->{"login-failures"}->{"entry"} as $falha) {
                $login = (String) $falha->attributes()->name;
                $time_first_failure = (Int) strtotime($falha->attributes()->{"first-failure"});
                $time_last_failure = (Int) strtotime($falha->attributes()->{"last-failure"});
                if (!isset($logins[$login])) {
                    continue;
                }
                if (isset($_POST["sel-opc-busca"]) && $_POST["sel-opc-busca"] == 1) {
                    $busca_login = $_POST["busca_login"];
                    if (!preg_match("/{$busca_login}/i", $login)) {
                        continue;
                    }
                }
                 if (isset($_POST["sel-opc-busca"]) && $_POST["sel-opc-busca"] == 2) {
                    if ($_POST["data_inicial"] != "" && $_POST["data_final"] != "") {
                        $data_inicial = strtotime(str_replace("/", "-", $_POST["data_inicial"]));
                        $data_final = strtotime(str_replace("/", "-", $_POST["data_final"]));
                        if(($time_first_failure < $data_inicial) || $time_first_failure > $data_final){
                            continue;                            
                        }
                    }
                }
                 if (isset($_POST["sel-opc-busca"]) && $_POST["sel-opc-busca"] == 3) {
                    if ($_POST["data_inicial"] != "" && $_POST["data_final"] != "") {
                        $data_inicial = strtotime(str_replace("/", "-", $_POST["data_inicial"]));
                        $data_final = strtotime(str_replace("/", "-", $_POST["data_final"]));
                        if(($time_last_failure < $data_inicial) || $time_last_failure > $data_final){
                            continue;                            
                        }
                    }
                }
                $dados_falha[$i]["login"] = $login;
                $dados_falha[$i]["porta_perfil"] = (String) $falha->attributes()->context;
                $dados_falha[$i]["inicio_falha"] = date('d/m/Y H:i:s', $time_first_failure);
                $dados_falha[$i]["ultima_falha"] = date('d/m/Y H:i:s', $time_last_failure);
                $dados_falha[$i]["ip"] = (String) $falha->attributes()->host;
                $dados_falha[$i]["obs"] = (String) $falha->attributes()->reason;
                $dados_falha[$i]["total_erros"] = (String) $falha->attributes()->{"failure-count"};
                $i++;
            }
        }
        //
    }


    /*
     * @attributes] => Array
      (
      [name] => sand01
      [context] => N32460/clarotv
      [last-failure] => Tue, 29 Jul 2014 19:32:15 +0000
      [first-failure] => Mon, 28 Jul 2014 03:06:10 +0000
      [failure-count] => 45948
      [host] => 201.9.125.122
      [reason] => unauthorized/invalid/missing password
      )
     * 
     */
}
?>
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
            <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
            <title><?php print($longtitle); ?></title>
            <link rel="shortcut icon" href="favicon.ico"/>
            <link rel="apple-touch-icon" href="favicon.png"/>
            <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
            <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
            <link href="css/main.css" rel="stylesheet" type="text/css" /> 

            <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
            <script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
            <script>
                $(function() {
                    $("#data_inicial").datepicker({
                        dateFormat: "dd/mm/yy 00:00:00"

                    });
                    $("#data_final").datepicker({
                        dateFormat: "dd/mm/yy 23:59:59"
                    });
                });
            </script>
            <script src="//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>                
    </head>
    <body style="font-size: 8pt;">                        
        <?php require_once 'topo.php'; ?>
        <div id="tudo" style="border: solid 0px red; width: 980px; margin: auto;">                        
            <p>Falhas de logins no servidor</p>
            <form method="post">
                <div class="form-group" style="width: 20%; float: left;">
                    <label>Servidor</label>
                    <select name="id_serv" id="id_serv" class="form-control">
                        <?php foreach ($csps as $perf => $dados_serv): ?>
                            <option value="<?php echo $dados_serv['id']; ?>" <?php if ($dados_serv['id'] == $_POST['id_serv']): ?>selected<?php endif; ?>><?php echo $dados_serv['desc_serv']; ?></option>
                        <?php endforeach; ?>
                    </select>
                    </div>
                <div class="form-group"  style="width: 20%; margin-left: 21%">
                    <label>Revenda:</label>  
                    <select name='p' class='form-control' id="_p">
                        <?php
                        $json["id"] = "{$_SESSION['adminid']}";
                        $p = base64_encode(json_encode($json));
                        $json["id"] = "0";
                        $p_2 = base64_encode(json_encode($json));
                        ?>

                        <option value="<?php echo $p_2 ?>" <?php if (isset($_POST['p']) && $_POST['p'] == $p_2): ?>selected<?php endif; ?>>Todas</option>

                        <option value="<?php echo $p ?>" <?php if (isset($_POST['p']) && $_POST['p'] == $p): ?>selected<?php endif; ?>><?php echo $_SESSION['loginuser'] ?></option>
                        <?php
                        $arvore = arvoreRevendas2();
                        $arvore_lista = arvoreRevendasLista();
                        listaOptionsRenvendas($arvore[$_SESSION['adminid']], $arvore_lista, isset($_POST['p']) ? $_POST['p'] : "", $_SESSION['_hierarquia']);
                        ?>
                    </select> 
                </div>
                <div class="form-group " style="clear: both">
                    <input type="checkbox" name="ck_busca_login" id="ck_busca_login" <?php if (isset($_POST["ck_busca_login"])): ?>checked<?php endif; ?>/>&nbsp;Busca avançada                                                                
                </div>
                <div class="form-group sel-opc-busca" style="width: 20%; display: none; border: solid 0px red; float: left">
                    <label>Selecione a opção</label>
                    <select class='form-control' name="sel-opc-busca" id="sel-opc-busca" disabled>
                        <option value="0">-- Selecione --</option>
                        <option value="1" <?php if (isset($_POST["sel-opc-busca"]) && $_POST["sel-opc-busca"] == 1): ?>selected<?php endif; ?>>Login</option>
                        <option value="2" <?php if (isset($_POST["sel-opc-busca"]) && $_POST["sel-opc-busca"] == 2): ?>selected<?php endif; ?>>Data Inicio Falha</option>
                        <option value="3" <?php if (isset($_POST["sel-opc-busca"]) && $_POST["sel-opc-busca"] == 3): ?>selected<?php endif; ?>>Data Ultima Falha</option>
                    </select>                                                              
                </div>
                <div class="form-group gp-busca-login" style="display: none;  border: solid 0px green; margin-left: 21%">
                    <label>Login</label>
                    <div style="width: 20%; ">
                        <input type="text" class="form-control" name="busca_login" id="busca_login" disabled value="<?php echo isset($_POST["busca_login"]) ? $_POST["busca_login"] : "" ?>"/>                             
                    </div>                                                                                                            
                </div>
                <div class="form-group gp-busca-datas" style="display: none; margin-left: 21%">

                    <div style="width: 20%;  border: solid 0px red; float: left">
                        <label style="display: inline-block; border: solid 0px red;">Data Inicial</label>
                        <input type="text" class="form-control" name="data_inicial" id="data_inicial" style="display: inline-block" value="<?php echo isset($_POST["data_inicial"]) ? $_POST["data_inicial"] : "" ?>" disabled/>                                     
                    </div>

                    <div style="width: 20%;  border: solid 0px green;margin-left: 21%">
                        <label style="display: inline-block; border: solid 0px red;">Data Final</label>
                        <input type="text" class="form-control" name="data_final" id="data_final" style="display: inline-block" value="<?php echo isset($_POST["data_final"]) ? $_POST["data_final"] : "" ?>" disabled/>                                     
                    </div> 
                </div>
                <div class="form-group" style="clear: both">
                    <button class="btn btn-success">Verificar</button>
                </div>
            </form>
            <p>&nbsp;</p>
            <?php if (isset($dados_falha) && count($dados_falha) > 0): ?>
                <div style="height: 500px; overflow: auto">
                    <table class="table table-bordered table-condensed" style="font-size: 8pt;">
                        <thead>
                            <th>Login:</th>
                            <th>Porta/ Perfil:</th>
                            <th>Inicio Falha</th>
                            <th>Ultima Falha</th>
                            <th>Host/Ip</th>
                            <th>Nº de Erros</th>
                            <th>Informações da Falha</th>
                        </thead>
                        <tbody>
                            <?php foreach ($dados_falha as $falha): ?>
                                <tr>
                                    <td><?php echo $falha["login"]; ?></td>
                                    <td><?php echo $falha["porta_perfil"]; ?></td>
                                    <td><?php echo $falha["inicio_falha"]; ?></td>
                                    <td><?php echo $falha["ultima_falha"]; ?></td>
                                    <td><?php echo $falha["ip"]; ?></td>
                                    <td><?php echo $falha["total_erros"]; ?></td>
                                    <td><?php echo $falha["obs"]; ?></td>
                                </tr>                        
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php endif; ?>
            <?php if (isset($dados_falha) && count($dados_falha) == 0): ?>
                <div style="font-size: 8pt; color: red">
                    Informações não localizadas para este no login, no servidor informado.
                </div>
            <?php endif; ?>
        </div>
        <script>
                $(document).ready(function() {
                    var ck = $("#ck_busca_login").prop("checked");
                    if (ck == true) {
                        $(".sel-opc-busca").css("display", "block");
                        $("#sel-opc-busca").prop("disabled", false);
                    }
                    var opc_busca = $("#sel-opc-busca").val();
                    if (opc_busca == 1) {
                        $("#busca_login").prop("disabled", false);
                        $("#data_inicial").prop("disabled", true);
                        $("#data_final").prop("disabled", true);
                        $(".gp-busca-login").css("display", "block");
                        $(".gp-busca-datas").css("display", "none");
                    }
                    if (opc_busca == 2) {
                        $("#busca_login").prop("disabled", true);
                        $("#data_inicial").prop("disabled", false);
                        $("#data_final").prop("disabled", false);
                        $(".gp-busca-login").css("display", "none");
                        $(".gp-busca-datas").css("display", "block");
                    }
                    if (opc_busca == 3) {
                        $("#busca_login").prop("disabled", true);
                        $("#data_inicial").prop("disabled", false);
                        $("#data_final").prop("disabled", false);
                        $(".gp-busca-login").css("display", "none");
                        $(".gp-busca-datas").css("display", "block");
                    }


                    $("#ck_busca_login").on("click", this, function() {
                        var ck = $(this).prop("checked");
                        if (ck == true) {
                            $(".sel-opc-busca").css("display", "block");
                            $("#sel-opc-busca").prop("disabled", false);
                        }
                        if (ck == false) {
                            $("#sel-opc-busca").prop("disabled", true);
                            $(".sel-opc-busca").css("display", "none");
                            $(".gp-busca-login").css("display", "none");
                            $(".gp-busca-datas").css("display", "none");
                            window.self.location.reload();
                        }
                    });
                    $("#sel-opc-busca").on("change", this, function() {
                        var opc_busca = $(this).val();
                        if (opc_busca == 1) {
                            $("#busca_login").prop("disabled", false);
                            $("#data_inicial").prop("disabled", true);
                            $("#data_final").prop("disabled", true);
                            $(".gp-busca-login").css("display", "block");
                            $(".gp-busca-datas").css("display", "none");
                        }
                        if (opc_busca == 2) {
                            $("#busca_login").prop("disabled", true);
                            $("#data_inicial").prop("disabled", false);
                            $("#data_final").prop("disabled", false);
                            $(".gp-busca-login").css("display", "none");
                            $(".gp-busca-datas").css("display", "block");
                        }
                        if (opc_busca == 3) {
                            $("#busca_login").prop("disabled", true);
                            $("#data_inicial").prop("disabled", false);
                            $("#data_final").prop("disabled", false);
                            $(".gp-busca-login").css("display", "none");
                            $(".gp-busca-datas").css("display", "block");
                        }
                    });
                });

        </script>
        <?php require_once("includes/footer.php"); ?>
    </body>
</html>