Code

daef071be2bcbef11609f523611904fd1c4ee67e
[gosa.git] / gosa-plugins / log / addons / logview / class_gosa_logview.inc
1 <?php
3 class gosa_logview extends plugin
4 {
5   /* Definitions */
6   var $plHeadline= "System logs";
7   var $plDescription= "This does something";
9   /* attribute list for save action */
10   var $attributes     = array();
11   var $objectclasses  = array();
13   var $server         = "";
14   var $action         = "modify";
15   var $time           = 2;
16   var $regex          = "*";
18   var $start  = 0;
19   var $sort   = 1;
21   var $sort_direction = "down";
22   var $fields         = array("action","timestamp","user","objecttype","object","result","repeated");
23   var $range          = 25;
24   var $view_logged    = FALSE;
25   var $location         = "";
26   var $location_id      = -1;
27   var $timezone_offset  = 0;
29   var $uid_map = array();
30   
32   function gosa_logview (&$config, $dn= NULL)
33   {
34     /* Include config object */
35     $this->config= &$config;
36     $this->ui = get_userinfo();
37     $this->location = $this->config->current['BASE'];
39     /* Restore last filter settings */
40     $logview = session::get('logview');
41     foreach(array("action","server","time","regex") as $attr){
42       if(isset($logview['gosa_log'][$attr])){
43         $this->$attr = $logview['gosa_log'][$attr];
44       }
45     }
47     $tz = timezone::get_default_timezone();
48     $this->timezone_offset = $tz['value'] * 60 * 60 ;
50     $ldap = $this->config->get_ldap_link();
51     $ldap->search("(&(objectClass=person)(uid=*))",array("uid","dn"));
52     while($attrs = $ldap->fetch()){
53       $this->uid_map[$attrs['dn']] = $attrs['uid'][0];
54     }
55   }
58   function execute()
59   {
60     /* Call parent execute */
61     plugin::execute();
63     /* Log view */
64     if(!$this->view_logged){
65       $this->view_logged = TRUE;
66       new log("view","gosa_logging/".get_class($this),$this->dn);
67     }
69     /* Time interval */
70     $date_select = array(
71         "0" => _("one hour"), "1" => _("6 hours"),
72         "2" => _("12 hours"), "3" => _("24 hours"),
73         "4" => _("2 days"),   "5" => _("one week"),
74         "6" => _("2 weeks"),  "7" => _("one month"));
77     $time = time();
78     $date_select_ = array(
79         "0" => $time - 3600, 
80         "1" => $time - 21600,
81         "2" => $time - 43200,
82         "3" => $time - 86400,
83         "4" => $time - 172800,
84         "5" => $time - 604800,
85         "6" => $time - 1209600,
86         "7" => $time - 2419200);
88     $smarty= get_smarty();
89     $smarty->assign("search_result", "");
90     $smarty->assign("plug", "?plug=".validate($_GET['plug']));
91     $smarty->assign("search_image", get_template_path('images/search.png'));
92     $smarty->assign("time_image", get_template_path('images/time.png'));
93     $smarty->assign("server_image", get_template_path('images/server.png'));
94     $smarty->assign("log_image", get_template_path('images/log_warning.png'));
95     $smarty->assign("ruleset_image", get_template_path('images/lists/edit.png'));
96     $smarty->assign("launchimage", get_template_path('images/launch.png'));
97     $smarty->assign("date_select", $date_select);
98     $smarty->assign("actions", array());
99     $smarty->assign("direction", "up");
100     $smarty->assign("mode0", "");
101     $smarty->assign("mode1", "");
102     $smarty->assign("mode2", "");
103     $smarty->assign("mode3", "");
104     $smarty->assign("mode4", "");
105     $smarty->assign("mode5", "");
106     $smarty->assign("mode6", "");
108     /* Assign select option content */
109     foreach( array("server", "action", "time", "regex") as $type){
110       $smarty->assign("$type", $this->$type);
111     }
113     /**** 
114      * Check if defined servers 
115      *  and mysql extension 
116      ****/
117     if (!isset($this->config->data['SERVERS']['LOGGING']) || !count($this->config->data['SERVERS']['LOGGING'])){
118       msg_dialog::display(_("Warning"), msgPool::noserver("GOsa log"), WARNING_DIALOG);
119       return ($smarty->fetch (get_template_path('gosa_log_contents.tpl', TRUE)));
120     }
121     
122     if(!is_callable("mysql_connect")){
123       msg_dialog::display(_("Configuration error"), sprintf(_("Missing %s PHP extension!"), "mysql"), WARNING_DIALOG);
124       return ($smarty->fetch (get_template_path('gosa_log_contents.tpl', TRUE)));
125     }
127     /****
128      * Get Configurations 
129      ****/
130     $list_of_servers = $this->config->data['SERVERS']['LOGGING']; 
131     $servers         = array();
132     foreach($list_of_servers as $servername => $data){
133       $servers[$servername] = $servername;
134     }
135     $smarty->assign("servers", $servers);
136     
137     /* Set a default server, if there is currently no valid server selected */
138     if(empty($this->server) || !in_array($this->server,$servers)){
139       $this->server = key($servers);
140     }
141    
142     /**** 
143      * Connect to currently selected server 
144      ****/
145     $cfg = $list_of_servers[$this->server];
146     $link = @mysql_pconnect($this->server, $cfg['USER'], $cfg['PWD']);
147     if ($link === FALSE){
148       msg_dialog::display(_("Error"), msgPool::dbconnect($this->server,@mysql_error(),"GOsa LOG"), ERROR_DIALOG);
149       new log("debug","gosa_logging","dbconnect",array(),@mysql_error());
150       return ($smarty->fetch (get_template_path('gosa_log_contents.tpl', TRUE)));
151     }
153     /* check if log database is available */
154     if (! @mysql_select_db($cfg['DB'])){
155       msg_dialog::display(_("Error"), msgPool::dbselect($cfg['DB'],@mysql_error(), "GOsa LOG"), ERROR_DIALOG);
156       new log("debug","gosa_logging","selectdb",array(),@mysql_error());
157       return ($smarty->fetch (get_template_path('gosa_log_contents.tpl', TRUE)));
158     }
161     /****
162      * Get location_id.
163      ****/
165     if($this->location_id == -1){
166       $actions = array("!ALL" => _("All"));
167       $query = "SELECT id FROM gosa_locations WHERE location='".mysql_escape_string($this->location)."';";
168       $res = @mysql_query($query);
169       if($res){
170         $attrs = @mysql_fetch_assoc($res);
171         if(isset($attrs['id'])){
172           $this->location_id = $attrs['id'];
173         }
174       } 
175     }
176    
177     /****
178      * Get all action types 
179      ****/
181     $actions = array("!ALL" => _("All"));
182     $query = "SELECT distinct(action) FROM gosa_log WHERE location_id='".$this->location_id."'; ";
183     $res = @mysql_query($query);
184     while($attrs = @mysql_fetch_assoc($res)){
185       $actions[$attrs['action']] = $attrs['action'];
186     } 
189     /****
190      * Check Acls 
191      ****/
193     $ui = get_userinfo();
194     $dn = $list_of_servers[$this->server]['DN'];
195     $acls = $ui->get_permissions($dn,"server/gosaLogServer","viewEntries");
196     
197     if(!preg_match("/r/",$acls)){
198       $res = "<tr>
199         <td colspan=".count($this->fields).">
200         "._("You have insufficient permissions to view syslog entries.")."
201         </td>
202         </tr>";
204       /* Show main page */
205       $smarty->assign("range_selector", "");
206       $smarty->assign("search_result", $res);
207       return ($smarty->fetch (get_template_path('gosa_log_contents.tpl', TRUE)));
208     }
210     /* Prepare order setting */
211     if ($this->sort_direction == "down"){
212       $desc= "DESC";
213       $sort_sign = "<img src='images/sort_down.png' alt='\/' class='center' title='down' border=0>";
214     } else {
215       $desc= "";
216       $sort_sign = "<img src='images/sort_up.png' alt='/\' class='center' title='up' border=0>";
217     }
219     /****
220      * Query stuff 
221      ****/
223     /* Check for required tables
224      */
225     $query = "SHOW TABLES;";
226     $res    = @mysql_query($query,$link);
227     $tables = array();
228     while($attrs  = @mysql_fetch_row($res)){
229       $tables[] = $attrs[0];
230     }
231     $error = FALSE;
232     foreach(array("gosa_log","gosa_locations") as $required){
233       if(!in_array($required,$tables)){
234         msg_dialog::display(_("Error"),
235             sprintf(_("Missing logging table (%s.%s) update your GOsa logging database schema."),
236               $cfg['DB'],$required), ERROR_DIALOG);
237         $error = TRUE;
238       }
239     }
240     if(!$error){
242       /* Get start time */
243       $start = $date_select_[$this->time];
245       /* Prepare search filter */
246       $sql_regex =trim(preg_replace("/\*/","%",$this->regex));
247       $sql_regex = "%".trim($sql_regex,"%")."%";
249       /* Create search filter */
250       $query_base= "FROM  gosa_log WHERE timestamp >= $start ";
252       /* Append action filter */
253       if($this->action != "!ALL"){
254         $query_base .=" AND action like '".$this->action."' ";
255       }
257       /* Append search filter */
258       if($sql_regex != "%%"){
259         $query_base .=" AND ( result like '".$sql_regex."' OR user like '".$sql_regex."') ";
260       }
262       /* Appen location */
263       $query_base .= " AND location_id='".$this->location_id."' ";
265       /* Get number of entries */
266       $query= "SELECT COUNT(`user`) ".$query_base.";";
267       $result = mysql_query($query);
268       if(!$result){
269         new log("debug","gosa_logging","",array(),@mysql_error());
270       }
271       $line= mysql_fetch_array($result, MYSQL_ASSOC);
272       $count= $line['COUNT(`user`)'];
273       if ($count > 25){
274         $smarty->assign("range_selector", range_selector($count, $this->start, $this->range,"EntriesPerPage"));
275       } else {
276         $smarty->assign("range_selector", "");
277       }
279       /* Query results that will be displayed */
280       $query= "SELECT * ".$query_base." ORDER BY ".$this->fields[$this->sort]." ".$desc." LIMIT  ".$this->start.",".$this->range.";";
281       @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__, $query, "Database query");
282       $result = @mysql_query($query);
283       if(!$result){
284         msg_dialog::display(_("Error"), msgPool::dbquery("gosa_log",@mysql_error(), "GOsa LOG"), ERROR_DIALOG);
285         new log("debug","gosa_logging","querydb",array(),@mysql_error());
286         return ($smarty->fetch (get_template_path('gosa_log_contents.tpl', TRUE)));
287       }
289       /* Display results */
290       $mod= 0;
292       /* Add entries to result str */
293       $res = "";
294       while ($line = mysql_fetch_array($result, MYSQL_ASSOC)){
296         /* Toggle background color */
297         if ( ($mod++) & 1){
298           $col= "background-color: #ECECEC;";
299         } else {
300           $col= "background-color: #F5F5F5;";
301         }
303         $base = ", ".substr($this->config->current['BASE'],0,5)."...";
305         if(isset($this->uid_map[$line['user']])){
306           $user = $this->uid_map[$line['user']];
307         }else{
308           $user = preg_replace("/,".normalizePreg($this->config->current['BASE'])."/",$base,$line['user']);
309         }
310         $object = preg_replace("/,".normalizePreg($this->config->current['BASE'])."/",$base,$line['object']);
312         $res.=" <tr style=\"$col\">\n";
313         $res.="   <td title='".$line['objecttype']."'>".$line['action']."</td>";
314         $res.="   <td>".date("H:i:s d.m.Y",($line['timestamp'] + $this->timezone_offset))."</td>";
315         $res.="   <td title='".$line['user']."'>".preg_replace("/,/",", ",$user)."</td>"; 
316         $res.="   <td title='".$line['objecttype']."'>".$line['objecttype']."</td>"; 
317         $res.="   <td title='".$line['object']."'>".preg_replace("/,/",", ",$object)."</td>"; 
318         $res.="   <td>".$line['result']."</td>";
319         $res.=" </tr>\n";
320       }
321     }
322     @mysql_close($link);
323     $smarty->assign("mode".$this->sort, $sort_sign);
324     $smarty->assign("search_result", $res);
326     $smarty->assign("regex", $this->regex);
327     $smarty->assign("server",$this->server);
328     $smarty->assign("servers",$servers);
329     $smarty->assign("action",$this->action);
330     $smarty->assign("actions",$actions);
331     $smarty->assign("date_select", $date_select);
333     $smarty->assign("direction", $this->sort_direction);
335     /* Show main page */
336     return ($smarty->fetch (get_template_path('gosa_log_contents.tpl', TRUE)));
337   }
340   function save_object()
341   {
342     if(isset($_POST['gosa_log_contents_posted'])){
344       /* Get submitted range */ 
345       if(isset($_POST['EntriesPerPage'])){
346         if(is_numeric($_POST['EntriesPerPage'])){
347           $this->range = $_POST['EntriesPerPage'];
348         }
349       }
351       /* Get actual select boxe values */
352       $logfilter_changed = FALSE;
353       foreach( array("server", "action","time","regex") as $type){
354         if(isset($_POST[$type])){
355           $this->$type = $_POST[$type];   
356         }
357       }
359       /* Filter regex values */
360       if ($this->regex == ""){
361         $this->regex= '*';
362       } else {
363         $new = preg_replace('/\*\**/', '*', $this->regex);
364         $this->regex= $new;
365       }
367       /* Set start value */
368       if (isset($_GET['start'])){
369         $this->start= (int)$_GET['start'];
370       }
372       /* Reset page number if filter has changed */
373       if ($logfilter_changed > 0){
374         $this->start= 0;
375       }
377       /* Adapt sorting */
378       if (isset($_GET['sort'])){
380         if($_GET['direction'] == "up"){
381           $this->sort_direction = "down";
382         }else{
383           $this->sort_direction = "up";
384         }
386         $this->sort= (int)$_GET['sort'];
387         if ($this->sort < 0 || $this->sort > count($this->fields)){
388           $this->sort= 0;
389         }
390       }
392       /* Save attributes in Sessiob, so we are able to recontruct filter on plugin reload */
393       $logview = session::get('logview');
394       $logview['gosa_log'] = array();
395       foreach(array("action","server","time","regex") as $attr){
396         $logview['gosa_log'][$attr] = $this->$attr;
397       }
398       session::set('logview',$logview);
399     }
400   }
403   /* Return plugin informations for acl handling
404      #FIXME You can only read attributes within this report plugin 
405   static function plInfo()
406   {
407     return (array(
408         "plShortName"   => _("Log view"),
409         "plDescription" => _("Log view addon"),
410         "plSelfModify"  => FALSE,
411         "plDepends"     => array(),
412         "plPriority"    => 0,
413         "plSection"     => array("addon"),
414         "plCategory"    => array("logview" => array("objectClass" => "none", "description" => _("System logs"))),
416         "plProvidedAcls" => array()
417         ));
418   }
419   */
421 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
422 ?>