<?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_once 'config.php';
require_once 'includes/debug.php';
require_once 'includes/settings.php';
require_once 'includes/logincheck.php';
require_once 'includes/functions.php';

//var_dump($_GET);
//var_dump($_SESSION);
//buscando os perfis
$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;
    }
}
//var_dump($csps);
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&name={$login}";
    // 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();
    }
    $total_retorno = $xml->{"login-failures"}->attributes()->count;
    $dados_falha = array();
    $i = 0;
    foreach ($xml->{"login-failures"}->{"entry"} as $falha) {
        $dados_falha[$i]["login"] = (String) $falha->attributes()->name;
        $dados_falha[$i]["porta_perfil"] = (String) $falha->attributes()->context;
        $dados_falha[$i]["inicio_falha"] = date('d/m/Y H:i:s', strtotime($falha->attributes()->{"first-failure"}));
        $dados_falha[$i]["ultima_falha"] = date('d/m/Y H:i:s', strtotime($falha->attributes()->{"last-failure"}));
        $dados_falha[$i]["ip"] = (String) $falha->attributes()->host;
        $dados_falha[$i]["obs"] = (String) $falha->attributes()->reason;
        $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="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
            <link href="css/main.css" rel="stylesheet" type="text/css" /> 
            <style>
                body{
                    padding: 10px;
                }
            </style>

    </head>
    <body>  
        <h4><?php echo $longtitle; ?></h4>
        <p>Falhas do login: &nbsp;<span class="label label-danger"><strong><?php echo $_GET['login'] ?></strong></span></p>
        <form method="post">
            <div class="form-group" style="width: 40%;">
                <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 echo $dados_serv['desc_serv']; ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="form-group">
                <button class="btn btn-success">Verificar</button>
            </div>
        </form>
        <?php if (isset($dados_falha) && count($dados_falha) > 0): ?>
            <div style="">
                <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>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["obs"]; ?></td>
                            </tr>                        
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        <?php endif; ?>
        <?php if(isset($total_retorno) && $total_retorno == "0"):?>
        <div style="font-size: 8pt; color: red">
            Informações não localizadas para este no login, no servidor informado.
        </div>
        <?php endif;?>

    </body>
</html>

