<?php
function runExternal($cmd,&$code) {
    $descriptorspec = array(
        0 => array("pipe", "r"),  // stdin is a pipe that the child will read from
        1 => array("pipe", "w"),  // stdout is a pipe that the child will write to
        2 => array("pipe", "w") // stderr is a file to write to
    );
    
    $pipes= array();
    $process = proc_open($cmd, $descriptorspec, $pipes);
    
    $output= "";
    
    if (!is_resource($process)) return false;
    
    #close child's input imidiately
    fclose($pipes[0]);
    
    stream_set_blocking($pipes[1],false);
    stream_set_blocking($pipes[2],false);
    
    $todo= array($pipes[1],$pipes[2]);
    
    while( true ) {
        sleep(1);
        $read= array(); 
        if( !feof($pipes[1]) ) $read[]= $pipes[1];
        if( !feof($pipes[2]) ) $read[]= $pipes[2];
        
        if (!$read) break;
        
        $ready= stream_select($read, $write=NULL, $ex= NULL, 2);
        
        if ($ready === false) {
            break; #should never happen - something died
        }
        
        foreach ($read as $r) {
            $s= fread($r,1024);
            $output.= $s;
        }
    }
    
    fclose($pipes[1]);
    fclose($pipes[2]);
    
    $code= proc_close($process);
    
    return $output;
}

$DEBUG=0;
include ("../dyn/session.inc");
set_time_limit(200);
require_once "DB.php";
include ("../dyn/connexion.php");
// * custom *
if(file_exists("../dyn/custom/var.inc")) {
  include("../dyn/custom/var.inc");
} else {
  include("../dyn/var.inc");
}
//*
$db=& DB :: connect($dsn, $db_option);
if (DB :: isError($db)) {
  die($db->getMessage());
}
if(isset($_GET['ajax']))
  $ajax=$_GET['ajax'];
else
  $ajax=0;
if(isset($_GET['index']))
  $index=$_GET['index'];
else
  $index=0;
if(isset($_GET['idstation']))
  $idstation=$_GET['idstation'];
else
  $idstation=0;
if(isset($_GET['validation']))
  $validation=$_GET['validation'];
else
  $validation=0;
if(isset($_POST['user']))
  $user=$_POST['user'];
elseif(isset($_GET['user']))
  $user=$_GET['user'];
else
  $user="";
if(isset($_POST['password']))
  $password=$_POST['password'];
elseif(isset($_GET['password']))
  $password=$_GET['password'];
else
  $password="";
if(isset($_POST['station']))
  $station=$_POST['station'];
elseif(isset($_GET['station']))
  $station=$_GET['station'];
else
  $station="";
if(isset($_POST['datescan']))
  $datescan=$_POST['datescan'];
else
  $datescan=date("Y-m-d");

if ($ajax) {
  if ($index) {  //recherche du nom de station à scanner
    $station=$db->getOne("select nomstationad from stationad where idstationad=$index");
    if (!is_null($station))
      echo $station;
    else
      echo "";
  } else { //peupler textarea du audit.php d'origine
    $rep=shell_exec("cscript audit.vbs $station $user $password");
//    $rep=runExternal ("cscript audit.vbs $station $user $password",$code);
//    sleep(2);
    echo nl2br(utf8_decode($rep/*."<br>Code ".$code*/));
  }
} else {  
  include ("../dyn/connexionAD.php");
  $total=1;
  if ($validation) {  //submit de station,user,password
    if (!$station) { //scan AD demandé ($station="")
      $ldapserver=ldap_connect($domaine);   //extension LDAP necessaire 
      if(!$ldapserver) {
        echo "<br>Active Directory non disponible !";
      } else {
        $bind = ldap_bind($ldapserver,"cn=$user,$dsiuo","$password");
        if(!$bind) {
          echo "<br>Nom ou mot de passe incorrect !";
        } else {
          $result = ldap_search($ldapserver,$computer_base_dn,$computer_filter,$computer_inforequired);
          ldap_sort ($ldapserver, $result, 'name' );
          $info = ldap_get_entries($ldapserver,$result);
          if($info["count"] == 0) {
            $this->msg=$this->msg."<br>Aucune information disponible !";
          } else {
            $sql="TRUNCATE TABLE stationad"; 
            $res = $db->query($sql);
            $sql="TRUNCATE TABLE stationad_seq"; 
            $res = $db->query($sql);
            $total=$info["count"];
            for($i=0;$i<$info["count"];$i++) {
              if (strcmp($db->getOne("select datescan from station where nomstation='".$info[$i]["name"][0]."'"),$datescan)<0 || !$datescan) {
                 if (!$station) $station=$info[0]["name"][$i];
                 $stationadF['idstationad']=$db->nextId("stationad");
                 $stationadF['nomstationad']=$info[$i]["name"][0];
                 $res= $db->autoExecute("stationad",$stationadF,DB_AUTOQUERY_INSERT);
                 if (DB :: isError($res))
                   echo $res->getDebugInfo().' '.$res->getMessage();
                 else {
                   if ($DEBUG == 1)
                     echo "La requête de mise à jour est effectuée.<br>";
                 }
              } else $total=$total-1;
            }
          }
        }
      }
    } else { //scan d'une station ($station<>"")
      $sql="TRUNCATE TABLE stationad"; 
      $res = $db->query($sql);
      $sql="TRUNCATE TABLE stationad_seq"; 
      $res = $db->query($sql);
      $stationadF['idstationad']=$db->nextId("stationad");
      $stationadF['nomstationad']=$station;
      $res= $db->autoExecute("stationad",$stationadF,DB_AUTOQUERY_INSERT);
      if (DB :: isError($res))
        echo $res->getDebugInfo().' '.$res->getMessage();
      else {
        if ($DEBUG == 1)
          echo "La requête de mise à jour est effectuée.<br>";
      }
    }
  } else $user="bureautique";
  //validation=0 si idstation >0
  //validation=1 démarrage du scan de station par bodyload
  if ($idstation) { //scan d'une station demandé depuis tab (validation=0)
    $station=$db->getOne("select nomstation from station where idstation=$idstation");
    $datescan="";
  }
  echo "<html>\n";
  echo "<head>\n";
  include("../dyn/entete.inc");
  echo "</head>\n";
  if ($validation)
    echo "<body onload=\"lancerscan('$station')\">\n";
  else
    echo "<body>\n";
  echo "<form method=\"POST\" action=\"audit.php?validation=1\" name=f1>\n";
  echo "<table border=\"1\" bordercolor=\"#000000\">\n";
  echo "<tr><td>Utilisateur</td><td><INPUT type=text name='user' id='user' value='$user'></td></tr>\n";
  echo "<tr><td>Mot de passe</td><td><INPUT type=password name='password' id='password' value='$password'></td></tr>\n";
  echo "<tr><td>Station à scanner</td><td><input type=text name='station' id='station' value='$station'></td></tr>\n";
  echo "<tr><td>Date de scan &lt; à</td><td><input type=text name='datescan' id='datescan' value='$datescan'></td></tr>\n";
  echo "</table>\n";
  echo "<input type='submit' value='Lancer le scan'><input type='button' value='Relancer' onclick='relancer();'><br>\n";
  echo "<INPUT type=text name='index' id='index' style='width:85px' value=1>/\n"; 
  echo "<INPUT type=text name='total' id='total' style='width:85px' value=$total><br>\n"; 
  echo "<div id='resultat' onpropertychange='scannersuivant()'></div>\n";
  echo "</form>\n";
  ?>
  <script language="javascript">

  function relancer() {
    document.getElementById("resultat").innerHTML="Relance en cours...";
  }

  function lancerscan(station) {
//    document.getElementById("station").value=station;
    scannerstation(station);
  } 

  function scannersuivant() {
    index=document.getElementById("index").value;
    index=parseInt(index)+1;
    document.getElementById("index").value=index;

    if(window.XMLHttpRequest) // Firefox   
        xhr_object = new XMLHttpRequest();   
    else if(window.ActiveXObject) // Internet Explorer   
        xhr_object = new ActiveXObject("Microsoft.XMLHTTP");   
    else { // XMLHttpRequest non supporté par le navigateur   
        alert("Votre navigateur ne supporte pas les objets XMLHTTPRequest...");   
        return;   
    }  

    xhr_object.open("GET", "audit.php?ajax=1&index="+index, true);

    xhr_object.onreadystatechange = function() {   
        if(xhr_object.readyState == 4) {   
//           alert("station---"+xhr_object.responseText+"---");
           document.getElementById('station').value = xhr_object.responseText; 

           station=document.getElementById("station").value;
           if (station) {
             scannerstation(station);
           }
        }
    }
    xhr_object.send(null);  

  }

  function scannerstation(station) {
    user=document.getElementById("user").value;
    password=document.getElementById("password").value;

    if(window.XMLHttpRequest) // Firefox   
        xhr_object = new XMLHttpRequest();   
    else if(window.ActiveXObject) // Internet Explorer   
        xhr_object = new ActiveXObject("Microsoft.XMLHTTP");   
    else { // XMLHttpRequest non supporté par le navigateur   
        alert("Votre navigateur ne supporte pas les objets XMLHTTPRequest...");   
        return;   
    }  

    xhr_object.open("GET", "audit.php?ajax=1&station="+station+"&user="+user+"&password="+password, true);

    xhr_object.onreadystatechange = function() {   
        if(xhr_object.readyState == 4) {   
//           alert(xhr_object.responseText);
           document.getElementById("resultat").innerHTML = xhr_object.responseText;
        }
    } 
    xhr_object.send(null);
  }  

  </script>
  <?php
  echo "</body>\n";
  echo "</html>\n";
}
?>