Code

Backport from trunk
[gosa.git] / gosa-plugins / rsyslog / addons / rsyslog / class_rsyslog.inc
index da20ef51139e69f57acacc39a1c02ec96f813a0d..7c878da801510e502af068e22fda3573e992bb29 100644 (file)
@@ -2,24 +2,34 @@
 
 class rsyslog extends plugin
 {
-  var $plHeadline= "rSyslog";
-  var $plDescription= "View system logs";
+  var $plHeadline= "System logs";
+  var $plDescription= "View recorded systemlogs";
 
   var $servers = array();
   var $selected_server = "";
-  var $selected_host = "";
+  var $selected_host = "all";
+  var $selected_priority = "all";
 
   var $startTime = "";
   var $stopTime  = "";
 
-  var $sort_value  = "FromHost";
+  var $search_for ="";
+
+  var $sort_value  = "DeviceReportedTime";
   var $sort_type  = "DESC";
-  var $limit  = 20;
+  var $limit  = "0";
   var $limits = array(20,50,100,200,500,1000,'-');
   var $page   = 0;
 
   function rsyslog (&$config, $dn= NULL)
   {
+      $this->initTime = microtime(TRUE);
+
+      // Create statistic table entry
+      stats::log('plugin', $class = get_class($this), $category = array($this->acl_category),  $action = 'open',
+              $amount = 1, $duration = (microtime(TRUE) - $this->initTime));
+
+
     $this->config= &$config;
     $this->ui = get_userinfo();
 
@@ -29,15 +39,16 @@ class rsyslog extends plugin
     // Get list of rsyslog servers 
     $ldap = $this->config->get_ldap_link();
     $ldap->cd($this->config->current['BASE']);
-    $ldap->search("objectClass=rSyslogServer",array("cn","rSyslogUser","rSyslogDatabase","rSyslogPassword"));
+    $ldap->search("objectClass=goLogDBServer",array("cn","goLogAdmin","gosaLogDB","goLogPassword"));
     while($attrs = $ldap->fetch()){
       if(empty($this->selected_server)) $this->selected_server = $attrs['cn'][0];
       $s = array('cn' => $attrs['cn'][0], 'dn' => $attrs['dn'], 'Password' => '', 'status' => 'ok');
-      $s['User'] = $attrs['rSyslogUser'][0]; 
-      $s['Database'] = $attrs['rSyslogDatabase'][0]; 
+      $s['User'] = $attrs['goLogAdmin'][0]; 
+      $s['Database'] = $attrs['gosaLogDB'][0]; 
       $s['Hosts'] = array();
+      $s['Priorities'] = array();
       $s['ACL'] = "";
-      if(isset($attrs['rSyslogPassword'])) $s['Password'] = $attrs['rSyslogPassword'][0];
+      if(isset($attrs['goLogPassword'])) $s['Password'] = $attrs['goLogPassword'][0];
       $this->servers[$attrs['cn'][0]] = $s;
     }
 
@@ -65,7 +76,7 @@ class rsyslog extends plugin
         $this->servers[$name]['error']  = "";
 
         // Detect ACLs
-        $this->servers[$name]['ACL'] =  $ui->get_permissions($server['dn'], 'server/rsyslog','viewEntries');
+        $this->servers[$name]['ACL'] =  $ui->get_permissions($server['dn'], 'server/rSyslogServer','viewEntries');
 
         // Get list of Hosts using this log server..
         if(preg_match('/r/', $this->servers[$name]['ACL'])){
@@ -79,6 +90,16 @@ class rsyslog extends plugin
             $this->servers[$name]['status'] = "query_failed";
             $this->servers[$name]['error']  = @mysql_error();
           }
+          $query = "SELECT distinct(Priority) FROM SystemEvents ORDER BY Priority;";
+          $res = @mysql_query($query, $link);
+          if($res){
+            while($attrs = @mysql_fetch_assoc($res)){
+              $this->servers[$name]['Priorities'][$attrs['Priority']] = $attrs['Priority'];  
+            }
+          }else{
+            $this->servers[$name]['status'] = "query_failed";
+            $this->servers[$name]['error']  = @mysql_error();
+          }
         }
       }
     }
@@ -86,35 +107,49 @@ class rsyslog extends plugin
 
   function execute()
   {
+    plugin::execute();
+
     $smarty = get_smarty();
-    $smarty->assign("usePrototype", "true");
+
     $ui = get_userinfo();
     
-    if(!isset($this->servers[$this->selected_server]) || !count($this->servers[$this->selected_server]['Hosts'])){
+    if(!isset($this->servers[$this->selected_server]['Hosts']) || !count($this->servers[$this->selected_server]['Hosts'])){
       $hosts = array('-' => _("-"));
     }else{
       $hosts = array('all' => _("All"));
       $hosts = array_merge($hosts,$this->servers[$this->selected_server]['Hosts']);
     }
+    if(!isset($this->servers[$this->selected_server]['Priorities']) || !count($this->servers[$this->selected_server]['Priorities'])){
+      $priorities = array('-' => _("-"));
+    }else{
+      $priorities = array('all' => _("All"));
+      foreach($this->servers[$this->selected_server]['Priorities'] as $id => $name){
+        $priorities[$id] = $this->severity2string($name);
+      }
+    }
 
     $result =$this->get_result();
 
-    $smarty->assign("servers",$this->servers);
-    $smarty->assign("hosts",$hosts);
-    $smarty->assign("selected_server",$this->selected_server);
-    $smarty->assign("selected_host",$this->selected_host);
-    $smarty->assign("startTime",  $this->startTime);
-    $smarty->assign("stopTime",    $this->stopTime);
-    $smarty->assign("sort_type",    $this->sort_type);
-    $smarty->assign("sort_value",   $this->sort_value);
-    $smarty->assign("limits",   $this->limits);
-    $smarty->assign("limit",    $this->limit);
-    $smarty->assign("page",    $this->page);
-    $smarty->assign("plug_id", $_GET['plug']);
-    $smarty->assign("downimg", "<img src='images/lists/sort-down.png' class='center' alt='\\/' border='0'>");
-    $smarty->assign("upimg", "<img src='images/lists/sort-up.png' class='center' alt='\\/' border='0'>");
+    $smarty->assign("servers",          set_post($this->servers));
+    $smarty->assign("hosts",            set_post($hosts));
+    $smarty->assign("priorities",       set_post($priorities));
+    $smarty->assign("selected_server",  set_post($this->selected_server));
+    $smarty->assign("selected_host",    set_post($this->selected_host));
+    $smarty->assign("selected_priority",set_post($this->selected_priority));
+    $smarty->assign("search_for",       set_post($this->search_for));
+    $smarty->assign("startTime",        set_post($this->startTime));
+    $smarty->assign("stopTime",         set_post($this->stopTime));
+    $smarty->assign("sort_type",        set_post($this->sort_type));
+    $smarty->assign("sort_value",       set_post($this->sort_value));
+    $smarty->assign("limits",           set_post($this->limits));
+    $smarty->assign("limit",            set_post($this->limit));
+    $smarty->assign("page",             set_post($this->page));
+    $smarty->assign("plug_id",          set_post($_GET['plug']));
+    $smarty->assign("downimg",  image('images/lists/sort-down.png'));
+    $smarty->assign("upimg",    image('images/lists/sort-up.png'));
     $smarty->assign("result", $result);
-    if($this->limit != '-'){
+    $smarty->assign("matches", sprintf(_("%s entries match the filter"), $result["count"]));
+    if($this->limits[$this->limit] != '-'){
       $smarty->assign("page_sel", range_selector($result['count'],$this->page,$this->limits[$this->limit]));
     }else{
       $smarty->assign("page_sel", "");
@@ -123,6 +158,64 @@ class rsyslog extends plugin
     return($smarty->fetch(get_template_path("rSyslog.tpl", TRUE)));
   }
 
+
+    function logToRss()
+    {
+        $result = array();
+        foreach($this->servers as $name => $server){
+            $link = @mysql_pconnect($server['cn'], $server['User'], $server['Password']);
+            if ($link === FALSE){
+                new log("debug","gosa_logging","dbconnect",array(),@mysql_error());
+                $this->servers[$name]['status'] = "connectfailed";
+                $this->servers[$name]['error']  = @mysql_error();
+            }elseif (! @mysql_select_db($server['Database'])){
+                new log("debug","gosa_logging","selectdb",array(),@mysql_error());
+                $this->servers[$name]['status'] = "dbmissing";
+                $this->servers[$name]['error']  = @mysql_error();
+            }else{
+                $this->servers[$name]['status'] = "ok";
+                $this->servers[$name]['error']  = "";
+            }
+
+            if($link){
+                $query = "SELECT * FROM SystemEvents WHERE Message like '%GOsa%' ORDER BY ID DESC LIMIT 50";
+                $res = mysql_query($query, $link);
+                if($res){
+                    while($attrs = mysql_fetch_assoc($res)){
+                        $result[] = $attrs; 
+                    }
+                }
+            }
+        }
+        $source =
+            '<?xml version="1.0" encoding="utf-8"?>'.
+            ' <rdf:RDF'.
+            '  xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"'.
+            '  xmlns="http://purl.org/rss/1.0/"'.
+            '  xmlns:dc="http://purl.org/dc/elements/1.1/">'.
+            ' <channel rdf:about="Gosa">'.
+            '  <description>GOsa</description>'.
+            '  <link>gosa-project.org</link>'.
+            '  <title>GOsa</title>'.
+            '  <dc:date>'.date('d.m.Y H:i:s').'</dc:date>'.
+            ' </channel>';
+
+        foreach($result as $entry){
+
+            $message = $entry['ReceivedAt']." - ".htmlentities($entry['FromHost'].": ".$entry['Message']);
+            $source .= "
+                <item>
+                <title>{$message}</title>
+                <description>{$message}</description>
+                <pubDate>2010-10-25T14:27:39Z</pubDate>
+                </item>";
+        }
+        $source .= "\n</rdf:RDF>";
+        return($source);
+    }
+
+
+
   function get_result()
   {
     $result = array();
@@ -132,14 +225,17 @@ class rsyslog extends plugin
     $result['error']   = "";
 
     // Check whether the selected server exists.
-    if(!isset($this->servers[$this->selected_server])){
-      $this->servers[$name]['status'] = sprintf(_("The selected server '%s' does not exists!"),$this->selected_server);
-      $this->servers[$name]['error']  = $this->servers[$this->selected_server]['error'];
+    if($this->selected_server == "unknown" || !isset($this->servers[$this->selected_server])){
+      $this->servers["unknown"]['status'] = sprintf(_("The selected server '%s' does not exists!"),$this->selected_server);
+      $this->servers["unknown"]["cn"] = "-";
       return($result);
     }
 
     // Check database connectivity    
     $name = $this->selected_server;
+
+
+
     $server = $this->servers[$name];
     $link = @mysql_pconnect($server['cn'], $server['User'], $server['Password']);
     if ($link === FALSE){
@@ -156,15 +252,28 @@ class rsyslog extends plugin
     }
 
     // Get log entries matching the selected filter
-    if(preg_match('/r/', $this->servers[$name]['ACL'])){
+    if(isset($this->servers[$name]['ACL']) && preg_match('/r/', $this->servers[$name]['ACL'])){
 
       $host = "%%";
       if($this->selected_host != "all") $host = $this->selected_host;
+      $prio = "%%";
+      if($this->selected_priority != "all") $prio = $this->selected_priority;
 
-      $filter = "FROM SystemEvents WHERE FromHost like '{$host}' ";
+      $filter = "FROM SystemEvents WHERE 1=1 ";
+      if($host != "%%"){
+        $filter.= " AND FromHost like '".mysql_real_escape_string($host)."' ";
+      }
+      if($prio != "%%"){
+        $filter.= "AND Priority like '".mysql_real_escape_string($prio)."' ";
+      }
       $filter.= "AND DeviceReportedTime >= '".(date("Y.m.d 00:00:00", strtotime($this->startTime)))."' ";     
       $filter.= "AND DeviceReportedTime <= '".(date("Y.m.d 23:59:59", strtotime($this->stopTime)))."' ";     
 
+      if(!empty($this->search_for)){
+          $filter.= "AND ( ( SysLogTag like '%".mysql_real_escape_string($this->search_for).
+              "%' ) OR  ( Message like '%".mysql_real_escape_string($this->search_for)."%' ) ) ";
+      }
+
       // Detect amount of matching entries 
       $query = "SELECT count(ID) as `amount` ".$filter;
       $res = @mysql_query($query, $link);
@@ -179,8 +288,8 @@ class rsyslog extends plugin
 
         if($result['count'] < $this->page) $this->page = 0;
 
-        $filter.= "ORDER BY ".$this->sort_value." ".$this->sort_type." ";
-        if($this->limit != "-"){
+        $filter.= "ORDER BY ".$this->sort_value." ".$this->sort_type.", DeviceReportedTime ".$this->sort_type." ";
+        if($this->limits[$this->limit]!= "-"){
           $filter.= "LIMIT ".$this->page.", ".$this->limits[$this->limit];
         }else{
           $this->page = 0;
@@ -190,6 +299,15 @@ class rsyslog extends plugin
         $res = mysql_query($query, $link);
         if($res){
           while($attrs = @mysql_fetch_assoc($res)){
+            $attrs['DeviceReportedTime']= $this->time2local($attrs['DeviceReportedTime']);
+            $attrs['Facility']= $this->facility2string($attrs['Facility']);
+            $attrs['Priority']= $this->severity2string($attrs['Priority']);
+            $attrs['SysLogTag']= preg_replace("/:$/", "", $attrs['SysLogTag']);
+
+            foreach($attrs as $key => $val){
+              $attrs[$key] = htmlentities($val, ENT_COMPAT, 'UTF-8');
+            }
+
             $result['entries'][] = $attrs;
           }
           $this->servers[$name]['status'] = "ok";
@@ -208,17 +326,44 @@ class rsyslog extends plugin
 
   function save_object()
   {
-    foreach(array("selected_host","selected_server","stopTime","startTime") as $attr){
+    // Get timestamps
+    foreach(array("stopTime","startTime") as $attr){
       if(isset($_POST[$attr])) $this->$attr = get_post($attr);
     }
+    
+    // Get server from post
+    if( isset($_POST['selected_server']) && isset($this->servers[$_POST['selected_server']])){ 
+      $this->selected_server = get_post('selected_server');
+    }
 
+    // Get Host
+    if( isset($this->servers[$this->selected_server]['Hosts']) &&  isset($_POST['selected_host']) && 
+        ($_POST['selected_host'] == "all" || 
+         in_array_strict($_POST['selected_host'],$this->servers[$this->selected_server]['Hosts']))){
+      $this->selected_host = get_post('selected_host');
+    }
+
+    // Get priority from post
+    if( isset($this->servers[$this->selected_server]['Priorities']) &&  isset($_POST['selected_priority']) && 
+        ($_POST['selected_priority'] == "all" || 
+         in_array_strict($_POST['selected_priority'],$this->servers[$this->selected_server]['Priorities']))){
+      $this->selected_priority = get_post('selected_priority');
+    }
+      
+    // Get serach string
+    if(isset($_POST['search_for'])){
+      $this->search_for = trim(get_post('search_for'));
+    } 
+
+    // Get page navigation attributes  
     if(isset($_GET['start'])) $this->page = $_GET['start'];
     if(isset($_POST['limit']) && isset($this->limits[$_POST['limit']])){
-      $this->limit = $_POST['limit'];
+      $this->limit = get_post('limit');
     }
 
-    if(isset($_GET['sort_value']) && in_array($_GET['sort_value'], 
-          array("DeviceReportedTime","FromHost","Facility","Priority","Message"))){
+    // Get sorting attributes 
+    if(isset($_GET['sort_value']) && in_array_strict($_GET['sort_value'], 
+          array("DeviceReportedTime","FromHost","Facility","Priority","Message","SysLogTag"))){
       $sort_value = $_GET['sort_value'];
       if($this->sort_value == $sort_value){
         if($this->sort_type == "ASC"){
@@ -230,6 +375,69 @@ class rsyslog extends plugin
       $this->sort_value=$sort_value; 
     } 
   }
+
+
+  function severity2string($severity)
+  {
+    $map= array( 0 => _("Emergency"),
+                 1 => _("Alert"),
+                 2 => _("Critical"),
+                 3 => _("Error"),
+                 4 => _("Warning"),
+                 5 => _("Notice"),
+                 6 => _("Informational"),
+                 7 => _("Debug") );
+
+    if (isset($map[$severity])) {
+      return $map[$severity];
+    }
+
+    return sprintf(_("Unknown (%s)"), $severity);
+  }
+
+
+  function facility2string($facility)
+  {
+    $map= array( 0 => _("Kernel"),
+                 1 => _("User level"),
+                 2 => _("Mail system"),
+                 3 => _("System daemon"),
+                 4 => _("Security"),
+                 5 => _("Internal"),
+                 6 => _("Printing"),
+                 7 => _("News"),
+                 8 => _("UUCP"),
+                 9 => _("Cron"),
+                10 => _("Security"),
+                11 => _("FTP"),
+                12 => _("NTP"),
+                13 => _("Log audit"),
+                14 => _("Log alert"),
+                15 => _("Clock"),
+                16 => "Local0",
+                17 => "Local1",
+                18 => "Local2",
+                19 => "Local3",
+                20 => "Local4",
+                21 => "Local5",
+                22 => "Local6",
+                23 => "Local7" );
+
+    if (isset($map[$facility])) {
+      return $map[$facility];
+    }
+
+    return sprintf(_("Unknown (%s)"), $facility);
+  }
+
+
+  function time2local($str)
+  {
+    list($date, $time)= explode(" ", $str);
+    list($y, $m, $d)= explode("-", $date);
+    return "$d.$m.$y $time";
+  }
+
 }
 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
 ?>