<?php

//20160610 - NemoFIM - pj/gael/CL

include_once("_nemo.email.cls.php");
//include_once("../_nemo.email.cls.php");

class NemoFIM extends NemoBasic
{
   private $dirRoot = "";


   private static $arrExcludeWildcard = array(
        "."
      , ".."
      , ".sublime-project"
      , ".sublime-workspace"
      , ".bak"
      , ".old"
      , "sess_"
      , ".git");

   public function __construct($dirRoot)
   {
      parent::__construct();
      //$Nemail = new NemoEmail($fields[strEmail] , "" , 0);


      $this->dirRoot = $dirRoot;
   }

   public static function iniSetPermissions(&$result = array(), $dirRoot = null)
   {
      global $DATABASE_SETTINGS, $BR, $SP, $TR, $SystemSettings, $DT;

      //ini
      if($dirRoot == null)
         $dirRoot = $DATABASE_SETTINGS[$_SERVER[SERVER_NAME]]->env_root;

      //get directory into an array
      $arrDir = scandir($dirRoot);
      $dirDisplay = str_replace($DATABASE_SETTINGS[$_SERVER[SERVER_NAME]]->env_root. DIRECTORY_SEPARATOR, "", $dirRoot . DIRECTORY_SEPARATOR);

      //go
      foreach ($arrDir as $i => $value)
      {//vd($i); vd($value);

         if (!in_array($value, self::$arrExcludeWildcard))
         {
            //vd($BR.$value);
            //if this is a subdirectory, check the permissions are 755 then recurrsively call this function again
            if (is_dir($dirRoot . DIRECTORY_SEPARATOR . $value))
            {
               if(file_exists( $dirRoot . DIRECTORY_SEPARATOR . $value))
               {
                  //Check that dir permission is 0755
                  if(substr(sprintf("%o", fileperms($dirRoot . DIRECTORY_SEPARATOR . $value)), -4) != "0755")
                  {
                     chmod($dirRoot . DIRECTORY_SEPARATOR . $value, 0755);
                  }
               }

               $result[$dirDisplay . $value] = (substr(sprintf("%o", fileperms($dirRoot . DIRECTORY_SEPARATOR . $value)), -4));

               //recursive: run sub directories
               self::iniSetPermissions($result, $dirRoot . DIRECTORY_SEPARATOR . $value);
   //print_rr($result);
   //break;
            }
            else
            {//if this is just a file, check permissions are 644 and save to array
               if(file_exists( $dirRoot . DIRECTORY_SEPARATOR . $value))
               {
                  //Check that File permission is 0655
                  if(substr(sprintf("%o", fileperms($dirRoot . DIRECTORY_SEPARATOR . $value)), -4) != "0644")
                  {
                     chmod($dirRoot . DIRECTORY_SEPARATOR . $value, 0644);
                  }
               }

               $result[$dirDisplay . $value] = (substr(sprintf("%o", fileperms($dirRoot . DIRECTORY_SEPARATOR . $value)), -4));
            }
         }
      }
   //print_rr($result);
      return $result;
   }


   public function Record(&$result = array(), $dirRoot = null)
   {
      global $DATABASE_SETTINGS, $BR, $SP, $TR, $SystemSettings, $DT, $MYSQLI, $xdb;

      //ini
      if($dirRoot == null)
         $dirRoot = $DATABASE_SETTINGS[$_SERVER[SERVER_NAME]]->env_root;

      //get directory into an array
      $arrDir = scandir($dirRoot);
      $dirDisplay = str_replace($DATABASE_SETTINGS[$_SERVER[SERVER_NAME]]->env_root. DIRECTORY_SEPARATOR, "", $dirRoot . DIRECTORY_SEPARATOR);

      //go
      foreach ($arrDir as $i => $value)
      {//vd($i); vd($value);

         if(!in_array($value, self::$arrExcludeWildcard))
         {
            //vd($BR.$value);
            //if this is a subdirectory, check the permissions are 755 then recurrsively call this function again
            if (is_dir($dirRoot . DIRECTORY_SEPARATOR . $value))
            {
               if(file_exists( $dirRoot . DIRECTORY_SEPARATOR . $value))
               {
                  //save
                  $this->Save("Dir", $dirRoot . DIRECTORY_SEPARATOR . $value);
               }
//continue;
               //recursive: run sub directories
               $this->Record($result, $dirRoot . DIRECTORY_SEPARATOR . $value);

   //break;
            }
            else
            {//if this is just a file, check permissions are 644 and save to array
               if(file_exists( $dirRoot . DIRECTORY_SEPARATOR . $value))
               {
                  //save
                  $this->Save("File", $dirRoot . DIRECTORY_SEPARATOR . $value);
               }
            }
         }
      }
   //print_rr($result);
      return $result;
   }

   protected function Save($type, $value)
   {//vd($value);
      global $DATABASE_SETTINGS, $BR, $SP, $TR, $SystemSettings, $DT, $MYSQLI, $xdb;
      //ini
      $env = $DATABASE_SETTINGS[$_SERVER[SERVER_NAME]]->environment;

      $arrValues["dtAudit"] = $DT;
      $arrValues["strType"] = $type;
      $arrValues["strPath"] = str_replace($DATABASE_SETTINGS[$_SERVER[SERVER_NAME]]->env_root, "", realpath($value));
      $arrValues["strOwner"] = strval(fileowner($value));
      $arrValues["strPermission"] = substr(sprintf("%o", fileperms($value)), -4);
      $arrValues["dblSize"] = strval(filesize($value));

      $arrValues["dtModify"] = date("Y-m-d H:i:s", filemtime($value));
      $arrValues["strLastUser"] = $env;

      $arrValues["strHash"] = "";
      switch($type)
      {
         case "Dir":
            $arrValues["strHash"] = sha1($arrValues["strPath"].$arrValues["strOwner"].$arrValues["strPermission"]); //.$arrValues["dblSize"]. $arrValues["dtModify"]
            break;
         case "File":
            $arrValues["strHash"] = sha1(sha1_file(realpath($value)). $arrValues["strOwner"] . $arrValues["strPermission"] . $arrValues["dblSize"] . $arrValues["dtModify"]);
            $arrValues["strExtension"] = pathinfo($value, PATHINFO_EXTENSION);
            break;
      }

//print_rr($arrValues); //die;
      //go
      $adb = new NemoDatabase("sysAudit_$env", null, null, 0);
      $adb->setValues($arrValues);
      $adb->Save(0,0);

   }

   public static function PullData($server_name, $maxAudit=null)
   {
      global $DATABASE_SETTINGS, $BR, $SP, $TR, $SystemSettings, $DT, $MYSQLI, $xdb;

      //ini
      $env = $DATABASE_SETTINGS[$server_name]->environment;

      //get data
      $MYSQLI = mysqli_connect($DATABASE_SETTINGS[$server_name]->hostname
                       , $DATABASE_SETTINGS[$server_name]->username
                       , $DATABASE_SETTINGS[$server_name]->password
                       , $DATABASE_SETTINGS[$server_name]->database);
      if($maxAudit == null)
         $maxAudit = $xdb->getRowSQL("SELECT MAX(dtAudit) AS maxAudit FROM sysAudit_$env")->maxAudit;

      $rst = $xdb->doQuery("SELECT * FROM sysAudit_$env WHERE dtAudit = '$maxAudit' ");
      while($row = $xdb->fetch_array($rst))
      {
         $arrData[] = $row;
      }//print_rr($arrData);

      //save data
      $MYSQLI = mysqli_connect($DATABASE_SETTINGS[$_SERVER[SERVER_NAME]]->hostname
                       , $DATABASE_SETTINGS[$_SERVER[SERVER_NAME]]->username
                       , $DATABASE_SETTINGS[$_SERVER[SERVER_NAME]]->password
                       , $DATABASE_SETTINGS[$_SERVER[SERVER_NAME]]->database);
      if(is_array($arrData)){
         $xdb->doQuery("TRUNCATE TABLE sysAudit_$env;");
      foreach($arrData as $i => $row){

         $adb = new NemoDatabase("sysAudit_$env", null, null, 0);
         $adb->setValues($row);
         $adb->Fields["ID"] = "NULL";
         $adb->Save(0,0);


      }}
   }

   public static function Compare($strPathIgnore=0)
   {
      global $DATABASE_SETTINGS, $BR, $SP, $TR, $SystemSettings, $DT, $MYSQLI, $xdb;
      //ini
      $sysAudit_ENV = "sysAudit_". $DATABASE_SETTINGS[$_SERVER[SERVER_NAME]]->environment;

      //0 - get ENV max AuditDate
      $maxAudit = $xdb->getRowSQL("SELECT MAX(dtAudit) AS maxAudit FROM $sysAudit_ENV")->maxAudit;


      $arrFields = array(
          "strOwner"
         , "strPermission"
         , "dblSize"
         , "dtModify"
         , "strHash");

      $arrIgnorePaths = explode(";", $SystemSettings["FIM_EXCLUDE_PATH_LIKE"]);
      foreach($arrIgnorePaths as $key){
         //print_rr($arrIgnorePaths);
         $excludeMASTER .= " AND sysAudit_master.strPath NOT LIKE '".$key."' ";
         $excludeENV .= " AND $sysAudit_ENV.strPath NOT LIKE '".$key."' ";
      }

   //go
         //1 - get Changes [M==L, W. M.strHash != L.strHash]

         $rst = $xdb->doQuery("
            SELECT sysAudit_master.ID AS 'MASTER_ID', sysAudit_master.dtAudit AS 'MASTER_dtAudit'
            , sysAudit_master.strType AS 'MASTER_strType', sysAudit_master.strPath AS 'MASTER_strPath'
            , sysAudit_master.strExtension AS 'MASTER_strExtension', sysAudit_master.strOwner AS 'MASTER_strOwner'
            , sysAudit_master.strPermission AS 'MASTER_strPermission'
            , sysAudit_master.dblSize AS 'MASTER_dblSize', sysAudit_master.dtModify AS 'MASTER_dtModify'
            , sysAudit_master.strHash AS 'MASTER_strHash'
            , $sysAudit_ENV.ID AS 'LIVE_ID', $sysAudit_ENV.dtAudit AS 'LIVE_dtAudit'
            , $sysAudit_ENV.strType AS 'LIVE_strType'
            , $sysAudit_ENV.strPath AS 'LIVE_strPath'
            , $sysAudit_ENV.strExtension AS 'LIVE_strExtension', $sysAudit_ENV.strOwner AS 'LIVE_strOwner'
            , $sysAudit_ENV.strPermission AS 'LIVE_strPermission'
            , $sysAudit_ENV.dblSize AS 'LIVE_dblSize', $sysAudit_ENV.dtModify AS 'LIVE_dtModify'
            , $sysAudit_ENV.strHash AS 'LIVE_strHash'
            FROM sysAudit_master INNER JOIN $sysAudit_ENV ON (sysAudit_master.strHash <> $sysAudit_ENV.strHash) AND (sysAudit_master.strPath = $sysAudit_ENV.strPath)
            WHERE $sysAudit_ENV.dtAudit ='$maxAudit' AND sysAudit_master.strHash <> 'IGNORE' $excludeMASTER
            ORDER BY MASTER_strPath, LIVE_strPath

           ", 1); //LIMIT 0,100

         $rstSummaryChanges = $xdb->getRowSQL("
            SELECT COUNT(*) AS 'CountChanges', MAX(sysAudit_master.dtAudit) AS 'maxDtChanges'
            , MIN(sysAudit_master.dtAudit) AS 'minDtChanges' , sysAudit_master.strHash, $sysAudit_ENV.strHash
            ,sysAudit_master.strPath, $sysAudit_ENV.strPath
            FROM sysAudit_master INNER JOIN $sysAudit_ENV ON (sysAudit_master.strHash <> $sysAudit_ENV.strHash) AND (sysAudit_master.strPath = $sysAudit_ENV.strPath)
            WHERE $sysAudit_ENV.dtAudit ='$maxAudit' AND sysAudit_master.strHash <> 'IGNORE' $excludeMASTER 

            ",0);

      $arrayChangesID = array();
      $i=0;
      while($row = $xdb->fetch($rst))
      {
         //ini
         $colour = array();
         $blnDisplay = 1;

         $i++;
         $arrayChangesID[$i] = $row->LIVE_ID;

         foreach($arrFields as $key)
         {//1.1 - compare & highlight changes
            $rowMaster = ("MASTER_".$key);
            $rowLive = ("LIVE_".$key);
            $colour[$key] = "black";

            if($row->$rowMaster != $row->$rowLive)
               $colour[$key] = "red";
         }

         if($row->MASTER_strType == "Dir" ){
            $colour[dblSize] = "black";
         }

         $IDChanges[$i] = $row->LIVE_ID;

         $trChanges .=
         "  
            <input id='arrIDChanges[]' type='hidden' name='arrIDChanges[]' value='$row->LIVE_ID' >
            <tr>
               <td rowspan='2' align='left' style='color:".$colour["strType"].";' >$row->MASTER_strType</td>
               <td rowspan='2' align='left' style='color:".$colour["strPath"].";' >$row->MASTER_strPath</td>
               <td rowspan='2' align='left' style='color:".$colour["strExtension"].";' >$row->MASTER_strExtension</td>
               <th align='left'>MASTER</th>
               <td align='left' style='color:".$colour["dtAudit"].";' >$row->MASTER_dtAudit</td>
               <td align='left' style='color:".$colour["strOwner"].";' >$row->MASTER_strOwner</td>
               <td align='left' style='color:".$colour["strPermission"].";' >$row->MASTER_strPermission</td>
               <td align='left' style='color:".$colour["dblSize"].";' >$row->MASTER_dblSize</td>
               <td align='left' style='color:".$colour["dtModify"].";' >$row->MASTER_dtModify</td>
               <td align='left' style='color:".$colour["strHash"].";' >$row->MASTER_strHash</td>
               <td rowspan='2' align='center'>
               <a href='".$SystemSettings[BASE_URL]."/cron.hourly.php?Action=FIM: IGNORE&ID=$row->MASTER_ID&state=CHANGES' target='_blank'>Ignore</a></td>
               <td rowspan='2' align='center'>
               <a href='".$SystemSettings[BASE_URL]."/cron.hourly.php?Action=FIM: UPDATE&ID=$row->LIVE_ID&state=CHANGES' target='_blank' >Update</a></td>
            </tr>
            <tr >
               <th align='left'>QA</th>
               <td align='left' style='color:".$colour["dtAudit"].";' >$row->LIVE_dtAudit</td>
               <td align='left' style='color:".$colour["strOwner"].";' >$row->LIVE_strOwner</td>
               <td align='left' style='color:".$colour["strPermission"].";' >$row->LIVE_strPermission</td>
               <td align='left' style='color:".$colour["dblSize"].";' >$row->LIVE_dblSize</td>
               <td align='left' style='color:".$colour["dtModify"].";' >$row->LIVE_dtModify</td>
               <td align='left' style='color:".$colour["strHash"].";' >$row->LIVE_strHash</td>
            </tr>
         ";
      }

      //ENCODED ARRAY ID TO PASS ON URL FOR EMAIL 
      $arrDataChanges = json_encode($arrayChangesID);


      //2 - get Missing [M=>L, W. L.ID is Null]

      $rst = $xdb->doQuery("
         SELECT sysAudit_master.ID AS 'MASTER_ID', sysAudit_master.dtAudit AS 'MASTER_dtAudit'
            , sysAudit_master.strType AS 'MASTER_strType', sysAudit_master.strPath AS 'MASTER_strPath'
            , sysAudit_master.strExtension AS 'MASTER_strExtension', sysAudit_master.strOwner AS 'MASTER_strOwner'
            , sysAudit_master.strPermission AS 'MASTER_strPermission'
            , sysAudit_master.dblSize AS 'MASTER_dblSize', sysAudit_master.dtModify AS 'MASTER_dtModify'
            , sysAudit_master.strHash AS 'MASTER_strHash'
            , $sysAudit_ENV.ID AS 'LIVE_ID', $sysAudit_ENV.dtAudit AS 'LIVE_dtAudit'
            , $sysAudit_ENV.strType AS 'LIVE_strType', $sysAudit_ENV.strPath AS 'LIVE_strPath'
            , $sysAudit_ENV.strExtension AS 'LIVE_strExtension', $sysAudit_ENV.strOwner AS 'LIVE_strOwner'
            , $sysAudit_ENV.strPermission AS 'LIVE_strPermission'
            , $sysAudit_ENV.dblSize AS 'LIVE_dblSize', $sysAudit_ENV.dtModify AS 'LIVE_dtModify'
            , $sysAudit_ENV.strHash AS 'LIVE_strHash'
            FROM sysAudit_master LEFT JOIN $sysAudit_ENV ON sysAudit_master.strPath = $sysAudit_ENV.strPath
            WHERE $sysAudit_ENV.ID Is Null AND sysAudit_master.strHash <> 'IGNORE' $excludeMASTER
            ORDER BY MASTER_strPath, LIVE_strPath", 1);//LIMIT 0,100

      $rstSummaryMissing = $xdb->getRowSQL("
            SELECT COUNT(*) AS 'CountMissing', MAX(sysAudit_master.dtAudit) AS 'maxDtMissing'
            , MIN(sysAudit_master.dtAudit) AS 'minDtMissing', sysAudit_master.strHash, $sysAudit_ENV.strHash
            ,sysAudit_master.strPath, $sysAudit_ENV.strPath
            FROM sysAudit_master LEFT JOIN $sysAudit_ENV ON sysAudit_master.strPath = $sysAudit_ENV.strPath
            WHERE $sysAudit_ENV.ID Is Null AND sysAudit_master.strHash <> 'IGNORE' $excludeMASTER 

            ",0);

      while($row = $xdb->fetch($rst))
      {
         //display
         $trMissing .= "
         <tr>
            <td rowspan='2' align='left'>".$row->MASTER_strType."</td>
            <td rowspan='2' align='left'>".$row->MASTER_strPath."</td>
            <td rowspan='2' align='left'>".$row->MASTER_strExtension."</td>
            <th align='left'>MASTER</th>
            <td align='left'>".$row->MASTER_dtAudit."</td>
            <td align='left'>".$row->MASTER_strOwner."</td>
            <td align='left'>".$row->MASTER_strPermission."</td>
            <td align='left'>".$row->MASTER_dblSize."</td>
            <td align='left'>".$row->MASTER_dtModify."</td>
            <td align='left' style='color:red;'>".$row->MASTER_strHash."</td>
            <td align='center' rowspan='2'>
            <a href='".$SystemSettings[BASE_URL]."/cron.hourly.php?Action=FIM: IGNORE&ID=$row->MASTER_ID&state=MISSING' target='_blank'>Ignore</a></td>

         </tr>
         <tr>
            <th align='left'>QA</th>
            <td align='left'>$row->LIVE_dtAudit</td>
            <td align='left'>$row->LIVE_strOwner</td>
            <td align='left'>$row->LIVE_strPermission</td>
            <td align='left'>$row->LIVE_dblSize</td>
            <td align='left'>$row->LIVE_dtModify</td>
            <td align='left'>$row->LIVE_strHash</td>
         </tr>";
      }


      //3 - get New     [M<=L, W. M.ID is Null]

      $rst = $xdb->doQuery("
         SELECT sysAudit_master.ID AS 'MASTER_ID', sysAudit_master.dtAudit AS 'MASTER_dtAudit'
         , sysAudit_master.strType AS 'MASTER_strType', sysAudit_master.strPath AS 'MASTER_strPath'
         , sysAudit_master.strExtension AS 'MASTER_strExtension', sysAudit_master.strOwner AS 'MASTER_strOwner'
         , sysAudit_master.strPermission AS 'MASTER_strPermission', sysAudit_master.dblSize AS 'MASTER_dblSize'
         , sysAudit_master.dtModify AS 'MASTER_dtModify', sysAudit_master.strHash AS 'MASTER_strHash'
         , $sysAudit_ENV.ID AS 'LIVE_ID', $sysAudit_ENV.dtAudit AS 'LIVE_dtAudit', $sysAudit_ENV.strType AS 'LIVE_strType'
         , $sysAudit_ENV.strPath AS 'LIVE_strPath', $sysAudit_ENV.strExtension AS 'LIVE_strExtension'
         , $sysAudit_ENV.strOwner AS 'LIVE_strOwner', $sysAudit_ENV.strPermission AS 'LIVE_strPermission'
         , $sysAudit_ENV.dblSize AS 'LIVE_dblSize', $sysAudit_ENV.dtModify AS 'LIVE_dtModify'
         , $sysAudit_ENV.strHash AS 'LIVE_strHash'
         FROM sysAudit_master RIGHT JOIN $sysAudit_ENV ON sysAudit_master.strPath = $sysAudit_ENV.strPath
         WHERE $sysAudit_ENV.dtAudit ='$maxAudit' AND sysAudit_master.ID Is Null $excludeENV
         ORDER BY MASTER_strPath, LIVE_strPath

         ", 1); //LIMIT 0,100

      $rstSummaryNew = $xdb->getRowSQL("
            SELECT COUNT(*) AS 'CountNew', MAX(sysAudit_master.dtAudit) AS 'maxDtNew'
            , MIN(sysAudit_master.dtAudit) AS 'minDtNew', sysAudit_master.strHash, $sysAudit_ENV.strHash
            ,sysAudit_master.strPath, $sysAudit_ENV.strPath
            FROM sysAudit_master RIGHT JOIN $sysAudit_ENV ON sysAudit_master.strPath = $sysAudit_ENV.strPath
            WHERE $sysAudit_ENV.dtAudit ='$maxAudit' AND sysAudit_master.ID Is Null $excludeENV

            ",0);

      $arrayNewID = array();
      $i=0;
      while($row = $xdb->fetch())
      {
         $i++;
         $arrayNewID[$i] = $row->LIVE_ID;
         //output
         $trNew .= "
         <input id='arrIDNew[]' type='hidden' name='arrIDNew[]' value='$row->LIVE_ID' >
         <tr>
            <td rowspan='2' align='left'>$row->LIVE_strType</td>
            <td rowspan='2' align='left'>$row->LIVE_strPath</td>
            <td rowspan='2' align='left'>$row->LIVE_strExtension</td>
            <th align='left'>MASTER</th>
            <td align='left'>$row->MASTER_dtAudit</td>
            <td align='left'>$row->MASTER_strOwner</td>
            <td align='left'>$row->MASTER_strPermission</td>
            <td align='left'>$row->MASTER_dblSize</td>
            <td align='left'>$row->MASTER_dtModify</td>
            <td align='left'>$row->MASTER_strHash</td>
            <td align='center' rowspan='2'>
            <a href='".$SystemSettings[BASE_URL]."/cron.hourly.php?Action=FIM: IGNORE&ID=$row->LIVE_ID&state=NEW' target='_blank'>Ignore</a></td>
            <td align='center' rowspan='2'>
            <a href='".$SystemSettings[BASE_URL]."/cron.hourly.php?Action=FIM: UPDATE&ID=$row->LIVE_ID&state=NEW' target='_blank'>Update</a></td>
         </tr>
         <tr>
            <th align='left'>QA</th>
            <td align='left'>$row->LIVE_dtAudit</td>
            <td align='left'>$row->LIVE_strOwner</td>
            <td align='left'>$row->LIVE_strPermission</td>
            <td align='left'>$row->LIVE_dblSize</td>
            <td align='left'>$row->LIVE_dtModify</td>
            <td align='left' style='color:red;' >$row->LIVE_strHash</td>
         </tr>";
      }

      //ENCODED ARRAY ID TO PASS ON URL FOR EMAIL 
      $arrDataNew = json_encode($arrayNewID);
      
      $thChanges = "
      <thead>
         <tr>
            <td colspan='100%'><h3>CHANGES</h3></td>
            <td colspan='2' >
            <a href='".$SystemSettings[BASE_URL]."/cron.hourly.php?Action=FIM: UPDATE ALL CHANGES&arrDataChanges=$arrDataChanges'>UPDATE ALL</a>
            </td>
         </tr>
         <tr BGCOLOR='#7f8c8d'>
            <th align='left'>Type</th>
            <th align='left'>Path</th>
            <th align='left'>Extension</th>
            <th align='left'>ENV</th>
            <th align='left'>dtAudit</th>
            <th align='left'>strOwner</th>
            <th align='left'>strPermission</th>
            <th align='left'>dblSize</th>
            <th align='left'>dtModify</th>
            <th align='left'>strHash</th>
            <th align='left'>Ignore</th>
            <th align='left'>Update</th>
         </tr>

      </thead>";

      $thMissing = "
        <thead>
            <tr><td colspan='100%'><h3>MISSING</h3></td></tr>
            <tr BGCOLOR='#7f8c8d'>
               <th align='left'>Type</th>
               <th align='left'>Path</th>
               <th align='left'>Extension</th>
               <th align='left'>ENV</th>
               <th align='left'>dtAudit</th>
               <th align='left'>strOwner</th>
               <th align='left'>strPermission</th>
               <th align='left'>dblSize</th>
               <th align='left'>dtModify</th>
               <th align='left'>strHash</th>
               <th align='left'>Ignore</th>
            </tr>

         </thead>";

      $thNew = "
         <thead>
            <tr><td colspan='100%'><h3>NEW</h3></td>
               <td colspan='2' >
                  <a href='".$SystemSettings[BASE_URL]."/cron.hourly.php?Action=FIM: UPDATE ALL NEW&arrDataNew=$arrDataNew'>UPDATE ALL</a>
               </td>
            </tr>
            <tr BGCOLOR='#7f8c8d'>
               <th align='left'>Type</th>
               <th align='left'>Path</th>
               <th align='left'>Extension</th>
               <th align='left'>ENV</th>
               <th align='left'>dtAudit</th>
               <th align='left'>strOwner</th>
               <th align='left'>strPermission</th>
               <th align='left'>dblSize</th>
               <th align='left'>dtModify</th>
               <th align='left'>strHash</th>
               <th align='left'>Ignore</th>
               <th align='left'>Update</th>
            </tr>

         </thead>";

      $thSummary = "
         <thead>
            <tr><td colspan='100%'><h3>FIM: Summary: $DT</h3></td>
            <tr>
               <th align='left'>#</th>
               <th align='left'>No. of files</th>
               <th align='left'>Min Date</th>
               <th align='left'>Max Date</th>
            </tr>
         </thead>
      ";

      $trSummary = 
      "
         <tr>
            <td align='left'>CHANGES</td>
            <td align='center'>$rstSummaryChanges->CountChanges</td>
            <td align='center'>$rstSummaryChanges->minDtChanges</td>
            <td align='center'>$rstSummaryChanges->maxDtChanges</td>
         </tr>
         <tr>
            <td align='left'>MISSING</td>
            <td align='center'>$rstSummaryMissing->CountMissing</td>
            <td align='center'>$rstSummaryMissing->minDtMissing</td>
            <td align='center'>$rstSummaryMissing->maxDtMissing</td>
         </tr>
         <tr>
            <td align='left'>NEW</td>
            <td align='center'>$rstSummaryNew->CountNew</td>
            <td align='center'>$rstSummaryNew->minDtNew</td>
            <td align='center'>$rstSummaryNew->maxDtNew</td>
         </tr>
      ";

   //post
      $strBody .= "
         <form id='frmFim' name='frmFim' method='post' action=''>
            <table class='tblNemoList' border='1' style='-fs-table-paginate: paginate;'>
               $thSummary
               $trSummary
            </table><br>
            <table class='tblNemoList' border='1' cellpadding='3' cellspacing='0' width='100%' style='-fs-table-paginate: paginate;'>
               $thChanges
               $trChanges
               $thMissing
               $trMissing
               $thNew
               $trNew
            </table>
         </form>
      ";
      $strFilename = "FIM_KnowMore_Report_$DT";
      //$strTitle = "<h2>Test 2: SetPermission's funct </h2><br>";

      // header("Pragma: no-cache");
      // header("Expires: 0");
      // header("Content-type: application/x-msdownload");
      // header("Content-Disposition: attachment; filename=". $strFilename .".xls"); //gets set inside the report.rpt.php
      // file_put_contents($strFilename, $strBody);
      // echo $strBody;
      // die;

      // pj@overdrive.co.za,gareth@overdrive.co.za
      $Email = new NemoEmail("gael@overdrive.co.za,pj@overdrive.co.za","FIM: KnowMore $DT");
      $Email->addHeader("FROM", $SystemSettings["SMTP Send As"]);
      $Email->addBody("html",$strBody);
      $Email->Send();

      return $strBody;
   }

   public static function Ignore($ID, $state){
      //ini
      global $DATABASE_SETTINGS, $BR, $SP, $TR, $SystemSettings, $DT, $MYSQLI, $xdb;

      $env = $DATABASE_SETTINGS[$_SERVER[SERVER_NAME]]->environment;

      //process
      switch ($state) {
         case "CHANGES":
         case "MISSING":
            $rst = $xdb->doQuery("UPDATE sysAudit_master SET strHash ='IGNORE' WHERE sysAudit_master.ID = ". $xdb->qs($ID), 1);
            break;
         case "NEW":
            $rst = $xdb->doQuery("
            INSERT INTO sysAudit_master ( dtAudit, strType, strPath, strExtension, strOwner, strPermission , dblSize, strHash, dtModify, strLastUser )
            SELECT NOW(), strType, strPath, strExtension, strOwner, strPermission, dblSize , 'IGNORE', dtModify, strLastUser
            FROM sysAudit_$env
            WHERE ID =". $xdb->qs($ID), 1);
            break;
      }
   }


   public static function Update($ID, $state){
      //ini
      global $DATABASE_SETTINGS, $BR, $SP, $TR, $SystemSettings, $DT, $MYSQLI, $xdb;

      $env = $DATABASE_SETTINGS[$_SERVER[SERVER_NAME]]->environment;

      switch ($state) {
         case "CHANGES":
            $rst = $xdb->doQuery("
            UPDATE sysAudit_master INNER JOIN sysAudit_$env ON sysAudit_master.strPath = sysAudit_$env.strPath
            SET sysAudit_master.dtAudit = Now(), sysAudit_master.strOwner = sysAudit_$env.strOwner
               , sysAudit_master.strPermission = sysAudit_$env.strPermission
               , sysAudit_master.dblSize = sysAudit_$env.dblSize
               , sysAudit_master.strHash = sysAudit_$env.strHash
               , sysAudit_master.dtModify = sysAudit_$env.dtModify
               , sysAudit_master.strLastUser = sysAudit_$env.strLastUser
            WHERE sysAudit_$env.ID=". $xdb->qs($ID), 1);
            break;
         case "MISSING": //n/a
            break;
         case "NEW":
            $rst = $xdb->doQuery("
               INSERT INTO sysAudit_master ( dtAudit, strType, strPath, strExtension, strOwner, strPermission, dblSize, strHash, dtModify, strLastUser, dtLastEdit )
               SELECT sysAudit_$env.dtAudit, sysAudit_$env.strType, sysAudit_$env.strPath
               , sysAudit_$env.strExtension, sysAudit_$env.strOwner, sysAudit_$env.strPermission, sysAudit_$env.dblSize
               , sysAudit_$env.strHash, sysAudit_$env.dtModify, sysAudit_$env.strLastUser, sysAudit_$env.dtLastEdit
               FROM sysAudit_$env
               WHERE sysAudit_$env.ID =". $xdb->qs($ID)." GROUP BY strPath",1);
            break;
      }
   }

   public static function ResetMaster()
   {
      //ini
      global $DATABASE_SETTINGS, $BR, $SP, $TR, $SystemSettings, $DT, $MYSQLI, $xdb;
      $env = $DATABASE_SETTINGS[$_SERVER[SERVER_NAME]]->environment;

      //process
      $rst = $xdb->doQuery("TRUNCATE TABLE sysAudit_master", 1);
      $rst = $xdb->doQuery("INSERT INTO sysAudit_master SELECT * FROM sysAudit_$env WHERE dtAudit = left(NOW(),10)", 1);
   }
}


/*

DROP TABLE IF EXISTS `sysAudit_live`;
CREATE TABLE IF NOT EXISTS `sysAudit_live` (
  `ID` int(11) NOT NULL AUTO_INCREMENT,
  `dtAudit` date NOT NULL,
  `strType` enum('File','Dir') NOT NULL,
  `strPath` varchar(255) NOT NULL,
  `strExtension` varchar(20) DEFAULT NULL,
  `strOwner` varchar(100) NOT NULL DEFAULT '',
  `strPermission` varchar(20) NOT NULL DEFAULT '',
  `dblSize` double NOT NULL DEFAULT '0',
  `strHash` varchar(255) NOT NULL DEFAULT '',
  `dtModify` datetime NOT NULL,
  `strLastUser` varchar(100) NOT NULL DEFAULT 'System',
  `dtLastEdit` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`ID`),
  UNIQUE KEY `UNIQUE` (`strPath`,`dtAudit`),
  KEY `strHash` (`strPath`,`strHash`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
SET FOREIGN_KEY_CHECKS=1;

*/
?>