<?php
/*
 * @version $Id: HEADER 15930 2011-10-30 15:47:55Z tsmr $
 -------------------------------------------------------------------------
 Eventlog plugin for GLPI
 Copyright (C) 2003-2011 by the Eventlog Development Team.

 https://forge.indepnet.net/projects/eventlog
 -------------------------------------------------------------------------

 LICENSE
		
 This file is part of Eventlog.

 Eventlog is free software; you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation; either version 2 of the License, or
 (at your option) any later version.

 Eventlog is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with Eventlog. If not, see <http://www.gnu.org/licenses/>.
 --------------------------------------------------------------------------
 */

if (!defined('GLPI_ROOT')) {
	die("Sorry. You can't access directly to this file");
}

// CLASSES plugin_eventlog
class PluginEventlogEventlog extends CommonDBTM {
   
   public $table = 'events';
  /**
   * Get a connection to the Eventlog server
   * @param $eventlogservers_id the eventlog server id
   * @return the connexion to the eventlog database
   */
   static function getDBEventlog($eventlogservers_id) {
      return new DBeventLog($eventlogservers_id);
   }
  
   /**
   * Check if Eventlog connection is always valid
   * If not, then establish a new connection on the good server
   *
   * @return nothing.
   */
   static function checkConnection($eventlogservers_id) {
      global $DBeventLog;

      //If $DBeventLog is not initialized, or if the connection should be on a different eventlog server
      // --> reinitialize connection to Eventlog server
      if (!$DBeventLog || $eventlogservers_id != $DBeventLog->getServerID()) {
         $DBeventLog = self::getDBEventlog($eventlogservers_id);
      }

      return $DBeventLog->connected;
   }

	function getfromDBEventlog ($ID,$eventlogservers_id) {
		global $DBeventLog;

      self::checkConnection($eventlogservers_id);

		$query = "SELECT *
				FROM `".$this->table."`
				WHERE `id` = '$ID'";
		if ($result = $DBeventLog->query($query)) {
			if ($DBeventLog->numrows($result)==1) {
				$data = $DBeventLog->fetch_array($result);
				foreach ($data as $key => $val)
					$this->fields[$key] = $val;
				return true;
			}
			else
				return false;
		}
		else
			return false;
	}
	
	function canCreate() {
      return plugin_eventlog_haveRight('eventlog', 'w');
   }

   function canView() {
      return plugin_eventlog_haveRight('eventlog', 'r');
   }
  
   function deleteEvent($ID,$eventlogservers_id) {
      global $DBeventLog;

      self::checkConnection($eventlogservers_id);

      $query="DELETE
        FROM `".$this->table."`
        WHERE `id` = '$ID';";
      $result = $DBeventLog->query($query);
   }
  
   function getSearchOptions() {
      global $LANG;

      $tab = array();
    
      $tab['common'] = $LANG['plugin_eventlog']['title'][0];

      $tab[1]['table']=$this->table;
      $tab[1]['field']='date';
      $tab[1]['linkfield']='date';
      $tab[1]['name']=$LANG['plugin_eventlog'][1];
      $tab[1]['meta']=1;

      $tab[2]['table']=$this->table;
      $tab[2]['field']='id';
      $tab[2]['linkfield']='';
      $tab[2]['name']=$LANG['common'][2];
      $tab[2]['meta']=1;

      $tab[3]['table']='glpi_plugin_eventlog_eventlogtypes';
      $tab[3]['field']='name';
      $tab[3]['linkfield']='name';
      $tab[3]['name']=$LANG['plugin_eventlog'][6];
      $tab[3]['meta']=2;

      $tab[4]['table']=$this->table;
      $tab[4]['field']='time';
      $tab[4]['linkfield']='time';
      $tab[4]['name']=$LANG['plugin_eventlog'][2];
      $tab[4]['meta']=1;

      $tab[5]['table']=$this->table;
      $tab[5]['field']='computer';
      $tab[5]['linkfield']='computer';
      $tab[5]['name']=$LANG['plugin_eventlog'][3];
      $tab[5]['meta']=1;

      $tab[6]['table']=$this->table;
      $tab[6]['field']='log';
      $tab[6]['linkfield']='log';
      $tab[6]['name']=$LANG['plugin_eventlog'][4];
      $tab[6]['meta']=0;

      $tab[7]['table']=$this->table;
      $tab[7]['field']='source';
      $tab[7]['linkfield']='source';
      $tab[7]['name']=$LANG['plugin_eventlog'][5];
      $tab[7]['meta']=1;

      $tab[8]['table']=$this->table;
      $tab[8]['field']='eventID';
      $tab[8]['linkfield']='eventID';
      $tab[8]['name']=$LANG['plugin_eventlog'][17];
      $tab[8]['meta']=2;

      $tab[9]['table']=$this->table;
      $tab[9]['field']='user';
      $tab[9]['linkfield']='user';
      $tab[9]['name']=$LANG['plugin_eventlog'][7];
      $tab[9]['meta']=1;

      $tab[10]['table']=$this->table;
      $tab[10]['field']='strings';
      $tab[10]['linkfield']='strings';
      $tab[10]['name']=$LANG['plugin_eventlog'][8];
      $tab[10]['meta']=1;
		
		return $tab;
   }

	function showForm ($ID, $options=array()) {
		global $LANG,$CFG_GLPI;
		
		$rand=mt_rand();
		if (!$this->canView()) return false;
      
      $eventlogservers_id = -1;
      if (isset($options['eventlogservers_id'])) {
         $eventlogservers_id = $options['eventlogservers_id'];
      }
      
		$con_spotted=false;

		if (empty($ID)) {

			if ($this->getEmpty()) $con_spotted = true;
		} else {
			if ($this->getfromDBEventlog($ID,$eventlogservers_id)) $con_spotted = true;
		}

		if ($con_spotted) {
			echo "<form method='post' name=form action='".$CFG_GLPI["root_doc"] ."/plugins/eventlog/front/eventlog.form.php'><div align='center'>";
			echo "<table class='tab_cadre_fixe' cellpadding='2'>";
			echo "<tr><th><div align='left'>";
			echo "<a href='".$_SERVER['HTTP_REFERER']."'>".$LANG['buttons'][13]."</a>";
			echo "</div></th>";

			echo "<th colspan='2'><div align='left'>";
			if (empty($ID)) {
				echo $LANG['common'][2].":";
				$this->getEmpty();
			} else {
				$this->getfromDB($ID);
				echo $LANG['plugin_eventlog']['title'][0]." ID $ID:";
			}

			echo "</div></th></tr>";
			echo "<tr class='tab_bg_1'><td>".$LANG['plugin_eventlog'][1].": </td><td>";
			echo Html::convdate($this->fields["date"]);
			echo "</td></tr>";

			echo "<tr class='tab_bg_1'><td>".$LANG['plugin_eventlog'][2].": </td><td>";
			echo $this->fields["time"];
			echo "</td></tr>";

			echo "<tr class='tab_bg_1'><td>".$LANG['plugin_eventlog'][3].": </td><td>";
			echo $this->fields["computer"];
			echo "</td></tr>";


			echo "<tr class='tab_bg_1'><td>".$LANG['plugin_eventlog'][4].": </td><td>";
			echo  $this->fields["log"];
			echo "</td></tr>";

			echo "<tr class='tab_bg_1'><td>".$LANG['plugin_eventlog'][5].": </td><td>";
			echo $this->fields["source"];
			echo "</td></tr>";

			$search_engines = array("EventID.net"	=> "http://www.eventid.net/display.asp?eventid=".$this->fields["eventID"]."&amp;source=".$this->fields["source"]."",
									"Microsoft" => "http://support.microsoft.com/search/default.aspx?catalog=LCID%3D1033&amp;query=".$this->fields["source"]."+event+id+".$this->fields["eventID"]."",
									"Google" => "http://www.google.com/search?q=".$this->fields["source"]."+event+id+".$this->fields["eventID"].""
							);
			$out="<tr class='tab_bg_1'><td>".$LANG['plugin_eventlog'][17].": </td><td>".$this->fields["eventID"];
			$out.="&nbsp;<div id=\"popUp$rand\" class=\"popUp\"><p class=\"popUpTitle\">".$LANG['plugin_eventlog']['buttons'][4]."</p>";
			foreach($search_engines as $key=>$val) {
				$out.="<a href='".$val."' class=\"menuLink\" onclick=\"popHide()\" target=\"_blank\">".$key."</a>";

			}
			$out.="</div><img src='".$CFG_GLPI["root_doc"]."/pics/aide.png' alt=\"\" onclick=\"popUp(event,'popUp$rand')\">";
			echo $out;

			echo "</td></tr>";
         $type = new PluginEventlogEventlogType();
			echo "<tr class='tab_bg_1'>";
			echo "<td>".$LANG['plugin_eventlog'][6].": </td>";
			echo "<td  bgcolor='".$type->getColor($this->fields["type"])."'>";
			echo $type->getDropdownName($this->fields["type"],$eventlogservers_id);
			echo "</td></tr>";

			echo "<tr class='tab_bg_1'><td>".$LANG['plugin_eventlog'][7].": </td><td>";
			echo $this->fields["user"];
			echo "</td></tr>";

			echo "<tr class='tab_bg_1'><td>".$LANG['plugin_eventlog'][8].": </td><td>";
			echo Toolbox::encodeInUtf8($this->fields["strings"]);
			echo "</td></tr>";

			if (!$ID) {
				echo "</table></div></form>";

			} else {

				echo "<tr>";
				echo "<td class='tab_bg_2 top' colspan='3'><div align='center'>";

				if ($this->canCreate()) {
					echo "<input type='hidden' name='id' value=\"$ID\">";
					echo "<input type='hidden' name='eventlogservers_id' value=\"$eventlogservers_id\">";
					echo "<input type='hidden' name='computer' value='".$this->fields["computer"]."' >";
					echo "<input type='submit' name='delete' value=\"".$LANG['buttons'][6]."\" class='submit'></div>";
				}
				echo "</td>";
				echo "</tr>";

				echo "</table></div>";
				echo "</form>";
			}

		} else {
			echo "<div align='center'><b>".$LANG['plugin_eventlog'][9]."</b></div>";
			return false;
		}
		return true;
	}
	
	function dateIndex($eventlogservers_id,$date,$acked) {
      global $LANG;

      echo "<form name='form' method='get' action=\"event.php\"><div align='center'>";
      echo "<table class='tab_cadre' cellpadding='2'>";
      echo "<tr>";
      echo "<th colspan='9'>";
      echo $LANG['plugin_eventlog'][5];
      echo "</th></tr>";
      echo "<tr class='tab_bg_1'>";
      echo "<td>".$LANG['search'][8].": </td>";
      echo "<td>";
      Html::showDateFormItem("date",$date,true,true);
      echo "</td>";
      echo "<td class='center'>".$LANG['plugin_eventlog'][19]." ";
      Dropdown::showYesNo("acked",$acked);
      echo "</td></tr>";
      echo "<tr>";
      echo "<td class='tab_bg_1' colspan='9'>";

      echo "<div align='center'>";
      echo "<input type='submit' name='update' value=\"".$LANG['buttons'][2]."\" class='submit' >";

      echo "</div></td>";
      echo "</tr>";
      echo "</table></div></form>";

   }
  
   function findDefaultTypes() {
      global $DB;

      $queryBranch='';
      // Recherche les enfants

      $queryChilds= "SELECT `types_id`
            FROM `glpi_plugin_eventlog_defaulttypes`";
      if ($resultChilds = $DB->query($queryChilds)) {
        while ($dataChilds = $DB->fetch_array($resultChilds)) {
          $child=$dataChilds["types_id"];
          $queryBranch .= ",$child";
        }
      }

      return $queryBranch;
   }
  
   function GetIDByName($value) {
      global $DB;
      
      $table = getTableForItemType('Computer');
      $query = "SELECT `id`
        FROM `".$table."`
        WHERE `name` LIKE '%".$value."%'";
      if ($result = $DB->query($query)) {
         $numrows =  $DB->numrows($result);
         while ($data=$DB->fetch_array($result)) {
            return $data["id"];
         }
      }
   }

   function summary($eventlogservers_id,$date,$acked) {
      global $CFG_GLPI, $LANG,$DBeventLog,$DB;
    
      $type = new PluginEventlogEventlogType();
    
      self::checkConnection($eventlogservers_id);
      $logs="";

      $query="SELECT COUNT(`".$this->table."`.`id`) AS total_ID,`computer`,`".$this->table."`.`log`
        FROM `".$this->table."`
        WHERE `date` LIKE '%".$date."%' ";
      $query.= "AND `".$this->table."`.`type` IN (0";
      $query.= $this->findDefaultTypes();
      $query.= ") ";

      $query_log= "SELECT `logs_name`
            FROM `glpi_plugin_eventlog_defaultlogs` ";
      $result_log = $DB->query($query_log);
      if ($DB->numrows($result_log)>0) {
         $query .= " AND (`".$this->table."`.`log` = 'log' ";
         while ($data_log=$DB->fetch_array($result_log)) {
            $logs.=$data_log["logs_name"]." / ";
            $type_where="OR `".$this->table."`.`log` = '".$data_log["logs_name"]."' ";
            $query .= " $type_where ";
         }
         $query .= ") ";
      }
      $logs=substr($logs,0,-2);
      if ($acked!=1) {
         $query .= " AND NOT EXISTS (SELECT *
                    FROM `acks`
                    WHERE `acks`.`computer` = `".$this->table."`.`computer`
                    AND `acks`.`log` = `".$this->table."`.`log`
                    AND `acks`.`source` = `".$this->table."`.`source`
                    AND `acks`.`eventID` = `".$this->table."`.`eventID`) ";
      } else {
         $query .= " AND EXISTS (SELECT *
                    FROM `acks`
                    WHERE `acks`.`computer` = `".$this->table."`.`computer`
                    AND `acks`.`log` = `".$this->table."`.`log`
                    AND `acks`.`source` = `".$this->table."`.`source`
                    AND `acks`.`eventID` = `".$this->table."`.`eventID`) ";

      }
      $query .= " GROUP BY `computer`
          ORDER BY `computer` ASC;";

      $result = $DBeventLog->query($query);

      if ($DBeventLog->numrows($result)!=0) {

         echo "<br><div align='center'>";
         echo "<table align='center' width='80%' >";
         echo "<tr><th colspan='4'>";
         echo $LANG['plugin_eventlog']['title'][1]." ".
            Html::convdate($date)." - ".$LANG['plugin_eventlog']['title'][2]." ";

         $querytype= "SELECT *
          FROM `glpi_plugin_eventlog_defaulttypes` ";
         if ($resulttype = $DB->query($querytype)) {
            while($ligne= $DB->fetch_array($resulttype)) {
               echo " - ".$type->getDropdownName($ligne["types_id"],$eventlogservers_id);
            }
         }

         echo "</th></tr>";
         echo "<tr><td class='top'>";
         echo "<table class='tab_cadre center' width='100%' >";
         echo "<tr><th colspan='2'>";
         echo $LANG['plugin_eventlog'][15]." ".$logs;

         echo "</th></tr>";
         while ($data=$DBeventLog->fetch_array($result)) {

            echo "<tr class='tab_bg_2'>";
            echo "<td class='left'>".$data["computer"]."</td>";
            echo "<td>".$LANG['plugin_eventlog'][12]." : ";
            echo "<a href='".$CFG_GLPI["root_doc"]."/plugins/eventlog/front/event.php?____date_show=".$date."&amp;date=".$date."&amp;computer=".$data["computer"]."&amp;log=".$data["log"]."&amp;acked=".$acked."&amp;update=Valider'>";
            echo $data["total_ID"]." ".$LANG['plugin_eventlog'][13]."</a></td>";
            echo "</tr>";
         }
         echo "</table>";
         echo "</td>";
         echo "</tr>";
         echo "</table>";
         echo "</div><br>";
      }
   }

   function showEvents($eventlogservers_id,$params) {
      global $CFG_GLPI, $LANG,$DB,$DBeventLog;
    
      /*ERROR => 1,
      WARNING => 2,
      INFORMATION => 4,
      ACK => 3,
      AUDIT => 8,
      DUMPERROR => 0,
      EMPTY => 16,
      UNDEF => 1024*/

      self::checkConnection($eventlogservers_id);
      
      // Default values of parameters
      $default_values["start"]=0;
      $default_values["date"]=0;
      $default_values["computer"]=0;
      $default_values["acked"]=0;
      $default_values["target"] = $CFG_GLPI["root_doc"]."/plugins/eventlog/front/event.php";
      
      foreach ($default_values as $key => $val) {
         if (isset($params[$key])) {
            $$key=$params[$key];
         } else {
            $$key=$default_values[$key];
         }
      }
      
      if (!$start) {
         $start = 0;
      }

      $query="SELECT `".$this->table."`.`id` AS id, 
                  `".$this->table."`.`date` AS date, 
                  `".$this->table."`.`time` AS time,
                  `".$this->table."`.`computer` AS computer,
                  `".$this->table."`.`eventID` AS eventID,
                  `".$this->table."`.`log` AS log,
                  `".$this->table."`.`user` AS user,
                  `".$this->table."`.`source` AS source,
                  `".$this->table."`.`log` AS log, 
                  `".$this->table."`.`strings` AS description, 
                  `glpi_plugin_eventlog_eventlogtypes`.`name` AS type, 
                  `glpi_plugin_eventlog_eventlogtypes`.`id` AS type_ID
        FROM `".$this->table."`
        LEFT JOIN `glpi_plugin_eventlog_eventlogtypes` 
        ON (`glpi_plugin_eventlog_eventlogtypes`.`id` = `".$this->table."`.`type`)";
      $query.= " WHERE `computer` LIKE '%".$computer."%'
          AND `date` LIKE '%".$date."%' ";
      $query.= "AND `".$this->table."`.`type` IN (0";
      $query.= $this->findDefaultTypes();
      $query.= ") ";

      $query_log= "SELECT `logs_name`
            FROM `glpi_plugin_eventlog_defaultlogs` ";
      $result_log = $DB->query($query_log);
      if ($DB->numrows($result_log)>0) {
        $query .= " AND (`".$this->table."`.`log` = 'log' ";
         while ($data_log=$DB->fetch_array($result_log)) {
            $type_where="OR `".$this->table."`.`log` = '".$data_log["logs_name"]."' ";
            $query .= " $type_where ";
         }
         $query .= ") ";
      }
      if ($acked!=1) {
         $query .= " AND NOT EXISTS (SELECT *
                    FROM `acks`
                    WHERE `acks`.`computer` = `".$this->table."`.`computer`
                    AND `acks`.`log` = `".$this->table."`.`log`
                    AND `acks`.`source` = `".$this->table."`.`source`
                    AND `acks`.`eventID` = `".$this->table."`.`eventID`) ";
      } else {
         $query .= " AND EXISTS (SELECT *
                    FROM `acks`
                    WHERE `acks`.`computer` = `".$this->table."`.`computer`
                    AND `acks`.`log` = `".$this->table."`.`log`
                    AND `acks`.`source` = `".$this->table."`.`source`
                    AND `acks`.`eventID` = `".$this->table."`.`eventID`) ";

      }
      $query .= " ORDER BY `time` ASC;";

      $result = $DBeventLog->query($query);
      $numrows =  $DBeventLog->numrows($result);

      if ($start<$numrows) {

         // Set display type for export if define
         $output_type=HTML_OUTPUT;
         if (isset($_GET["display_type"]))
            $output_type=$_GET["display_type"];

         $parameters2="acked=$acked&amp;computer=$computer&amp;date=$date";
         $parameters=$parameters2."&amp;start=$start";

        // Pager

        $total=0;

         if ($output_type==HTML_OUTPUT)
            Html::printPager($start,$numrows,$target,$parameters);

         // Define begin and end var for loop
         // Search case
         $begin_display=$start;
         $end_display=$start+$_SESSION["glpilist_limit"];

         // Export All case
         if (isset($_GET['export_all'])) {
            $begin_display=0;
            $end_display=$numrows;
         }

         echo "<br><div align='center'>";
         echo "<table class='tab_cadre' cellpadding='2' cellspacing='2' width='90%'>";
         echo "<tr><th colspan='8'>";
         echo $LANG['plugin_eventlog'][11]." - ".$LANG['plugin_eventlog'][3]. " ".
               $computer." - ".Html::convdate($date);
         echo " - <a href='./eventlog.php?eventlogservers_id=".$eventlogservers_id."&amp;computer=".$computer."&amp;acked=".$acked."'>";
         echo $LANG['plugin_eventlog'][14]."</a></th></tr>";

         $i=$start;
         if (isset($_GET['export_all']))
            $i=0;

         if ($i>0) {
            $DBeventLog->data_seek($result,$i);
         }

         $row_num=1;

         echo "<tr>";
         echo "<th>".$LANG['plugin_eventlog'][1]."</th>";
         echo "<th>".$LANG['plugin_eventlog'][3]."</th>";
         echo "<th>".$LANG['plugin_eventlog'][4]."</th>";
         echo "<th>".$LANG['plugin_eventlog'][5]."</th>";
         echo "<th width='5%'>".$LANG['plugin_eventlog'][17]."</th>";
         echo "<th width='12%'>".$LANG['plugin_eventlog'][7]."</th>";
         echo "<th>".$LANG['plugin_eventlog'][6]."</th>";
         echo "<th>".$LANG['plugin_eventlog'][8]."</th>";
         echo "</tr>";

         while ($i < $numrows && $i < $end_display) {
            $i++;

            $item_num=1;
            $data=$DBeventLog->fetch_array($result);
            $rand=mt_rand();

            if ($acked==1) {
               $query_ack="SELECT `comment`,`eventID`
                  FROM `acks`
                  WHERE `computer` = '".$data["computer"]."'
                  AND `log` = '".$data["log"]."'
                  AND `source` = '".$data["source"]."'
                  AND `eventID` = '".$data["eventID"]."'
                  GROUP BY `eventID`";

               if ($result_ack = $DBeventLog->query($query_ack)) {
                  $data_ack=$DBeventLog->fetch_array($result_ack);

                  if ($data_ack["eventID"]==$data["eventID"])
                     echo $this->displaySearchNewLine(HTML_OUTPUT);
                  else
                     echo "<tr class='tab_bg_2'>";
               }
            } else
               echo "<tr class='tab_bg_2'>";

            $moment= $data["date"]." ".$data["time"];

            echo "<td width='10%'>";
            echo "<div align='center'>";
            echo "<a href=\"".$CFG_GLPI["root_doc"]."/plugins/eventlog/front/eventlog.form.php?id=".$data["id"]."&amp;eventlogservers_id=".$eventlogservers_id."\">";
            echo Html::convdatetime($moment);
            echo "</a>";
            echo "</div>";
            echo "</td>";
            $glpi_computer= $this->GetIDByName($computer);
            echo "<td>";
            echo "<div align='center'>";
            echo "<a href=\"".$CFG_GLPI["root_doc"]."/front/computer.form.php?id=".$glpi_computer."\">";
            echo $data["computer"];
            echo "</a>";
            echo "</div>";
            echo "</td>";
            echo "<td><div align='center'>".$data["log"]."</div></td>";
            echo "<td><div align='center'>".$data["source"]."</div></td>";

            $search_engines = array("EventID.net"	=> "http://www.eventid.net/display.asp?eventid=".$data["eventID"]."&amp;source=".$data["source"]."",
                      "Microsoft" => "http://support.microsoft.com/search/default.aspx?catalog=LCID%3D1033&amp;query=".$data["source"]."+event+id+".$data["eventID"]."",
                      "Google" => "http://www.google.com/search?q=".$data["source"]."+event+id+".$data["eventID"].""
                     );
            $out="<td><div align='center' >".$data["eventID"];
            $out.="&nbsp;<div id=\"popUp$rand\" class=\"popUp\">";
            $out.= "<p class=\"popUpTitle\">".$LANG['plugin_eventlog']['buttons'][4]."</p>";
            foreach($search_engines as $key=>$val) {
               $out.="<a href='".$val."' class=\"menuLink\" onclick=\"popHide()\" target=\"_blank\">".$key."</a>";
            }
            $out.="</div><img src='".$CFG_GLPI["root_doc"]."/pics/aide.png' alt=\"\" onclick=\"popUp(event,'popUp$rand')\">";
            echo $out;

            echo "</div></td>";

            echo "<td><div align='center'>".$data["user"]."</div></td>";
            $type = new PluginEventlogEventlogType();
            echo "<td bgcolor='".$type->getColor($data["type_ID"])."'>";
            echo "<div align='center'>".$data["type"]."</div></td>";
            echo "<td>".nl2br(Toolbox::encodeInUtf8($data["description"]))."</td>";
            echo "</tr>";
         }

        echo "</table>";
        echo "</div>";
        if ($output_type==HTML_OUTPUT) {
            echo "<br>";
            Html::printPager($start,$numrows,$target,$parameters);
         }
      }
   }

   function displaySearchNewLine($type,$odd=false) {
  
      $out="";
      switch ($type) {
         case PDF_OUTPUT_LANDSCAPE : //pdf
         case PDF_OUTPUT_PORTRAIT :
            break;
         case SYLK_OUTPUT : //sylk
  //			$out="\n";
            break;
         case CSV_OUTPUT : //csv
            break;
         default :
            $class=" class='plugin_eventlog_acked' ";
            $out="<tr $class>";
            break;
      }
      return $out;
   }

   function searchForm($params) {
      global $CFG_GLPI, $LANG;
      
      // Default values of parameters
      $default_values["link"]="";
      $default_values["field"]="";
      $default_values["contains"]="";
      $default_values["sort"]="";
      $default_values["is_deleted"]=0;
      $default_values["link2"]="";
      $default_values["contains2"]="";
      $default_values["field2"]="";
      $default_values["itemtype2"]="";
      $default_values["eventlogservers_id"]=0;
      $default_values["computer"]=0;
      $default_values["acked"]=0;
      $default_values["target"] = $this->getFormURL();
      
      foreach ($default_values as $key => $val) {
         if (isset($params[$key])) {
            $$key=$params[$key];
         } else {
            $$key=$default_values[$key];
         }
      }
      
      $option[$this->table.".id"]								= $LANG['common'][2];
      $option[$this->table.".date"]								= $LANG['plugin_eventlog'][1];
      $option[$this->table.".time"]								= $LANG['plugin_eventlog'][2];
      //$option[$this->table.".computer"]						= $LANG['plugin_eventlog'][3];
      $option[$this->table."..log"]								= $LANG['plugin_eventlog'][4];
      $option[$this->table.".source"]							= $LANG['plugin_eventlog'][5];
      $option[$this->table.".eventID"]							= $LANG['plugin_eventlog'][17];
      $option["glpi_plugin_eventlog_eventlogtypes.name"]	   = $LANG['plugin_eventlog'][6];
      $option[$this->table.".user"]								= $LANG['plugin_eventlog'][7];
      $option[$this->table.".strings"]							= $LANG['plugin_eventlog'][8];

      echo "<form method='get' action=\"./eventlog.php\">";
      echo "<div align='center'><table  width='750' class='tab_cadre'>";
      echo "<tr><th colspan='5'><b>".$LANG['search'][0].":</b></th></tr>";
      echo "<tr class='tab_bg_1'>";
      echo "<td class='center'>";
      echo "<input type='text' size='15' name=\"contains\" value=\"". $contains ."\" >";
      echo "&nbsp;";
      echo $LANG['search'][11]."&nbsp;<select name=\"field\" size='1'>";
      echo "<option value='all' ";
      if ($field == "all") echo "selected";
      echo ">".$LANG['common'][66]."</option>";
      reset($option);
      foreach ($option as $key => $val) {
         echo "<option value=\"".$key."\"";
         if ($key == $field) echo "selected";
         echo ">". substr($val, 0, 25) ."</option>\n";
      }
      echo "</select>&nbsp;";
      echo "</td><td>";
      echo $LANG['search'][4];
      echo "&nbsp;<select name='sort' size='1'>";
      reset($option);
      foreach ($option as $key => $val) {
         echo "<option value=\"".$key."\"";
         if ($key == $sort) echo "selected";
         echo ">".$val."</option>\n";
      }
      echo "</select> ";

      echo "<td class='center'>";
      echo "<a href='".$CFG_GLPI["root_doc"]."/plugins/eventlog/front/eventlog.php?reset_search=reset_search&amp;computer=".$computer."&amp;eventlogservers_id=".$eventlogservers_id."' >";
      echo "<img title=\"".$LANG['buttons'][16]."\" alt=\"".$LANG['buttons'][16]."\" src='".$CFG_GLPI["root_doc"]."/pics/reset.png' class='calendrier'>";
      echo "</a>";
      echo "</td>";

      echo "<td width='80' class='tab_bg_2 center'>";
      echo "<input type='hidden'  name='computer' value='".$computer."' >";
      echo "<input type='hidden'  name='acked' value='".$acked."' >";
      echo "<input type='hidden'  name='eventlogservers_id' value='".$eventlogservers_id."' >";
      echo "<input type='submit' value=\"".$LANG['buttons'][0]."\" class='submit'>";
      echo "</td></tr></table></div></form>";

   }

   function showList($params) {
      global $DB,$CFG_GLPI,$LANG,$DBeventLog;
    
      $searchopt=array();
      $searchopt=$this->getSearchOptions();
      
      // Default values of parameters
      $default_values["link"]=array();
      $default_values["field"]=array();
      $default_values["contains"]=array();
      $default_values["sort"]="1";
      $default_values["order"]="ASC";
      $default_values["start"]=0;
      $default_values["is_deleted"]=0;
      $default_values["export_all"]=0;
      $default_values["link2"]="";
      $default_values["contains2"]="";
      $default_values["field2"]="";
      $default_values["itemtype2"]="";
      $default_values["phrasetype"]="contains";
      $default_values["eventlogservers_id"]=0;
      $default_values["computer"]=0;
      $default_values["acked"]=0;
      $default_values["target"] = $CFG_GLPI["root_doc"]."/plugins/eventlog/front/eventlog.php";
      
      foreach ($default_values as $key => $val) {
         if (isset($params[$key])) {
            $$key=$params[$key];
         } else {
            $$key=$default_values[$key];
         }
      }
      
      self::checkConnection($eventlogservers_id);

      if (!$DBeventLog->error) {
         // Build query
         if ($field=="all") {
            $where = " (";
            $fields = $DBeventLog->list_fields($this->table);
            $columns = count($fields);
            $i=0;
            foreach ($fields as $key => $val) {
               if ($i != 0) {
                  $where .= " OR ";
               }
               if ($key == "type") {
                  $where .= "`glpi_plugin_eventlog_eventlogtypes`.`name` LIKE '%".$contains."%'";
               } else {
                  $where .= "`".$this->table."`.`".$key ."` LIKE '%".$contains."%'";
               }
               $i++;
            }
            $where .= ")";
         } else {
            if ($phrasetype == "contains") {
               $where = "($field LIKE '%".$contains."%')";
            } else {
               $where = "($field LIKE '".$contains."')";
            }
         }

         if (!$start) {
            $start = 0;
         }
         if (!$order) {
            $order = "DESC";
         }
         $query = "SELECT `".$this->table."`.`id` AS id,
                      `".$this->table."`.`eventID` AS eventID, 
                      `".$this->table."`.`date` AS date, 
                      `".$this->table."`.`time` AS time, 
                      `".$this->table."`.`computer` AS computer, 
                      `".$this->table."`.`log` AS log, 
                      `".$this->table."`.`source` AS source, 
                      `".$this->table."`.`user` AS user, 
                      `".$this->table."`.`strings` AS description,  ";
         $query.= " `glpi_plugin_eventlog_eventlogtypes`.`name` AS type,
                  `glpi_plugin_eventlog_eventlogtypes`.`id` AS type_ID ";
         //$query.= " acks.computer AS acks_computer ";
         $query.= " FROM `".$this->table."` ";
         $query.= " LEFT JOIN `glpi_plugin_eventlog_eventlogtypes` 
                  ON (`glpi_plugin_eventlog_eventlogtypes`.`id` = `".$this->table."`.`type`)";
         //$query.= " LEFT JOIN acks ON (events.eventID = acks.eventID)";
         $query.= " WHERE ";
         if (!empty($where)) $query .= " $where ";
         if (!empty($computer))
            $query .= " AND `".$this->table."`.`computer` LIKE '%".$computer."%' ";
         else if (isset($_GET["computer"]) && !empty($_GET["computer"]))
            $query .= " AND `".$this->table."`.`computer` LIKE '%".$_GET["computer"]."%' ";
         if ((isset($_GET["acked"]) && $_GET["acked"]!=1) || $acked!=1)
            $query .= " AND NOT EXISTS (SELECT *
                      FROM `acks`
                      WHERE `acks`.`computer` = `".$this->table."`.`computer`
                      AND `acks`.`log` = `".$this->table."`.`log`
                      AND `acks`.`source` = `".$this->table."`.`source`
                      AND `acks`.`eventID` = `".$this->table."`.`eventID`) ";

         $query .= " ORDER BY $sort $order";

         // Get it from database
         if ($result = $DBeventLog->query($query)) {
            $numrows =  $DBeventLog->numrows($result);

            if ($start<$numrows) {			// Pager
               $output_type=HTML_OUTPUT;
               if (isset($_GET["display_type"]))
                  $output_type=$_GET["display_type"];

               // Pager
               $parameters2="field=$field&amp;phrasetype=$phrasetype&amp;contains=$contains&amp;eventlogservers_id=$eventlogservers_id";
               if (!empty($computer) && isset($acked))
                  $parameters=$parameters2."&amp;start=$start&amp;sort=$sort&amp;order=$order&amp;computer=$computer&amp;acked=$acked";
               else
                  $parameters=$parameters2."&amp;start=$start&amp;order=$order";

               if ($output_type==HTML_OUTPUT)
                  Html::printPager($start,$numrows,$target,$parameters,$this->getType());

               // Get the items to display
               $toview=array();
               // Add first element (name)
               array_push($toview,1);
               // Add default items

               $query_display="SELECT *
                        FROM `glpi_displaypreferences`
                        WHERE `itemtype` = '".$this->getType()."'
                        AND `users_id` = '".Session::getLoginUserID()."'
                        AND `num` != '1'
                        ORDER by `rank`";
               $result_display=$DB->query($query_display);
               // GET default serach options
               if ($DB->numrows($result_display)==0) {
                  $query_display="SELECT *
                          FROM `glpi_displaypreferences`
                          WHERE `itemtype` = '".$this->getType()."'
                          AND `users_id` = '0'
                          AND `num` != '1'
                          ORDER by `rank`";
                  $result_display=$DB->query($query_display);
               }

               if ($DB->numrows($result_display)>0) {
                  while ($data_display=$DB->fetch_array($result_display))
                     if (isset($searchopt[$data_display["num"]]))
                        array_push($toview,$data_display["num"]);
               }

               // Clean toview array
               $toview=array_unique($toview);
               $toview_count=count($toview);
               $nbcols=$toview_count;
               //massive action
               $sel="";
               if (isset($_GET["select"])&&$_GET["select"]=="all") $sel="checked";

               if ($this->canCreate() && $output_type==HTML_OUTPUT)
                  echo "<form method='post' name='massiveaction_form' id='massiveaction_form' action=\"../ajax/massiveactionEventlog.php\">";

               // Define begin and end var for loop
               // Search case
               $begin_display=$start;
               $end_display=$start+$_SESSION["glpilist_limit"];

               // Export All case
               if (isset($_GET['export_all'])) {
               $begin_display=0;
               $end_display=$numrows;
               }

               echo Search::showHeader($output_type,$end_display-$start+1,$nbcols,0);
               $header_num=1;
               // Display column Headers for toview items
               echo Search::showNewLine($output_type);

               if ($output_type==HTML_OUTPUT) {// HTML display - massive modif
                  $search_config="";
                  if ($this->canCreate()) {
                     $tmp= " style='cursor:pointer;' onClick=\"window.open('".$CFG_GLPI["root_doc"]."/front/popup.php?popup=search_config&amp;itemtype=".$this->getType()."' ,'glpipopup', 'height=400, width=1000, top=100, left=100, scrollbars=yes' )\"";

                     $search_config= "<img alt='".$LANG['common'][25]."' src='".$CFG_GLPI["root_doc"]."/pics/options_search.png' ";
                     $search_config.=$tmp.">";

                     echo Search::showHeaderItem($output_type,$search_config,$header_num,"",0,$order);
                  }
               }

               for ($i=0;$i<$toview_count;$i++) {
                  $issort=0;
                  $link="";
                  if ($sort==$searchopt[$toview[$i]]["table"].".".$searchopt[$toview[$i]]["field"]) $issort=1;
                  $link=$target."?".$parameters."&amp;order=".($order=="ASC"?"DESC":"ASC")."&amp;sort=".$searchopt[$toview[$i]]["table"].".".$searchopt[$toview[$i]]["field"];
                  echo Search::showHeaderItem($output_type,$searchopt[$toview[$i]]["name"],$header_num,$link,$issort,$order);
               }
               // End Line for column headers
               echo Search::showEndLine($output_type);

               $i=$start;
               if (isset($_GET['export_all']))
                  $i=0;

               if ($i>0) {
                  $DBeventLog->data_seek($result,$i);
               }

               $row_num=1;

               while ($i < $numrows && $i < $end_display) {

                  $item_num=1;
                  $data=$DBeventLog->fetch_array($result);
                  $i++;
                  $row_num++;
                  $del=false;

                  if ((isset($_GET["acked"]) && $_GET["acked"]==1) || $acked==1) {
                     $query_ack="SELECT `comment`,`eventID`
                          FROM `acks`
                          WHERE `computer` = '".$data["computer"]."'
                          AND `log` = '".$data["log"]."'
                          AND `source` = '".$data["source"]."'
                          AND `eventID` = '".$data["eventID"]."'
                          GROUP BY `eventID`";

                     if ($result_ack = $DBeventLog->query($query_ack)) {
                        $data_ack=$DB->fetch_array($result_ack);
                        if ($data_ack["eventID"]==$data["eventID"])
                           echo $this->displaySearchNewLine($output_type,$i%2);
                        else
                           echo Search::showNewLine($output_type,$i%2);
                     }
                  } else
                     echo Search::showNewLine($output_type,$i%2);


                  if ($this->canCreate() && $output_type==HTML_OUTPUT)
                     echo Search::showItem($output_type,"<input type='checkbox' name='item[".$data["id"]."]' value='1' $sel>",$item_num,$row_num,"width='10'");
                  for ($j=0;$j<$toview_count;$j++) {
                     if ($searchopt[$toview[$j]]["table"].".".$searchopt[$toview[$j]]["field"]!="glpi_plugin_eventlog_eventlogtypes.name" && $searchopt[$toview[$j]]["table"].".".$searchopt[$toview[$j]]["field"]!=$this->table.".eventID") {
                        echo Search::showItem($output_type,$this->giveItem($eventlogservers_id,$output_type,$searchopt[$toview[$j]]["table"].".".$searchopt[$toview[$j]]["field"],$data,$j,$searchopt[$toview[$j]]["linkfield"]),$item_num,$row_num);
                     } else if ($searchopt[$toview[$j]]["table"].".".$searchopt[$toview[$j]]["field"]==$this->table.".eventID") {
                        echo Search::showItem($output_type,$this->giveItem($eventlogservers_id,$output_type,$searchopt[$toview[$j]]["table"].".".$searchopt[$toview[$j]]["field"],$data,$j,$searchopt[$toview[$j]]["linkfield"]),$item_num,$row_num,"width='50'");
                     } else {
                        $type = new PluginEventlogEventlogType();
                        echo Search::showItem($output_type,$data["type"],$item_num,$row_num,"bgcolor='".$type->getColor($data["type_ID"])."' align='center' ");
                     }
                  }

                  echo Search::showEndLine($output_type);
               }
               $title="";
               // Create title
               if ($output_type==PDF_OUTPUT_PORTRAIT|| $output_type==PDF_OUTPUT_LANDSCAPE) {
                  $title.=$LANG['plugin_eventlog'][18];
               }

               // Display footer
               echo Search::showFooter($output_type,$title);
               //massive action

               if ($this->canCreate() && $output_type==HTML_OUTPUT) {
                  echo "<div align='center'>";
                  echo "<table width='80%'>";
                  echo "<tr><td>";
                  echo "<img src=\"".$CFG_GLPI["root_doc"]."/pics/arrow-left.png\" alt=''>";
                  echo "</td>";
                  echo "<td class='center'>";
                  echo "<a onclick= \"if ( markCheckboxes('massiveaction_form') ) return false;\" href='#' >";
                  echo $LANG['buttons'][18]."</a></td>";

                  echo "<td>/</td>";
                  echo "<td class='center'>";
                  echo "<a onclick= \"if ( unMarkCheckboxes('massiveaction_form') ) return false;\" href='#'>";
                  echo $LANG['buttons'][19]."</a>";
                  echo "</td><td class='left' width='80%'>";
                  $this->dropdownMassiveAction($data["id"],$eventlogservers_id);
                  echo "</td>";
                  echo "</table>";
                  echo "</div></form>";
               }
               // Pager
               if ($output_type==HTML_OUTPUT)
                  Html::printPager($start,$numrows,$target,$parameters);

            } else {
               echo "<div align='center'><b>".$LANG['plugin_eventlog'][9]."</b></div>";
            }
         }
      } else {
         echo "<div align='center'>";
         echo $LANG['plugin_eventlog']['setup'][1]."</div>";
      }
   }

   function giveItem ($eventlogservers_id,$output_type,$field,$data,$num,$linkfield="") {
      global $CFG_GLPI,$LANG;
    
      $rand=mt_rand();
      switch ($field) {
         case $this->table.".date" :
            $out = "";
            if ($output_type==HTML_OUTPUT)
               $out.= "<a href=\"".$CFG_GLPI["root_doc"]."/plugins/eventlog/front/eventlog.form.php?id=".$data['id']."&amp;eventlogservers_id=".$eventlogservers_id."\">";
            $out.= Html::convdate($data["date"]);
            if ($_SESSION["glpiis_ids_visible"]||empty($data["date"])) $out.= " (".$data["id"].")";
            if ($output_type==HTML_OUTPUT)
               $out.= "</a>";
            return $out;
            break;
         case "glpi_plugin_eventlog_eventlogtypes.name" :
            $out= $data["type"];
            return $out;
            break;
         case $this->table.".time" :
            $out= $data["time"];
            return $out;
            break;
         case $this->table.".eventID" :
            $search_engines = array("EventID.net"	=> "http://www.eventid.net/display.asp?eventid=".$data["eventID"]."&amp;source=".$data["source"]."",
                       "Microsoft" => "http://support.microsoft.com/search/default.aspx?catalog=LCID%3D1033&amp;query=".$data["source"]."+event+id+".$data["eventID"]."",
                       "Google" => "http://www.google.com/search?q=".$data["source"]."+event+id+".$data["eventID"].""
                   );

            $out=$data["eventID"];
            if ($output_type==HTML_OUTPUT) {
               $out.="&nbsp;<div id=\"popUp$rand\" class=\"popUp\"><p class=\"popUpTitle\">".$LANG['plugin_eventlog']['buttons'][4]."</p>";

               foreach($search_engines as $key=>$val) {
                  $out.="<a href='".$val."' class=\"menuLink\" onclick=\"popHide()\" target=\"_blank\">".$key."</a>";

               }
               $out.="</div><img src='".$CFG_GLPI["root_doc"]."/pics/aide.png' alt=\"\" onclick=\"popUp(event,'popUp$rand')\">";
            }
            return $out;
            break;
         case $this->table.".computer" :
            $out= $data["computer"];
            return $out;
            break;
         case $this->table.".log" :
            $out= $data["log"];
            return $out;
            break;
         case $this->table.".source" :
            $out= $data["source"];
            return $out;
            break;
         case $this->table.".user" :
            $out= $data["user"];
            return $out;
            break;
         case $this->table.".strings" :
            $out= nl2br(Toolbox::encodeInUtf8($data["description"]));
            return $out;
            break;
         default:
            return "";
            break;
      }
   }
  
   function dropdownMassiveAction($ID,$eventlogservers_id) {
      global $LANG,$CFG_GLPI;

      echo "<select name=\"massiveaction\" id='massiveaction'>";
      echo "<option value=\"-1\" selected>".Dropdown::EMPTY_VALUE."</option>";
      if ($this->canCreate()) {
         echo "<option value=\"ack\">".$LANG['plugin_eventlog'][21]."</option>";
         echo "<option value=\"desack\">".$LANG['plugin_eventlog'][22]."</option>";
         echo "<option value=\"delete\">".$LANG['buttons'][6]."</option>";
         echo "<option value=\"import\">".$LANG['plugin_eventlog'][10]."</option>";
         echo "<option value=\"kb\">".$LANG['plugin_eventlog'][20]."</option>";
      }
      echo "</select>";

      $params=array('action'=>'__VALUE__',
      'id'=>$ID,
      'eventlogservers_id'=>$eventlogservers_id,
      );

      Ajax::UpdateItemOnSelectEvent("massiveaction","show_massiveaction",$CFG_GLPI["root_doc"]."/plugins/eventlog/ajax/dropdownMassiveActionEventlog.php",$params);

      echo "<span id='show_massiveaction'>&nbsp;</span>\n";
   }
}

?>