Code

Apply follow-up patch for 1797 from mba
[gosa.git] / trunk / gosa-core / include / class_log.inc
1 <?php
2 /*
3  * This code is part of GOsa (http://www.gosa-project.org)
4  * Copyright (C) 2003-2008 GONICUS GmbH
5  *
6  * ID: $$Id$$
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 2 of the License, or
11  * (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program; if not, write to the Free Software
20  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
21  */
23 /*! \brief   The logging base class
24   \author  Fabian Hickert <hickert@gonicus.de>
25   \version 2.6
26   \date    11.04.2007
28   This is the base class for the GOsa logging functionality.
29   All logging should lead to this class. 
30  */
31 class log {
33   var $LOG_TO_MYSQL = FALSE;
34   var $LOG_TO_SYSLOG= FALSE;
35   var $config;
37  /*! \brief logging constructor
39     \param action         One of these values (modify|create|remove|snapshot|copy)
40     \param objecttype     represents the current edited objecttype, like users/user
41     \param object         represents the current edited object dn
42     \param changes_array  An array containing names of all touched attributes
43     \param result         A status message, containing errors or success messages 
45     \sa log()
46    */
47   function log($action,$objecttype,$object,$changes_array = array(),$result = "")
48   {
49     if(!is_array($changes_array)){
50       trigger_error("log(string,string,string,array(),bool). Forth parameter must be an array.");
51       $changes_array = array();
52     }
54     $entry = array(); 
55     if(!session::global_is_set('config')){
56       $entry['user']= "unkown";
57     }else{
59       $this->config = session::global_get('config');
60       $ui           = get_userinfo(); 
61       $entry['user']= @$ui->dn;
62     }
64     /* Create string out of changes */
65     $changes  ="";
66     foreach($changes_array as $str ){
67       $changes .= $str.",";
68     }
69     $changes = preg_replace("/,$/","",$changes );
70     
71     /* Create data object */
72     $entry['timestamp'] = time();
73     $entry['action']    = $action;
74     $entry['objecttype']= $objecttype;
75     $entry['object']    = $object;
76     $entry['changes']   = $changes;
77     $entry['result']    = $result;
79     if(!isset($this->config) || ( $this->config->get_cfg_value("logging") == ""  && empty($entry['user']))){
80       $entry['user']  = "unknown";
81     }
82  
83     /* Check if all given values are valid */
84     $msgs = @log::check($entry);
85     if(count($msgs)){
86       foreach($msgs as $msg){
87         trigger_error("Logging failed, reason was: ".$msg);
88         msg_dialog::display(_("Internal error"), sprintf(_("Logging failed: %s"), $msg), ERROR_DIALOG);
89       }
90       
91     }else{
93       if (isset ($this->config)){
94         if ($this->config->get_cfg_value("logging") == ""){
95           $this->log_into_syslog($entry);
96         }else{
98           /* Start logging for configured methods */
99           if(preg_match("/(^|,)syslog(,|$)/i",$this->config->get_cfg_value("logging"))){
100             $this->log_into_syslog($entry);
101           }
102           if(preg_match("/(^|,)mysql(,|$)/i",$this->config->get_cfg_value("logging"))){
103             $this->log_into_db($entry);
104           }
105         }
106       }
107     }
108   }
111   function check($entry = array())
112   {
113     $msgs = array();
115     if(!isset($entry['action']) || !in_array($entry['action'],array("modify","create","remove","copy","snapshot","view","security","debug"))){
116       $msgs[] = sprintf(_("Invalid option '%s' specified!"), $entry['action']);
117     }
119     if(!isset($entry['objecttype']) || empty($entry['objecttype'])){
120       $msgs[] = _("Specified objectType is empty or invalid!");
121     }
122   
123     return($msgs);
124   }
126    
127   /* This function is used to into the systems syslog */
128   function log_into_syslog($entry)
129   {
130     $str = $entry['user']." ".$entry['action']." ".$entry['object']." from type ".$entry['objecttype']." ".$entry['changes']." : Result was ".$entry['result'];
131     gosa_log($str);
132   }
135   function disable_mysql_log($server,$error)
136   {
137     global $config;
138     msg_dialog::display(_("Error"), $error, ERROR_DIALOG);
139     msg_dialog::display(_("MySQL error"),sprintf(_("Logging to MySQL database will be disabled for server '%s'!"),$server), INFO_DIALOG);
140     unset($config->data['SERVERS']['LOGGING'][$server]) ;
141     $this->config = $config;
142   }
145   /* Log into configured logging databses.*/
146   function log_into_db($entry)
147   {
148     if(isset($this->config->data['SERVERS']['LOGGING'])){
149       $servers = $this->config->data['SERVERS']['LOGGING'];
150     }else{
151       return(FALSE);
152     }
154     /* Log into each configured server 
155      */
156     foreach($servers as $server_name => $server){
158       $error = "";
159    
160       /* Check GosaUnitTag
161        */
162       global $config;
163       $ui = get_userinfo();
164       if (isset($config->current['HONOURUNITTAGS']) &&
165                 preg_match('/true/i', $config->current['HONOURUNITTAGS']) &&
166                 $ui->gosaUnitTag != '' &&
167                 !isset($config->data['SERVERS']['LOGGING'][$server_name]['UNITTAG'])) { 
168         $ldap = $this->config->get_ldap_link() ;
169         $ldap->cd($this->config->current['BASE']);
170         $ldap->search("(&(&(objectClass=gosaLogServer)(gosaUnitTag=$ui->gosaUnitTag)(cn=$server_name)))");
172         if (!$ldap->count()){      
173           /* Remove server from config
174            */
175           unset($config->data['SERVERS']['LOGGING'][$server_name]);  
176           $this->config = $config;
177           continue;
178         } else {
179           /* Add gosaUnitTag to config for future reference
180            */
181           $config->data['SERVERS']['LOGGING'][$server_name]['UNITTAG'] = $ui->gosaUnitTag;
182           $this->config = $config;
183         }
184       }
186       /* Connect to the database 
187        */
188       $con = @mysql_pconnect($server_name,$server['USER'],$server['PWD']);
189       if(!$con){
190         $error = msgPool::dbconnect(_("MySQL logging"),mysql_error());
191         $this->disable_mysql_log($server_name,$error);
192         continue;
193       }
195       /* Check if the database is available 
196        */
197       $db = @mysql_select_db($server['DB'],$con);
198       if(!$db){
199         $error = msgPool::dbselect(_("MySQL logging"),mysql_error());
200         $this->disable_mysql_log($server_name,$error);
201         continue;
202       }
204       /* Check if our current location is already registerd 
205          in this case get its id.
206          If it wasn't registered yet, create it. 
207        */
208       $base = mysql_escape_string($this->config->current['BASE']);
209       $query= "SELECT id FROM gosa_locations WHERE location=\"".$base."\";";
210       $res  = mysql_query($query);  
211       if(!$res){
212         $error = msgPool::dbquery(_("MySQL logging"),mysql_error());
213         $this->disable_mysql_log($server_name,$error);
214         continue;
215       }
217       $location_id = -1;
218       while($attrs = mysql_fetch_assoc($res)){
219         $location_id = $attrs['id'];
220         break;
221       }
223       /* No location found that matches our location.
224          Create it.
225        */
226       if($location_id == -1){
227         $query = "INSERT INTO gosa_locations (location) VALUES ('".$base."');";
228         if(!mysql_query($query,$con)){
229           $error = msgPool::dbquery(_("MySQL logging"),mysql_error());
230           $this->disable_mysql_log($server_name,$error);
231           continue;
232         }
234         /* Try to detect the location again 
235          */ 
236         $query= "SELECT id FROM gosa_locations WHERE location=\"".$base."\";";
237         $res  = mysql_query($query);
238         $location_id = -1;
239         while($attrs = mysql_fetch_assoc($res)){
240           $location_id = $attrs['id'];
241           break;
242         }
243         if($location_id == -1){
244           $error = sprintf(_("Cannot add location to the database!")."<br><br>"._("Error").": %s",mysql_error($con));
245           $this->disable_mysql_log($server_name,$error);
246           continue;
247         }
248       }  
250       /* Create mysql syntax */
251       $query ="INSERT INTO gosa_log 
252         (timestamp,user,action,objecttype,object,changes,result,location_id)
253         VALUES 
254         (
255          \"".mysql_escape_string($entry['timestamp'])."\", 
256          \"".mysql_escape_string($entry['user'])."\", 
257          \"".mysql_escape_string($entry['action'])."\", 
258          \"".mysql_escape_string($entry['objecttype'])."\", 
259          \"".mysql_escape_string($entry['object'])."\", 
260          \"".mysql_escape_string($entry['changes'])."\", 
261          \"".mysql_escape_string($entry['result'])."\", 
262          \"".mysql_escape_string($location_id)."\" 
263         );
264       ";
265       $res = mysql_query($query,$con);
266       if(!$res){
267         $error = dbquery(_("MySQL logging"), mysql_error());
268         $this->disable_mysql_log($server_name,$error);
269         continue;
270       } 
271       if(is_resource($con)){
272         mysql_close($con);
273       }
274     }
275   }
278 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
279 ?>