Passed
Push — master ( a5cb6b...ce1111 )
by Patrick
02:05
created
library/Trapdirector/TrapsProcess/Trap.php 1 patch
Indentation   +967 added lines, -967 removed lines patch added patch discarded remove patch
@@ -16,957 +16,957 @@  discard block
 block discarded – undo
16 16
  */
17 17
 class Trap
18 18
 {
19
-    // Configuration files and dirs
20
-    /** @var string Icinga etc path */
21
-    protected $icingaweb2Etc;
22
-    /** @var string $trapModuleConfig config.ini of module */
23
-    protected $trapModuleConfig;
24
-    /** @var string $icingaweb2Ressources resources.ini of icingaweb2 */
25
-    protected $icingaweb2Ressources;
26
-    // Options from config.ini (default values)
27
-    /** @var string $snmptranslate */
28
-    protected $snmptranslate='/usr/bin/snmptranslate';
29
-    /** @var string $snmptranslate_dirs */
30
-    protected $snmptranslate_dirs='/usr/share/icingaweb2/modules/trapdirector/mibs';
31
-    /** @var string $icinga2cmd */
32
-    protected $icinga2cmd='/var/run/icinga2/cmd/icinga2.cmd';
33
-    /** @var string $dbPrefix */
34
-    protected $dbPrefix='traps_';
35
-    
36
-    // API
37
-    /** @var boolean $apiUse */
38
-    protected $apiUse=false;
39
-    /** @var Icinga2API $icinga2api */
40
-    protected $icinga2api=null;
41
-    /** @var string $apiHostname */
42
-    protected $apiHostname='';
43
-    /** @var integer $apiPort */
44
-    protected $apiPort=0;
45
-    /** @var string $apiUsername */
46
-    protected $apiUsername='';
47
-    /** @var string $apiPassword */
48
-    protected $apiPassword='';
49
-    
50
-    // Logs
51
-    /** @var Logging Logging class. */
52
-    public $logging;    //< Logging class.
53
-    /** @var bool true if log was setup in constructor */
54
-    protected $logSetup;   //< bool true if log was setup in constructor
55
-    
56
-    // Databases
57
-    /** @var Database $trapsDB  Database class*/
58
-    public $trapsDB = null;
59
-    
60
-    // Trap received data
61
-    protected $receivingHost;
62
-    /** @var array	Main trap data (oid, source...) */
63
-    public $trapData=array();
64
-    /** @var array $trapDataExt Additional trap data objects (oid/value).*/
65
-    public $trapDataExt=array(); 
66
-    /** @var int $trapId trap_id after sql insert*/
67
-    public $trapId=null;
68
-    /** @var string $trapAction trap action for final write*/
69
-    public $trapAction=null;
70
-    /** @var boolean $trapToDb log trap to DB */
71
-    protected $trapToDb=true;
72
-    
73
-    /** @var Mib mib class */
74
-    public $mibClass = null;
75
-    
76
-    /** @var Rule rule class */
77
-    public $ruleClass = null;
78
-    
79
-    /** @var Plugins plugins manager **/
80
-    public $pluginClass = null;
81
-    
82
-    function __construct($etcDir='/etc/icingaweb2',$baseLogLevel=null,$baseLogMode='syslog',$baseLogFile='')
83
-    {
84
-        // Paths of ini files
85
-        $this->icingaweb2Etc=$etcDir;
86
-        $this->trapModuleConfig=$this->icingaweb2Etc."/modules/trapdirector/config.ini";
87
-        $this->icingaweb2Ressources=$this->icingaweb2Etc."/resources.ini";
88
-        
89
-        //************* Setup logging
90
-        $this->logging = new Logging();
91
-        if ($baseLogLevel != null)
92
-        {
93
-            $this->logging->setLogging($baseLogLevel, $baseLogMode,$baseLogFile);
94
-            $this->logSetup=true;
95
-        }
96
-        else
97
-        {
98
-            $this->logSetup=false;
99
-        }
100
-        $this->logging->log('Loggin started', INFO);
101
-        
102
-        //*************** Get options from ini files
103
-        if (! is_file($this->trapModuleConfig))
104
-        {
105
-            throw new Exception("Ini file ".$this->trapModuleConfig." does not exists");
106
-        }
107
-        $trapConfig=parse_ini_file($this->trapModuleConfig,true);
108
-        if ($trapConfig == false)
109
-        {
110
-            $this->logging->log("Error reading ini file : ".$this->trapModuleConfig,ERROR,'syslog');
111
-            throw new Exception("Error reading ini file : ".$this->trapModuleConfig);
112
-        }
113
-        $this->getMainOptions($trapConfig); // Get main options from ini file
114
-        
115
-        //*************** Setup database class & get options
116
-        $this->setupDatabase($trapConfig);
117
-        
118
-        $this->getDatabaseOptions(); // Get options in database
119
-        
120
-        //*************** Setup API
121
-        if ($this->apiUse === true) $this->getAPI(); // Setup API
122
-        
123
-        //*************** Setup MIB
124
-        $this->mibClass = new Mib($this->logging,$this->trapsDB,$this->snmptranslate,$this->snmptranslate_dirs); // Create Mib class
125
-        
126
-        //*************** Setup Rule
127
-        $this->ruleClass = new Rule($this->logging); //< Create Rule class
128
-        
129
-        $this->trapData=array(  // TODO : put this in a reset function (DAEMON_MODE)
130
-            'source_ip'	=> 'unknown',
131
-            'source_port'	=> 'unknown',
132
-            'destination_ip'	=> 'unknown',
133
-            'destination_port'	=> 'unknown',
134
-            'trap_oid'	=> 'unknown'
135
-        );
136
-        
137
-        //*************** Setup Plugins
138
-        //Create plugin class. Plugins are not loaded here, but by calling registerAllPlugins
139
-        $this->pluginClass = new Plugins($this);
19
+	// Configuration files and dirs
20
+	/** @var string Icinga etc path */
21
+	protected $icingaweb2Etc;
22
+	/** @var string $trapModuleConfig config.ini of module */
23
+	protected $trapModuleConfig;
24
+	/** @var string $icingaweb2Ressources resources.ini of icingaweb2 */
25
+	protected $icingaweb2Ressources;
26
+	// Options from config.ini (default values)
27
+	/** @var string $snmptranslate */
28
+	protected $snmptranslate='/usr/bin/snmptranslate';
29
+	/** @var string $snmptranslate_dirs */
30
+	protected $snmptranslate_dirs='/usr/share/icingaweb2/modules/trapdirector/mibs';
31
+	/** @var string $icinga2cmd */
32
+	protected $icinga2cmd='/var/run/icinga2/cmd/icinga2.cmd';
33
+	/** @var string $dbPrefix */
34
+	protected $dbPrefix='traps_';
35
+    
36
+	// API
37
+	/** @var boolean $apiUse */
38
+	protected $apiUse=false;
39
+	/** @var Icinga2API $icinga2api */
40
+	protected $icinga2api=null;
41
+	/** @var string $apiHostname */
42
+	protected $apiHostname='';
43
+	/** @var integer $apiPort */
44
+	protected $apiPort=0;
45
+	/** @var string $apiUsername */
46
+	protected $apiUsername='';
47
+	/** @var string $apiPassword */
48
+	protected $apiPassword='';
49
+    
50
+	// Logs
51
+	/** @var Logging Logging class. */
52
+	public $logging;    //< Logging class.
53
+	/** @var bool true if log was setup in constructor */
54
+	protected $logSetup;   //< bool true if log was setup in constructor
55
+    
56
+	// Databases
57
+	/** @var Database $trapsDB  Database class*/
58
+	public $trapsDB = null;
59
+    
60
+	// Trap received data
61
+	protected $receivingHost;
62
+	/** @var array	Main trap data (oid, source...) */
63
+	public $trapData=array();
64
+	/** @var array $trapDataExt Additional trap data objects (oid/value).*/
65
+	public $trapDataExt=array(); 
66
+	/** @var int $trapId trap_id after sql insert*/
67
+	public $trapId=null;
68
+	/** @var string $trapAction trap action for final write*/
69
+	public $trapAction=null;
70
+	/** @var boolean $trapToDb log trap to DB */
71
+	protected $trapToDb=true;
72
+    
73
+	/** @var Mib mib class */
74
+	public $mibClass = null;
75
+    
76
+	/** @var Rule rule class */
77
+	public $ruleClass = null;
78
+    
79
+	/** @var Plugins plugins manager **/
80
+	public $pluginClass = null;
81
+    
82
+	function __construct($etcDir='/etc/icingaweb2',$baseLogLevel=null,$baseLogMode='syslog',$baseLogFile='')
83
+	{
84
+		// Paths of ini files
85
+		$this->icingaweb2Etc=$etcDir;
86
+		$this->trapModuleConfig=$this->icingaweb2Etc."/modules/trapdirector/config.ini";
87
+		$this->icingaweb2Ressources=$this->icingaweb2Etc."/resources.ini";
88
+        
89
+		//************* Setup logging
90
+		$this->logging = new Logging();
91
+		if ($baseLogLevel != null)
92
+		{
93
+			$this->logging->setLogging($baseLogLevel, $baseLogMode,$baseLogFile);
94
+			$this->logSetup=true;
95
+		}
96
+		else
97
+		{
98
+			$this->logSetup=false;
99
+		}
100
+		$this->logging->log('Loggin started', INFO);
101
+        
102
+		//*************** Get options from ini files
103
+		if (! is_file($this->trapModuleConfig))
104
+		{
105
+			throw new Exception("Ini file ".$this->trapModuleConfig." does not exists");
106
+		}
107
+		$trapConfig=parse_ini_file($this->trapModuleConfig,true);
108
+		if ($trapConfig == false)
109
+		{
110
+			$this->logging->log("Error reading ini file : ".$this->trapModuleConfig,ERROR,'syslog');
111
+			throw new Exception("Error reading ini file : ".$this->trapModuleConfig);
112
+		}
113
+		$this->getMainOptions($trapConfig); // Get main options from ini file
114
+        
115
+		//*************** Setup database class & get options
116
+		$this->setupDatabase($trapConfig);
117
+        
118
+		$this->getDatabaseOptions(); // Get options in database
119
+        
120
+		//*************** Setup API
121
+		if ($this->apiUse === true) $this->getAPI(); // Setup API
122
+        
123
+		//*************** Setup MIB
124
+		$this->mibClass = new Mib($this->logging,$this->trapsDB,$this->snmptranslate,$this->snmptranslate_dirs); // Create Mib class
125
+        
126
+		//*************** Setup Rule
127
+		$this->ruleClass = new Rule($this->logging); //< Create Rule class
128
+        
129
+		$this->trapData=array(  // TODO : put this in a reset function (DAEMON_MODE)
130
+			'source_ip'	=> 'unknown',
131
+			'source_port'	=> 'unknown',
132
+			'destination_ip'	=> 'unknown',
133
+			'destination_port'	=> 'unknown',
134
+			'trap_oid'	=> 'unknown'
135
+		);
136
+        
137
+		//*************** Setup Plugins
138
+		//Create plugin class. Plugins are not loaded here, but by calling registerAllPlugins
139
+		$this->pluginClass = new Plugins($this);
140 140
             
141 141
             
142
-    }
143
-    
144
-    /**
145
-     * Get option from array of ini file, send message if empty
146
-     * @param string $option_array Array of ini file
147
-     * @param string $option_category category in ini file
148
-     * @param string $option_name name of option in category
149
-     * @param mixed $option_var variable to fill if found, left untouched if not found
150
-     * @param integer $log_level default 2 (warning)
151
-     * @param string $message warning message if not found
152
-     * @return boolean true if found, or false
153
-     */
154
-    protected function getOptionIfSet($option_array,$option_category,$option_name, &$option_var, $log_level = 2, $message = null)
155
-    {
156
-        if (!isset($option_array[$option_category][$option_name]))
157
-        {
158
-            if ($message === null)
159
-            {
160
-                $message='No ' . $option_name . ' in config file: '. $this->trapModuleConfig;
161
-            }
162
-            $this->logging->log($message,$log_level);
163
-            return false;
164
-        }
165
-        else
166
-        {
167
-            $option_var=$option_array[$option_category][$option_name];
168
-            return true;
169
-        }
170
-    }
171
-    
172
-    /**
173
-     * Get options from ini file
174
-     * @param array $trap_config : ini file array
175
-     */
176
-    protected function getMainOptions($trapConfig)
177
-    {
178
-        
179
-        // Snmptranslate binary path
180
-        $this->getOptionIfSet($trapConfig,'config','snmptranslate', $this->snmptranslate);
181
-        
182
-        // mibs path
183
-        $this->getOptionIfSet($trapConfig,'config','snmptranslate_dirs', $this->snmptranslate_dirs);
184
-        
185
-        // icinga2cmd path
186
-        $this->getOptionIfSet($trapConfig,'config','icingacmd', $this->icinga2cmd);
187
-        
188
-        // table prefix
189
-        $this->getOptionIfSet($trapConfig,'config','database_prefix', $this->dbPrefix);
190
-        
191
-        // API options
192
-        if ($this->getOptionIfSet($trapConfig,'config','icingaAPI_host', $this->apiHostname))
193
-        {
194
-            $this->apiUse=true;
195
-            $this->getOptionIfSet($trapConfig,'config','icingaAPI_port', $this->apiPort);
196
-            $this->getOptionIfSet($trapConfig,'config','icingaAPI_user', $this->apiUsername);
197
-            $this->getOptionIfSet($trapConfig,'config','icingaAPI_password', $this->apiPassword);
198
-        }
199
-    }
200
-    
201
-    /**
202
-     * Create and setup database class for trap & ido (if no api) db
203
-     * @param array $trap_config : ini file array
204
-     */
205
-    protected function setupDatabase($trapConfig)
206
-    {
207
-        // Trap database
208
-        if (!array_key_exists('database',$trapConfig['config']))
209
-        {
210
-            $this->logging->log("No database in config file: ".$this->trapModuleConfig,ERROR,'');
211
-            return;
212
-        }
213
-        $dbTrapName=$trapConfig['config']['database'];
214
-        $this->logging->log("Found database in config file: ".$dbTrapName,INFO );
215
-        
216
-        if ( ($dbConfig=parse_ini_file($this->icingaweb2Ressources,true)) === false)
217
-        {
218
-            $this->logging->log("Error reading ini file : ".$this->icingaweb2Ressources,ERROR,'');
219
-            return;
220
-        }
221
-        if (!array_key_exists($dbTrapName,$dbConfig))
222
-        {
223
-            $this->logging->log("No database '.$dbTrapName.' in config file: ".$this->icingaweb2Ressources,ERROR,'');
224
-            return;
225
-        }
226
-        
227
-        $this->trapsDB = new Database($this->logging,$dbConfig[$dbTrapName],$this->dbPrefix);
228
-        
229
-        if ($this->apiUse === true) return; // In case of API use, no IDO is necessary
230
-        
231
-        // IDO Database
232
-        if (!array_key_exists('IDOdatabase',$trapConfig['config']))
233
-        {
234
-            $this->logging->log("No IDOdatabase in config file: ".$this->trapModuleConfig,ERROR,'');
235
-        }
236
-        $dbIdoName=$trapConfig['config']['IDOdatabase'];
237
-        
238
-        $this->logging->log("Found IDO database in config file: ".$dbIdoName,INFO );
239
-        if (!array_key_exists($dbIdoName,$dbConfig))
240
-        {
241
-            $this->logging->log("No database '.$dbIdoName.' in config file: ".$this->icingaweb2Ressources,ERROR,'');
242
-            return;
243
-        }
244
-        
245
-        $this->trapsDB->setupIDO($dbConfig[$dbIdoName]);
246
-    }
247
-    
248
-    /**
249
-     * Get options in database
250
-     */
251
-    protected function getDatabaseOptions()
252
-    {
253
-        // Database options
254
-        if ($this->logSetup === false) // Only if logging was no setup in constructor
255
-        {
256
-            $this->getDBConfigIfSet('log_level',$this->logging->debugLevel);
257
-            $this->getDBConfigIfSet('log_destination',$this->logging->outputMode);
258
-            $this->getDBConfigIfSet('log_file',$this->logging->outputFile);
259
-        }
260
-    }
261
-    
262
-    /** Set $variable to value if $element found in database config table
263
-     * @param string $element
264
-     * @param string $variable
265
-     */
266
-    protected function getDBConfigIfSet($element,&$variable)
267
-    {
268
-        $value=$this->getDBConfig($element);
269
-        if ($value != null) $variable=$value;
270
-    }
271
-    
272
-    /**
273
-     *   Get data from db_config
274
-     *	@param $element string name of param
275
-     *	@return mixed : value (or null)
276
-     */
277
-    protected function getDBConfig($element)  // TODO : put this in DB class
278
-    {
279
-        $db_conn=$this->trapsDB->db_connect_trap();
280
-        $sql='SELECT value from '.$this->dbPrefix.'db_config WHERE ( name=\''.$element.'\' )';
281
-        if (($ret_code=$db_conn->query($sql)) === false) {
282
-            $this->logging->log('No result in query : ' . $sql,WARN,'');
283
-            return null;
284
-        }
285
-        $value=$ret_code->fetch();
286
-        if ($value != null && isset($value['value']))
287
-        {
288
-            return $value['value'];
289
-        }
290
-        return null;
291
-    }
292
-    
293
-    /** OBSOLETE Send log. Throws exception on critical error
294
-     *	@param	string $message Message to log
295
-     *	@param	int $level 1=critical 2=warning 3=trace 4=debug
296
-     *	@param  string $destination file/syslog/display
297
-     *	@return void
298
-     **/
299
-    public function trapLog( $message, $level, $destination ='') // OBSOLETE
300
-    {
301
-        // TODO : replace ref with $this->logging->log
302
-        $this->logging->log($message, $level, $destination);
303
-    }
304
-    
305
-    public function setLogging($debugLvl,$outputType,$outputOption=null)  // OBSOLETE
306
-    {
307
-        $this->logging->setLogging($debugLvl, $outputType,$outputOption);
308
-    }
309
-    
310
-    /**
311
-     * Returns or create new IcingaAPI object
312
-     * @return \Icinga\Module\Trapdirector\Icinga2API
313
-     */
314
-    protected function getAPI()
315
-    {
316
-        if ($this->icinga2api == null)
317
-        {
318
-            $this->icinga2api = new Icinga2API($this->apiHostname,$this->apiPort);
319
-        }
320
-        return $this->icinga2api;
321
-    }
322
-    
323
-    
324
-    /**
325
-     * read data from stream
326
-     *	@param $stream string input stream, defaults to "php://stdin"
327
-     *	@return mixed array trap data or exception with error
328
-     */
329
-    public function read_trap($stream='php://stdin')
330
-    {
331
-        //Read data from snmptrapd from stdin
332
-        $input_stream=fopen($stream, 'r');
333
-        
334
-        if ($input_stream === false)
335
-        {
336
-            $this->writeTrapErrorToDB("Error reading trap (code 1/Stdin)");
337
-            $this->logging->log("Error reading stdin !",ERROR,'');
338
-            return null; // note : exception thrown by logging
339
-        }
340
-        
341
-        // line 1 : host
342
-        $this->receivingHost=chop(fgets($input_stream));
343
-        if ($this->receivingHost === false)
344
-        {
345
-            $this->writeTrapErrorToDB("Error reading trap (code 1/Line Host)");
346
-            $this->logging->log("Error reading Host !",ERROR,'');
347
-        }
348
-        // line 2 IP:port=>IP:port
349
-        $IP=chop(fgets($input_stream));
350
-        if ($IP === false)
351
-        {
352
-            $this->writeTrapErrorToDB("Error reading trap (code 1/Line IP)");
353
-            $this->logging->log("Error reading IP !",ERROR,'');
354
-        }
355
-        $matches=array();
356
-        $ret_code=preg_match('/.DP: \[(.*)\]:(.*)->\[(.*)\]:(.*)/',$IP,$matches);
357
-        if ($ret_code===0 || $ret_code===false)
358
-        {
359
-            $this->writeTrapErrorToDB("Error parsing trap (code 2/IP)");
360
-            $this->logging->log('Error parsing IP : '.$IP,ERROR,'');
361
-        }
362
-        else
363
-        {
364
-            $this->trapData['source_ip']=$matches[1];
365
-            $this->trapData['destination_ip']=$matches[3];
366
-            $this->trapData['source_port']=$matches[2];
367
-            $this->trapData['destination_port']=$matches[4];
368
-        }
369
-        
370
-        while (($vars=fgets($input_stream)) !==false)
371
-        {
372
-            $vars=chop($vars);
373
-            $ret_code=preg_match('/^([^ ]+) (.*)$/',$vars,$matches);
374
-            if ($ret_code===0 || $ret_code===false)
375
-            {
376
-                $this->logging->log('No match on trap data : '.$vars,WARN,'');
377
-            }
378
-            else
379
-            {
380
-                if (($matches[1]=='.1.3.6.1.6.3.1.1.4.1.0') || ($matches[1]=='.1.3.6.1.6.3.1.1.4.1'))
381
-                {
382
-                    $this->trapData['trap_oid']=$matches[2];
383
-                }
384
-                else
385
-                {
386
-                    $object= new stdClass;
387
-                    $object->oid =$matches[1];
388
-                    $object->value = $matches[2];
389
-                    array_push($this->trapDataExt,$object);
390
-                }
391
-            }
392
-        }
393
-        
394
-        if ($this->trapData['trap_oid']=='unknown')
395
-        {
396
-            $this->writeTrapErrorToDB("No trap oid found : check snmptrapd configuration (code 3/OID)",$this->trapData['source_ip']);
397
-            $this->logging->log('no trap oid found',ERROR,'');
398
-        }
399
-        
400
-        // Translate oids.
401
-        
402
-        $retArray=$this->translateOID($this->trapData['trap_oid']);
403
-        if ($retArray != null)
404
-        {
405
-            $this->trapData['trap_name']=$retArray['trap_name'];
406
-            $this->trapData['trap_name_mib']=$retArray['trap_name_mib'];
407
-        }
408
-        foreach ($this->trapDataExt as $key => $val)
409
-        {
410
-            $retArray=$this->translateOID($val->oid);
411
-            if ($retArray != null)
412
-            {
413
-                $this->trapDataExt[$key]->oid_name=$retArray['trap_name'];
414
-                $this->trapDataExt[$key]->oid_name_mib=$retArray['trap_name_mib'];
415
-            }
416
-        }
417
-        
418
-        
419
-        $this->trapData['status']= 'waiting';
420
-        
421
-        return $this->trapData;
422
-    }
423
-    
424
-    /**
425
-     * Translate oid into array(MIB,Name)
426
-     * @param $oid string oid to translate
427
-     * @return mixed : null if not found or array(MIB,Name)
428
-     */
429
-    public function translateOID($oid)
430
-    {
431
-        // try from database
432
-        $db_conn=$this->trapsDB->db_connect_trap();
433
-        
434
-        $sql='SELECT mib,name from '.$this->dbPrefix.'mib_cache WHERE oid=\''.$oid.'\';';
435
-        $this->logging->log('SQL query : '.$sql,DEBUG );
436
-        if (($ret_code=$db_conn->query($sql)) === false) {
437
-            $this->logging->log('No result in query : ' . $sql,ERROR,'');
438
-        }
439
-        $name=$ret_code->fetch();
440
-        if ($name['name'] != null)
441
-        {
442
-            return array('trap_name_mib'=>$name['mib'],'trap_name'=>$name['name']);
443
-        }
444
-        
445
-        // Also check if it is an instance of OID
446
-        $oid_instance=preg_replace('/\.[0-9]+$/','',$oid);
447
-        
448
-        $sql='SELECT mib,name from '.$this->dbPrefix.'mib_cache WHERE oid=\''.$oid_instance.'\';';
449
-        $this->logging->log('SQL query : '.$sql,DEBUG );
450
-        if (($ret_code=$db_conn->query($sql)) === false) {
451
-            $this->logging->log('No result in query : ' . $sql,ERROR,'');
452
-        }
453
-        $name=$ret_code->fetch();
454
-        if ($name['name'] != null)
455
-        {
456
-            return array('trap_name_mib'=>$name['mib'],'trap_name'=>$name['name']);
457
-        }
458
-        
459
-        // Try to get oid name from snmptranslate
460
-        $translate=exec($this->snmptranslate . ' -m ALL -M +'.$this->snmptranslate_dirs.
461
-            ' '.$oid);
462
-        $matches=array();
463
-        $ret_code=preg_match('/(.*)::(.*)/',$translate,$matches);
464
-        if ($ret_code===0 || $ret_code === false) {
465
-            return NULL;
466
-        } else {
467
-            $this->logging->log('Found name with snmptrapd and not in DB for oid='.$oid,INFO);
468
-            return array('trap_name_mib'=>$matches[1],'trap_name'=>$matches[2]);
469
-        }
470
-    }
471
-    
472
-    /**
473
-     * Erase old trap records
474
-     *	@param integer $days : erase traps when more than $days old
475
-     *	@return integer : number of lines deleted
476
-     **/
477
-    public function eraseOldTraps($days=0)
478
-    {
479
-        if ($days==0)
480
-        {
481
-            if (($days=$this->getDBConfig('db_remove_days')) == null)
482
-            {
483
-                $this->logging->log('No days specified & no db value : no tap erase' ,WARN,'');
484
-                return;
485
-            }
486
-        }
487
-        $db_conn=$this->trapsDB->db_connect_trap();
488
-        $daysago = strtotime("-".$days." day");
489
-        $sql= 'delete from '.$this->dbPrefix.'received where date_received < \''.date("Y-m-d H:i:s",$daysago).'\';';
490
-        if ($db_conn->query($sql) === false) {
491
-            $this->logging->log('Error erasing traps : '.$sql,ERROR,'');
492
-        }
493
-        $this->logging->log('Erased traps older than '.$days.' day(s) : '.$sql,INFO);
494
-    }
495
-    
496
-    /** Write error to received trap database
497
-     */
498
-    public function writeTrapErrorToDB($message,$sourceIP=null,$trapoid=null)
499
-    {
500
-        
501
-        $db_conn=$this->trapsDB->db_connect_trap();
502
-        
503
-        // add date time
504
-        $insert_col ='date_received,status';
505
-        $insert_val = "'" . date("Y-m-d H:i:s")."','error'";
506
-        
507
-        if ($sourceIP !=null)
508
-        {
509
-            $insert_col .=',source_ip';
510
-            $insert_val .=",'". $sourceIP ."'";
511
-        }
512
-        if ($trapoid !=null)
513
-        {
514
-            $insert_col .=',trap_oid';
515
-            $insert_val .=",'". $trapoid ."'";
516
-        }
517
-        $insert_col .=',status_detail';
518
-        $insert_val .=",'". $message ."'";
519
-        
520
-        $sql= 'INSERT INTO '.$this->dbPrefix.'received (' . $insert_col . ') VALUES ('.$insert_val.')';
521
-        
522
-        switch ($this->trapsDB->trapDBType)
523
-        {
524
-            case 'pgsql':
525
-                $sql .= ' RETURNING id;';
526
-                $this->logging->log('sql : '.$sql,INFO);
527
-                if (($ret_code=$db_conn->query($sql)) === false) {
528
-                    $this->logging->log('Error SQL insert : '.$sql,1,'');
529
-                }
530
-                $this->logging->log('SQL insertion OK',INFO );
531
-                // Get last id to insert oid/values in secondary table
532
-                if (($inserted_id_ret=$ret_code->fetch(PDO::FETCH_ASSOC)) === false) {
142
+	}
143
+    
144
+	/**
145
+	 * Get option from array of ini file, send message if empty
146
+	 * @param string $option_array Array of ini file
147
+	 * @param string $option_category category in ini file
148
+	 * @param string $option_name name of option in category
149
+	 * @param mixed $option_var variable to fill if found, left untouched if not found
150
+	 * @param integer $log_level default 2 (warning)
151
+	 * @param string $message warning message if not found
152
+	 * @return boolean true if found, or false
153
+	 */
154
+	protected function getOptionIfSet($option_array,$option_category,$option_name, &$option_var, $log_level = 2, $message = null)
155
+	{
156
+		if (!isset($option_array[$option_category][$option_name]))
157
+		{
158
+			if ($message === null)
159
+			{
160
+				$message='No ' . $option_name . ' in config file: '. $this->trapModuleConfig;
161
+			}
162
+			$this->logging->log($message,$log_level);
163
+			return false;
164
+		}
165
+		else
166
+		{
167
+			$option_var=$option_array[$option_category][$option_name];
168
+			return true;
169
+		}
170
+	}
171
+    
172
+	/**
173
+	 * Get options from ini file
174
+	 * @param array $trap_config : ini file array
175
+	 */
176
+	protected function getMainOptions($trapConfig)
177
+	{
178
+        
179
+		// Snmptranslate binary path
180
+		$this->getOptionIfSet($trapConfig,'config','snmptranslate', $this->snmptranslate);
181
+        
182
+		// mibs path
183
+		$this->getOptionIfSet($trapConfig,'config','snmptranslate_dirs', $this->snmptranslate_dirs);
184
+        
185
+		// icinga2cmd path
186
+		$this->getOptionIfSet($trapConfig,'config','icingacmd', $this->icinga2cmd);
187
+        
188
+		// table prefix
189
+		$this->getOptionIfSet($trapConfig,'config','database_prefix', $this->dbPrefix);
190
+        
191
+		// API options
192
+		if ($this->getOptionIfSet($trapConfig,'config','icingaAPI_host', $this->apiHostname))
193
+		{
194
+			$this->apiUse=true;
195
+			$this->getOptionIfSet($trapConfig,'config','icingaAPI_port', $this->apiPort);
196
+			$this->getOptionIfSet($trapConfig,'config','icingaAPI_user', $this->apiUsername);
197
+			$this->getOptionIfSet($trapConfig,'config','icingaAPI_password', $this->apiPassword);
198
+		}
199
+	}
200
+    
201
+	/**
202
+	 * Create and setup database class for trap & ido (if no api) db
203
+	 * @param array $trap_config : ini file array
204
+	 */
205
+	protected function setupDatabase($trapConfig)
206
+	{
207
+		// Trap database
208
+		if (!array_key_exists('database',$trapConfig['config']))
209
+		{
210
+			$this->logging->log("No database in config file: ".$this->trapModuleConfig,ERROR,'');
211
+			return;
212
+		}
213
+		$dbTrapName=$trapConfig['config']['database'];
214
+		$this->logging->log("Found database in config file: ".$dbTrapName,INFO );
215
+        
216
+		if ( ($dbConfig=parse_ini_file($this->icingaweb2Ressources,true)) === false)
217
+		{
218
+			$this->logging->log("Error reading ini file : ".$this->icingaweb2Ressources,ERROR,'');
219
+			return;
220
+		}
221
+		if (!array_key_exists($dbTrapName,$dbConfig))
222
+		{
223
+			$this->logging->log("No database '.$dbTrapName.' in config file: ".$this->icingaweb2Ressources,ERROR,'');
224
+			return;
225
+		}
226
+        
227
+		$this->trapsDB = new Database($this->logging,$dbConfig[$dbTrapName],$this->dbPrefix);
228
+        
229
+		if ($this->apiUse === true) return; // In case of API use, no IDO is necessary
230
+        
231
+		// IDO Database
232
+		if (!array_key_exists('IDOdatabase',$trapConfig['config']))
233
+		{
234
+			$this->logging->log("No IDOdatabase in config file: ".$this->trapModuleConfig,ERROR,'');
235
+		}
236
+		$dbIdoName=$trapConfig['config']['IDOdatabase'];
237
+        
238
+		$this->logging->log("Found IDO database in config file: ".$dbIdoName,INFO );
239
+		if (!array_key_exists($dbIdoName,$dbConfig))
240
+		{
241
+			$this->logging->log("No database '.$dbIdoName.' in config file: ".$this->icingaweb2Ressources,ERROR,'');
242
+			return;
243
+		}
244
+        
245
+		$this->trapsDB->setupIDO($dbConfig[$dbIdoName]);
246
+	}
247
+    
248
+	/**
249
+	 * Get options in database
250
+	 */
251
+	protected function getDatabaseOptions()
252
+	{
253
+		// Database options
254
+		if ($this->logSetup === false) // Only if logging was no setup in constructor
255
+		{
256
+			$this->getDBConfigIfSet('log_level',$this->logging->debugLevel);
257
+			$this->getDBConfigIfSet('log_destination',$this->logging->outputMode);
258
+			$this->getDBConfigIfSet('log_file',$this->logging->outputFile);
259
+		}
260
+	}
261
+    
262
+	/** Set $variable to value if $element found in database config table
263
+	 * @param string $element
264
+	 * @param string $variable
265
+	 */
266
+	protected function getDBConfigIfSet($element,&$variable)
267
+	{
268
+		$value=$this->getDBConfig($element);
269
+		if ($value != null) $variable=$value;
270
+	}
271
+    
272
+	/**
273
+	 *   Get data from db_config
274
+	 *	@param $element string name of param
275
+	 *	@return mixed : value (or null)
276
+	 */
277
+	protected function getDBConfig($element)  // TODO : put this in DB class
278
+	{
279
+		$db_conn=$this->trapsDB->db_connect_trap();
280
+		$sql='SELECT value from '.$this->dbPrefix.'db_config WHERE ( name=\''.$element.'\' )';
281
+		if (($ret_code=$db_conn->query($sql)) === false) {
282
+			$this->logging->log('No result in query : ' . $sql,WARN,'');
283
+			return null;
284
+		}
285
+		$value=$ret_code->fetch();
286
+		if ($value != null && isset($value['value']))
287
+		{
288
+			return $value['value'];
289
+		}
290
+		return null;
291
+	}
292
+    
293
+	/** OBSOLETE Send log. Throws exception on critical error
294
+	 *	@param	string $message Message to log
295
+	 *	@param	int $level 1=critical 2=warning 3=trace 4=debug
296
+	 *	@param  string $destination file/syslog/display
297
+	 *	@return void
298
+	 **/
299
+	public function trapLog( $message, $level, $destination ='') // OBSOLETE
300
+	{
301
+		// TODO : replace ref with $this->logging->log
302
+		$this->logging->log($message, $level, $destination);
303
+	}
304
+    
305
+	public function setLogging($debugLvl,$outputType,$outputOption=null)  // OBSOLETE
306
+	{
307
+		$this->logging->setLogging($debugLvl, $outputType,$outputOption);
308
+	}
309
+    
310
+	/**
311
+	 * Returns or create new IcingaAPI object
312
+	 * @return \Icinga\Module\Trapdirector\Icinga2API
313
+	 */
314
+	protected function getAPI()
315
+	{
316
+		if ($this->icinga2api == null)
317
+		{
318
+			$this->icinga2api = new Icinga2API($this->apiHostname,$this->apiPort);
319
+		}
320
+		return $this->icinga2api;
321
+	}
322
+    
323
+    
324
+	/**
325
+	 * read data from stream
326
+	 *	@param $stream string input stream, defaults to "php://stdin"
327
+	 *	@return mixed array trap data or exception with error
328
+	 */
329
+	public function read_trap($stream='php://stdin')
330
+	{
331
+		//Read data from snmptrapd from stdin
332
+		$input_stream=fopen($stream, 'r');
333
+        
334
+		if ($input_stream === false)
335
+		{
336
+			$this->writeTrapErrorToDB("Error reading trap (code 1/Stdin)");
337
+			$this->logging->log("Error reading stdin !",ERROR,'');
338
+			return null; // note : exception thrown by logging
339
+		}
340
+        
341
+		// line 1 : host
342
+		$this->receivingHost=chop(fgets($input_stream));
343
+		if ($this->receivingHost === false)
344
+		{
345
+			$this->writeTrapErrorToDB("Error reading trap (code 1/Line Host)");
346
+			$this->logging->log("Error reading Host !",ERROR,'');
347
+		}
348
+		// line 2 IP:port=>IP:port
349
+		$IP=chop(fgets($input_stream));
350
+		if ($IP === false)
351
+		{
352
+			$this->writeTrapErrorToDB("Error reading trap (code 1/Line IP)");
353
+			$this->logging->log("Error reading IP !",ERROR,'');
354
+		}
355
+		$matches=array();
356
+		$ret_code=preg_match('/.DP: \[(.*)\]:(.*)->\[(.*)\]:(.*)/',$IP,$matches);
357
+		if ($ret_code===0 || $ret_code===false)
358
+		{
359
+			$this->writeTrapErrorToDB("Error parsing trap (code 2/IP)");
360
+			$this->logging->log('Error parsing IP : '.$IP,ERROR,'');
361
+		}
362
+		else
363
+		{
364
+			$this->trapData['source_ip']=$matches[1];
365
+			$this->trapData['destination_ip']=$matches[3];
366
+			$this->trapData['source_port']=$matches[2];
367
+			$this->trapData['destination_port']=$matches[4];
368
+		}
369
+        
370
+		while (($vars=fgets($input_stream)) !==false)
371
+		{
372
+			$vars=chop($vars);
373
+			$ret_code=preg_match('/^([^ ]+) (.*)$/',$vars,$matches);
374
+			if ($ret_code===0 || $ret_code===false)
375
+			{
376
+				$this->logging->log('No match on trap data : '.$vars,WARN,'');
377
+			}
378
+			else
379
+			{
380
+				if (($matches[1]=='.1.3.6.1.6.3.1.1.4.1.0') || ($matches[1]=='.1.3.6.1.6.3.1.1.4.1'))
381
+				{
382
+					$this->trapData['trap_oid']=$matches[2];
383
+				}
384
+				else
385
+				{
386
+					$object= new stdClass;
387
+					$object->oid =$matches[1];
388
+					$object->value = $matches[2];
389
+					array_push($this->trapDataExt,$object);
390
+				}
391
+			}
392
+		}
393
+        
394
+		if ($this->trapData['trap_oid']=='unknown')
395
+		{
396
+			$this->writeTrapErrorToDB("No trap oid found : check snmptrapd configuration (code 3/OID)",$this->trapData['source_ip']);
397
+			$this->logging->log('no trap oid found',ERROR,'');
398
+		}
399
+        
400
+		// Translate oids.
401
+        
402
+		$retArray=$this->translateOID($this->trapData['trap_oid']);
403
+		if ($retArray != null)
404
+		{
405
+			$this->trapData['trap_name']=$retArray['trap_name'];
406
+			$this->trapData['trap_name_mib']=$retArray['trap_name_mib'];
407
+		}
408
+		foreach ($this->trapDataExt as $key => $val)
409
+		{
410
+			$retArray=$this->translateOID($val->oid);
411
+			if ($retArray != null)
412
+			{
413
+				$this->trapDataExt[$key]->oid_name=$retArray['trap_name'];
414
+				$this->trapDataExt[$key]->oid_name_mib=$retArray['trap_name_mib'];
415
+			}
416
+		}
417
+        
418
+        
419
+		$this->trapData['status']= 'waiting';
420
+        
421
+		return $this->trapData;
422
+	}
423
+    
424
+	/**
425
+	 * Translate oid into array(MIB,Name)
426
+	 * @param $oid string oid to translate
427
+	 * @return mixed : null if not found or array(MIB,Name)
428
+	 */
429
+	public function translateOID($oid)
430
+	{
431
+		// try from database
432
+		$db_conn=$this->trapsDB->db_connect_trap();
433
+        
434
+		$sql='SELECT mib,name from '.$this->dbPrefix.'mib_cache WHERE oid=\''.$oid.'\';';
435
+		$this->logging->log('SQL query : '.$sql,DEBUG );
436
+		if (($ret_code=$db_conn->query($sql)) === false) {
437
+			$this->logging->log('No result in query : ' . $sql,ERROR,'');
438
+		}
439
+		$name=$ret_code->fetch();
440
+		if ($name['name'] != null)
441
+		{
442
+			return array('trap_name_mib'=>$name['mib'],'trap_name'=>$name['name']);
443
+		}
444
+        
445
+		// Also check if it is an instance of OID
446
+		$oid_instance=preg_replace('/\.[0-9]+$/','',$oid);
447
+        
448
+		$sql='SELECT mib,name from '.$this->dbPrefix.'mib_cache WHERE oid=\''.$oid_instance.'\';';
449
+		$this->logging->log('SQL query : '.$sql,DEBUG );
450
+		if (($ret_code=$db_conn->query($sql)) === false) {
451
+			$this->logging->log('No result in query : ' . $sql,ERROR,'');
452
+		}
453
+		$name=$ret_code->fetch();
454
+		if ($name['name'] != null)
455
+		{
456
+			return array('trap_name_mib'=>$name['mib'],'trap_name'=>$name['name']);
457
+		}
458
+        
459
+		// Try to get oid name from snmptranslate
460
+		$translate=exec($this->snmptranslate . ' -m ALL -M +'.$this->snmptranslate_dirs.
461
+			' '.$oid);
462
+		$matches=array();
463
+		$ret_code=preg_match('/(.*)::(.*)/',$translate,$matches);
464
+		if ($ret_code===0 || $ret_code === false) {
465
+			return NULL;
466
+		} else {
467
+			$this->logging->log('Found name with snmptrapd and not in DB for oid='.$oid,INFO);
468
+			return array('trap_name_mib'=>$matches[1],'trap_name'=>$matches[2]);
469
+		}
470
+	}
471
+    
472
+	/**
473
+	 * Erase old trap records
474
+	 *	@param integer $days : erase traps when more than $days old
475
+	 *	@return integer : number of lines deleted
476
+	 **/
477
+	public function eraseOldTraps($days=0)
478
+	{
479
+		if ($days==0)
480
+		{
481
+			if (($days=$this->getDBConfig('db_remove_days')) == null)
482
+			{
483
+				$this->logging->log('No days specified & no db value : no tap erase' ,WARN,'');
484
+				return;
485
+			}
486
+		}
487
+		$db_conn=$this->trapsDB->db_connect_trap();
488
+		$daysago = strtotime("-".$days." day");
489
+		$sql= 'delete from '.$this->dbPrefix.'received where date_received < \''.date("Y-m-d H:i:s",$daysago).'\';';
490
+		if ($db_conn->query($sql) === false) {
491
+			$this->logging->log('Error erasing traps : '.$sql,ERROR,'');
492
+		}
493
+		$this->logging->log('Erased traps older than '.$days.' day(s) : '.$sql,INFO);
494
+	}
495
+    
496
+	/** Write error to received trap database
497
+	 */
498
+	public function writeTrapErrorToDB($message,$sourceIP=null,$trapoid=null)
499
+	{
500
+        
501
+		$db_conn=$this->trapsDB->db_connect_trap();
502
+        
503
+		// add date time
504
+		$insert_col ='date_received,status';
505
+		$insert_val = "'" . date("Y-m-d H:i:s")."','error'";
506
+        
507
+		if ($sourceIP !=null)
508
+		{
509
+			$insert_col .=',source_ip';
510
+			$insert_val .=",'". $sourceIP ."'";
511
+		}
512
+		if ($trapoid !=null)
513
+		{
514
+			$insert_col .=',trap_oid';
515
+			$insert_val .=",'". $trapoid ."'";
516
+		}
517
+		$insert_col .=',status_detail';
518
+		$insert_val .=",'". $message ."'";
519
+        
520
+		$sql= 'INSERT INTO '.$this->dbPrefix.'received (' . $insert_col . ') VALUES ('.$insert_val.')';
521
+        
522
+		switch ($this->trapsDB->trapDBType)
523
+		{
524
+			case 'pgsql':
525
+				$sql .= ' RETURNING id;';
526
+				$this->logging->log('sql : '.$sql,INFO);
527
+				if (($ret_code=$db_conn->query($sql)) === false) {
528
+					$this->logging->log('Error SQL insert : '.$sql,1,'');
529
+				}
530
+				$this->logging->log('SQL insertion OK',INFO );
531
+				// Get last id to insert oid/values in secondary table
532
+				if (($inserted_id_ret=$ret_code->fetch(PDO::FETCH_ASSOC)) === false) {
533 533
                     
534
-                    $this->logging->log('Erreur recuperation id',1,'');
535
-                }
536
-                if (! isset($inserted_id_ret['id'])) {
537
-                    $this->logging->log('Error getting id',1,'');
538
-                }
539
-                $this->trapId=$inserted_id_ret['id'];
540
-                break;
541
-            case 'mysql':
542
-                $sql .= ';';
543
-                $this->logging->log('sql : '.$sql,INFO );
544
-                if ($db_conn->query($sql) === false) {
545
-                    $this->logging->log('Error SQL insert : '.$sql,1,'');
546
-                }
547
-                $this->logging->log('SQL insertion OK',INFO );
548
-                // Get last id to insert oid/values in secondary table
549
-                $sql='SELECT LAST_INSERT_ID();';
550
-                if (($ret_code=$db_conn->query($sql)) === false) {
551
-                    $this->logging->log('Erreur recuperation id',1,'');
552
-                }
534
+					$this->logging->log('Erreur recuperation id',1,'');
535
+				}
536
+				if (! isset($inserted_id_ret['id'])) {
537
+					$this->logging->log('Error getting id',1,'');
538
+				}
539
+				$this->trapId=$inserted_id_ret['id'];
540
+				break;
541
+			case 'mysql':
542
+				$sql .= ';';
543
+				$this->logging->log('sql : '.$sql,INFO );
544
+				if ($db_conn->query($sql) === false) {
545
+					$this->logging->log('Error SQL insert : '.$sql,1,'');
546
+				}
547
+				$this->logging->log('SQL insertion OK',INFO );
548
+				// Get last id to insert oid/values in secondary table
549
+				$sql='SELECT LAST_INSERT_ID();';
550
+				if (($ret_code=$db_conn->query($sql)) === false) {
551
+					$this->logging->log('Erreur recuperation id',1,'');
552
+				}
553 553
                 
554
-                $inserted_id=$ret_code->fetch(PDO::FETCH_ASSOC)['LAST_INSERT_ID()'];
555
-                if ($inserted_id==false) throw new Exception("Weird SQL error : last_insert_id returned false : open issue");
556
-                $this->trapId=$inserted_id;
557
-                break;
558
-            default:
559
-                $this->logging->log('Error SQL type unknown  : '.$this->trapsDB->trapDBType,1,'');
560
-        }
561
-        
562
-        $this->logging->log('id found: '. $this->trapId,INFO );
563
-    }
564
-    
565
-    /** Write trap data to trap database
566
-     */
567
-    public function writeTrapToDB()
568
-    {
569
-        
570
-        // If action is ignore -> don't send t DB
571
-        if ($this->trapToDb === false) return;
572
-        
573
-        
574
-        $db_conn=$this->trapsDB->db_connect_trap();
575
-        
576
-        $insert_col='';
577
-        $insert_val='';
578
-        // add date time
579
-        $this->trapData['date_received'] = date("Y-m-d H:i:s");
580
-        
581
-        $firstcol=1;
582
-        foreach ($this->trapData as $col => $val)
583
-        {
584
-            if ($firstcol==0)
585
-            {
586
-                $insert_col .=',';
587
-                $insert_val .=',';
588
-            }
589
-            $insert_col .= $col ;
590
-            $insert_val .= ($val==null)? 'NULL' : $db_conn->quote($val);
591
-            $firstcol=0;
592
-        }
593
-        
594
-        $sql= 'INSERT INTO '.$this->dbPrefix.'received (' . $insert_col . ') VALUES ('.$insert_val.')';
595
-        switch ($this->trapsDB->trapDBType)
596
-        {
597
-            case 'pgsql':
598
-                $sql .= ' RETURNING id;';
599
-                $this->logging->log('sql : '.$sql,INFO );
600
-                if (($ret_code=$db_conn->query($sql)) === false) {
601
-                    $this->logging->log('Error SQL insert : '.$sql,ERROR,'');
602
-                }
603
-                $this->logging->log('SQL insertion OK',INFO );
604
-                // Get last id to insert oid/values in secondary table
605
-                if (($inserted_id_ret=$ret_code->fetch(PDO::FETCH_ASSOC)) === false) {
554
+				$inserted_id=$ret_code->fetch(PDO::FETCH_ASSOC)['LAST_INSERT_ID()'];
555
+				if ($inserted_id==false) throw new Exception("Weird SQL error : last_insert_id returned false : open issue");
556
+				$this->trapId=$inserted_id;
557
+				break;
558
+			default:
559
+				$this->logging->log('Error SQL type unknown  : '.$this->trapsDB->trapDBType,1,'');
560
+		}
561
+        
562
+		$this->logging->log('id found: '. $this->trapId,INFO );
563
+	}
564
+    
565
+	/** Write trap data to trap database
566
+	 */
567
+	public function writeTrapToDB()
568
+	{
569
+        
570
+		// If action is ignore -> don't send t DB
571
+		if ($this->trapToDb === false) return;
572
+        
573
+        
574
+		$db_conn=$this->trapsDB->db_connect_trap();
575
+        
576
+		$insert_col='';
577
+		$insert_val='';
578
+		// add date time
579
+		$this->trapData['date_received'] = date("Y-m-d H:i:s");
580
+        
581
+		$firstcol=1;
582
+		foreach ($this->trapData as $col => $val)
583
+		{
584
+			if ($firstcol==0)
585
+			{
586
+				$insert_col .=',';
587
+				$insert_val .=',';
588
+			}
589
+			$insert_col .= $col ;
590
+			$insert_val .= ($val==null)? 'NULL' : $db_conn->quote($val);
591
+			$firstcol=0;
592
+		}
593
+        
594
+		$sql= 'INSERT INTO '.$this->dbPrefix.'received (' . $insert_col . ') VALUES ('.$insert_val.')';
595
+		switch ($this->trapsDB->trapDBType)
596
+		{
597
+			case 'pgsql':
598
+				$sql .= ' RETURNING id;';
599
+				$this->logging->log('sql : '.$sql,INFO );
600
+				if (($ret_code=$db_conn->query($sql)) === false) {
601
+					$this->logging->log('Error SQL insert : '.$sql,ERROR,'');
602
+				}
603
+				$this->logging->log('SQL insertion OK',INFO );
604
+				// Get last id to insert oid/values in secondary table
605
+				if (($inserted_id_ret=$ret_code->fetch(PDO::FETCH_ASSOC)) === false) {
606 606
                     
607
-                    $this->logging->log('Erreur recuperation id',ERROR,'');
608
-                }
609
-                if (! isset($inserted_id_ret['id'])) {
610
-                    $this->logging->log('Error getting id',ERROR,'');
611
-                }
612
-                $this->trapId=$inserted_id_ret['id'];
613
-                break;
614
-            case 'mysql':
615
-                $sql .= ';';
616
-                $this->logging->log('sql : '.$sql,INFO );
617
-                if ($db_conn->query($sql) === false) {
618
-                    $this->logging->log('Error SQL insert : '.$sql,ERROR,'');
619
-                }
620
-                $this->logging->log('SQL insertion OK',INFO );
621
-                // Get last id to insert oid/values in secondary table
622
-                $sql='SELECT LAST_INSERT_ID();';
623
-                if (($ret_code=$db_conn->query($sql)) === false) {
624
-                    $this->logging->log('Erreur recuperation id',ERROR,'');
625
-                }
607
+					$this->logging->log('Erreur recuperation id',ERROR,'');
608
+				}
609
+				if (! isset($inserted_id_ret['id'])) {
610
+					$this->logging->log('Error getting id',ERROR,'');
611
+				}
612
+				$this->trapId=$inserted_id_ret['id'];
613
+				break;
614
+			case 'mysql':
615
+				$sql .= ';';
616
+				$this->logging->log('sql : '.$sql,INFO );
617
+				if ($db_conn->query($sql) === false) {
618
+					$this->logging->log('Error SQL insert : '.$sql,ERROR,'');
619
+				}
620
+				$this->logging->log('SQL insertion OK',INFO );
621
+				// Get last id to insert oid/values in secondary table
622
+				$sql='SELECT LAST_INSERT_ID();';
623
+				if (($ret_code=$db_conn->query($sql)) === false) {
624
+					$this->logging->log('Erreur recuperation id',ERROR,'');
625
+				}
626 626
                 
627
-                $inserted_id=$ret_code->fetch(PDO::FETCH_ASSOC)['LAST_INSERT_ID()'];
628
-                if ($inserted_id==false) throw new Exception("Weird SQL error : last_insert_id returned false : open issue");
629
-                $this->trapId=$inserted_id;
630
-                break;
631
-            default:
632
-                $this->logging->log('Error SQL type unknown : '.$this->trapsDB->trapDBType,ERROR,'');
633
-        }
634
-        $this->logging->log('id found: '.$this->trapId,INFO );
635
-        
636
-        // Fill trap extended data table
637
-        foreach ($this->trapDataExt as $value) {
638
-            // TODO : detect if trap value is encoded and decode it to UTF-8 for database
639
-            $firstcol=1;
640
-            $value->trap_id = $this->trapId;
641
-            $insert_col='';
642
-            $insert_val='';
643
-            foreach ($value as $col => $val)
644
-            {
645
-                if ($firstcol==0)
646
-                {
647
-                    $insert_col .=',';
648
-                    $insert_val .=',';
649
-                }
650
-                $insert_col .= $col;
651
-                $insert_val .= ($val==null)? 'NULL' : $db_conn->quote($val);
652
-                $firstcol=0;
653
-            }
627
+				$inserted_id=$ret_code->fetch(PDO::FETCH_ASSOC)['LAST_INSERT_ID()'];
628
+				if ($inserted_id==false) throw new Exception("Weird SQL error : last_insert_id returned false : open issue");
629
+				$this->trapId=$inserted_id;
630
+				break;
631
+			default:
632
+				$this->logging->log('Error SQL type unknown : '.$this->trapsDB->trapDBType,ERROR,'');
633
+		}
634
+		$this->logging->log('id found: '.$this->trapId,INFO );
635
+        
636
+		// Fill trap extended data table
637
+		foreach ($this->trapDataExt as $value) {
638
+			// TODO : detect if trap value is encoded and decode it to UTF-8 for database
639
+			$firstcol=1;
640
+			$value->trap_id = $this->trapId;
641
+			$insert_col='';
642
+			$insert_val='';
643
+			foreach ($value as $col => $val)
644
+			{
645
+				if ($firstcol==0)
646
+				{
647
+					$insert_col .=',';
648
+					$insert_val .=',';
649
+				}
650
+				$insert_col .= $col;
651
+				$insert_val .= ($val==null)? 'NULL' : $db_conn->quote($val);
652
+				$firstcol=0;
653
+			}
654 654
             
655
-            $sql= 'INSERT INTO '.$this->dbPrefix.'received_data (' . $insert_col . ') VALUES ('.$insert_val.');';
655
+			$sql= 'INSERT INTO '.$this->dbPrefix.'received_data (' . $insert_col . ') VALUES ('.$insert_val.');';
656 656
             
657
-            if ($db_conn->query($sql) === false) {
658
-                $this->logging->log('Erreur insertion data : ' . $sql,WARN,'');
659
-            }
660
-        }
661
-    }
662
-    
663
-    /** Get rules from rule database with ip and oid
664
-     *	@param $ip string ipv4 or ipv6
665
-     *	@param $oid string oid in numeric
666
-     *	@return mixed|boolean : PDO object or false
667
-     */
668
-    protected function getRules($ip,$oid)
669
-    {
670
-        $db_conn=$this->trapsDB->db_connect_trap();
671
-        // fetch rules based on IP in rule and OID
672
-        $sql='SELECT * from '.$this->dbPrefix.'rules WHERE trap_oid=\''.$oid.'\' ';
673
-        $this->logging->log('SQL query : '.$sql,DEBUG );
674
-        if (($ret_code=$db_conn->query($sql)) === false) {
675
-            $this->logging->log('No result in query : ' . $sql,WARN,'');
676
-            return false;
677
-        }
678
-        $rules_all=$ret_code->fetchAll();
679
-        //echo "rule all :\n";print_r($rules_all);echo "\n";
680
-        $rules_ret=array();
681
-        $rule_ret_key=0;
682
-        foreach ($rules_all as $key => $rule)
683
-        {
684
-            if ($rule['ip4']==$ip || $rule['ip6']==$ip)
685
-            {
686
-                $rules_ret[$rule_ret_key]=$rules_all[$key];
687
-                //TODO : get host name by API (and check if correct in rule).
688
-                $rule_ret_key++;
689
-                continue;
690
-            }
691
-            // TODO : get hosts IP by API
692
-            if (isset($rule['host_group_name']) && $rule['host_group_name']!=null)
693
-            { // get ips of group members by oid
694
-                $db_conn2=$this->trapsDB->db_connect_ido();
695
-                $sql="SELECT m.host_object_id, a.address as ip4, a.address6 as ip6, b.name1 as host_name
657
+			if ($db_conn->query($sql) === false) {
658
+				$this->logging->log('Erreur insertion data : ' . $sql,WARN,'');
659
+			}
660
+		}
661
+	}
662
+    
663
+	/** Get rules from rule database with ip and oid
664
+	 *	@param $ip string ipv4 or ipv6
665
+	 *	@param $oid string oid in numeric
666
+	 *	@return mixed|boolean : PDO object or false
667
+	 */
668
+	protected function getRules($ip,$oid)
669
+	{
670
+		$db_conn=$this->trapsDB->db_connect_trap();
671
+		// fetch rules based on IP in rule and OID
672
+		$sql='SELECT * from '.$this->dbPrefix.'rules WHERE trap_oid=\''.$oid.'\' ';
673
+		$this->logging->log('SQL query : '.$sql,DEBUG );
674
+		if (($ret_code=$db_conn->query($sql)) === false) {
675
+			$this->logging->log('No result in query : ' . $sql,WARN,'');
676
+			return false;
677
+		}
678
+		$rules_all=$ret_code->fetchAll();
679
+		//echo "rule all :\n";print_r($rules_all);echo "\n";
680
+		$rules_ret=array();
681
+		$rule_ret_key=0;
682
+		foreach ($rules_all as $key => $rule)
683
+		{
684
+			if ($rule['ip4']==$ip || $rule['ip6']==$ip)
685
+			{
686
+				$rules_ret[$rule_ret_key]=$rules_all[$key];
687
+				//TODO : get host name by API (and check if correct in rule).
688
+				$rule_ret_key++;
689
+				continue;
690
+			}
691
+			// TODO : get hosts IP by API
692
+			if (isset($rule['host_group_name']) && $rule['host_group_name']!=null)
693
+			{ // get ips of group members by oid
694
+				$db_conn2=$this->trapsDB->db_connect_ido();
695
+				$sql="SELECT m.host_object_id, a.address as ip4, a.address6 as ip6, b.name1 as host_name
696 696
 						FROM icinga_objects as o
697 697
 						LEFT JOIN icinga_hostgroups as h ON o.object_id=h.hostgroup_object_id
698 698
 						LEFT JOIN icinga_hostgroup_members as m ON h.hostgroup_id=m.hostgroup_id
699 699
 						LEFT JOIN icinga_hosts as a ON a.host_object_id = m.host_object_id
700 700
 						LEFT JOIN icinga_objects as b ON b.object_id = a.host_object_id
701 701
 						WHERE o.name1='".$rule['host_group_name']."';";
702
-                if (($ret_code2=$db_conn2->query($sql)) === false) {
703
-                    $this->logging->log('No result in query : ' . $sql,WARN,'');
704
-                    continue;
705
-                }
706
-                $grouphosts=$ret_code2->fetchAll();
707
-                //echo "rule grp :\n";print_r($grouphosts);echo "\n";
708
-                foreach ( $grouphosts as $host)
709
-                {
710
-                    //echo $host['ip4']."\n";
711
-                    if ($host['ip4']==$ip || $host['ip6']==$ip)
712
-                    {
713
-                        //echo "Rule added \n";
714
-                        $rules_ret[$rule_ret_key]=$rules_all[$key];
715
-                        $rules_ret[$rule_ret_key]['host_name']=$host['host_name'];
716
-                        $rule_ret_key++;
717
-                    }
718
-                }
719
-            }
720
-        }
721
-        //echo "rule rest :\n";print_r($rules_ret);echo "\n";exit(0);
722
-        return $rules_ret;
723
-    }
724
-    
725
-    /** Add rule match to rule
726
-     *	@param id int : rule id
727
-     *   @param set int : value to set
728
-     */
729
-    protected function add_rule_match($id, $set)
730
-    {
731
-        $db_conn=$this->trapsDB->db_connect_trap();
732
-        $sql="UPDATE ".$this->dbPrefix."rules SET num_match = '".$set."' WHERE (id = '".$id."');";
733
-        if ($db_conn->query($sql) === false) {
734
-            $this->logging->log('Error in update query : ' . $sql,WARN,'');
735
-        }
736
-    }
737
-    
738
-    /** Send SERVICE_CHECK_RESULT with icinga2cmd or API
739
-     *
740
-     * @param string $host
741
-     * @param string $service
742
-     * @param integer $state numerical staus
743
-     * @param string $display
744
-     * @returnn bool true is service check was sent without error
745
-     */
746
-    public function serviceCheckResult($host,$service,$state,$display)
747
-    {
748
-        if ($this->apiUse === false)
749
-        {
750
-            $send = '[' . date('U') .'] PROCESS_SERVICE_CHECK_RESULT;' .
751
-                $host.';' .$service .';' . $state . ';'.$display;
752
-                $this->logging->log( $send." : to : " .$this->icinga2cmd,INFO );
702
+				if (($ret_code2=$db_conn2->query($sql)) === false) {
703
+					$this->logging->log('No result in query : ' . $sql,WARN,'');
704
+					continue;
705
+				}
706
+				$grouphosts=$ret_code2->fetchAll();
707
+				//echo "rule grp :\n";print_r($grouphosts);echo "\n";
708
+				foreach ( $grouphosts as $host)
709
+				{
710
+					//echo $host['ip4']."\n";
711
+					if ($host['ip4']==$ip || $host['ip6']==$ip)
712
+					{
713
+						//echo "Rule added \n";
714
+						$rules_ret[$rule_ret_key]=$rules_all[$key];
715
+						$rules_ret[$rule_ret_key]['host_name']=$host['host_name'];
716
+						$rule_ret_key++;
717
+					}
718
+				}
719
+			}
720
+		}
721
+		//echo "rule rest :\n";print_r($rules_ret);echo "\n";exit(0);
722
+		return $rules_ret;
723
+	}
724
+    
725
+	/** Add rule match to rule
726
+	 *	@param id int : rule id
727
+	 *   @param set int : value to set
728
+	 */
729
+	protected function add_rule_match($id, $set)
730
+	{
731
+		$db_conn=$this->trapsDB->db_connect_trap();
732
+		$sql="UPDATE ".$this->dbPrefix."rules SET num_match = '".$set."' WHERE (id = '".$id."');";
733
+		if ($db_conn->query($sql) === false) {
734
+			$this->logging->log('Error in update query : ' . $sql,WARN,'');
735
+		}
736
+	}
737
+    
738
+	/** Send SERVICE_CHECK_RESULT with icinga2cmd or API
739
+	 *
740
+	 * @param string $host
741
+	 * @param string $service
742
+	 * @param integer $state numerical staus
743
+	 * @param string $display
744
+	 * @returnn bool true is service check was sent without error
745
+	 */
746
+	public function serviceCheckResult($host,$service,$state,$display)
747
+	{
748
+		if ($this->apiUse === false)
749
+		{
750
+			$send = '[' . date('U') .'] PROCESS_SERVICE_CHECK_RESULT;' .
751
+				$host.';' .$service .';' . $state . ';'.$display;
752
+				$this->logging->log( $send." : to : " .$this->icinga2cmd,INFO );
753 753
                 
754
-                // TODO : file_put_contents & fopen (,'w' or 'a') does not work. See why. Or not as using API will be by default....
755
-                exec('echo "'.$send.'" > ' .$this->icinga2cmd);
756
-                return true;
757
-        }
758
-        else
759
-        {
760
-            // Get perfdata if found
761
-            $matches=array();
762
-            if (preg_match('/(.*)\|(.*)/',$display,$matches) == 1)
763
-            {
764
-                $display=$matches[1];
765
-                $perfdata=$matches[2];
766
-            }
767
-            else
768
-            {
769
-                $perfdata='';
770
-            }
754
+				// TODO : file_put_contents & fopen (,'w' or 'a') does not work. See why. Or not as using API will be by default....
755
+				exec('echo "'.$send.'" > ' .$this->icinga2cmd);
756
+				return true;
757
+		}
758
+		else
759
+		{
760
+			// Get perfdata if found
761
+			$matches=array();
762
+			if (preg_match('/(.*)\|(.*)/',$display,$matches) == 1)
763
+			{
764
+				$display=$matches[1];
765
+				$perfdata=$matches[2];
766
+			}
767
+			else
768
+			{
769
+				$perfdata='';
770
+			}
771 771
             
772
-            $api = $this->getAPI();
773
-            $api->setCredentials($this->apiUsername, $this->apiPassword);
774
-            list($retcode,$retmessage)=$api->serviceCheckResult($host,$service,$state,$display,$perfdata);
775
-            if ($retcode == false)
776
-            {
777
-                $this->logging->log( "Error sending result : " .$retmessage,WARN,'');
778
-                return false;
779
-            }
780
-            else
781
-            {
782
-                $this->logging->log( "Sent result : " .$retmessage,INFO );
783
-                return true;
784
-            }
785
-        }
786
-    }
787
-    
788
-    public function getHostByIP($ip)
789
-    {
790
-        $api = $this->getAPI();
791
-        $api->setCredentials($this->apiUsername, $this->apiPassword);
792
-        return $api->getHostByIP($ip);
793
-    }
794
-    
795
-    /** Resolve display.
796
-     *	Changes _OID(<oid>) to value if found or text "<not in trap>"
797
-     *	@param $display string
798
-     *	@return string display
799
-     */
800
-    protected function applyDisplay($display)
801
-    {
802
-        $matches=array();
803
-        while (preg_match('/_OID\(([0-9\.]+)\)/',$display,$matches) == 1)
804
-        {
805
-            $oid=$matches[1];
806
-            $found=0;
807
-            foreach($this->trapDataExt as $val)
808
-            {
809
-                if ($oid == $val->oid)
810
-                {
811
-                    $val->value=preg_replace('/"/','',$val->value);
812
-                    $rep=0;
813
-                    $display=preg_replace('/_OID\('.$oid.'\)/',$val->value,$display,-1,$rep);
814
-                    if ($rep==0)
815
-                    {
816
-                        $this->logging->log("Error in display",WARN,'');
817
-                        return $display;
818
-                    }
819
-                    $found=1;
820
-                    break;
821
-                }
822
-            }
823
-            if ($found==0)
824
-            {
825
-                $display=preg_replace('/_OID\('.$oid.'\)/','<not in trap>',$display,-1,$rep);
826
-                if ($rep==0)
827
-                {
828
-                    $this->logging->log("Error in display",WARN,'');
829
-                    return $display;
830
-                }
831
-            }
832
-        }
833
-        return $display;
834
-    }
835
-    
836
-    /** Match rules for current trap and do action
837
-     */
838
-    public function applyRules()
839
-    {
840
-        $rules = $this->getRules($this->trapData['source_ip'],$this->trapData['trap_oid']);
841
-        
842
-        if ($rules===false || count($rules)==0)
843
-        {
844
-            $this->logging->log('No rules found for this trap',INFO );
845
-            $this->trapData['status']='unknown';
846
-            $this->trapToDb=true;
847
-            return;
848
-        }
849
-        //print_r($rules);
850
-        // Evaluate all rules in sequence
851
-        $this->trapAction=null;
852
-        foreach ($rules as $rule)
853
-        {
772
+			$api = $this->getAPI();
773
+			$api->setCredentials($this->apiUsername, $this->apiPassword);
774
+			list($retcode,$retmessage)=$api->serviceCheckResult($host,$service,$state,$display,$perfdata);
775
+			if ($retcode == false)
776
+			{
777
+				$this->logging->log( "Error sending result : " .$retmessage,WARN,'');
778
+				return false;
779
+			}
780
+			else
781
+			{
782
+				$this->logging->log( "Sent result : " .$retmessage,INFO );
783
+				return true;
784
+			}
785
+		}
786
+	}
787
+    
788
+	public function getHostByIP($ip)
789
+	{
790
+		$api = $this->getAPI();
791
+		$api->setCredentials($this->apiUsername, $this->apiPassword);
792
+		return $api->getHostByIP($ip);
793
+	}
794
+    
795
+	/** Resolve display.
796
+	 *	Changes _OID(<oid>) to value if found or text "<not in trap>"
797
+	 *	@param $display string
798
+	 *	@return string display
799
+	 */
800
+	protected function applyDisplay($display)
801
+	{
802
+		$matches=array();
803
+		while (preg_match('/_OID\(([0-9\.]+)\)/',$display,$matches) == 1)
804
+		{
805
+			$oid=$matches[1];
806
+			$found=0;
807
+			foreach($this->trapDataExt as $val)
808
+			{
809
+				if ($oid == $val->oid)
810
+				{
811
+					$val->value=preg_replace('/"/','',$val->value);
812
+					$rep=0;
813
+					$display=preg_replace('/_OID\('.$oid.'\)/',$val->value,$display,-1,$rep);
814
+					if ($rep==0)
815
+					{
816
+						$this->logging->log("Error in display",WARN,'');
817
+						return $display;
818
+					}
819
+					$found=1;
820
+					break;
821
+				}
822
+			}
823
+			if ($found==0)
824
+			{
825
+				$display=preg_replace('/_OID\('.$oid.'\)/','<not in trap>',$display,-1,$rep);
826
+				if ($rep==0)
827
+				{
828
+					$this->logging->log("Error in display",WARN,'');
829
+					return $display;
830
+				}
831
+			}
832
+		}
833
+		return $display;
834
+	}
835
+    
836
+	/** Match rules for current trap and do action
837
+	 */
838
+	public function applyRules()
839
+	{
840
+		$rules = $this->getRules($this->trapData['source_ip'],$this->trapData['trap_oid']);
841
+        
842
+		if ($rules===false || count($rules)==0)
843
+		{
844
+			$this->logging->log('No rules found for this trap',INFO );
845
+			$this->trapData['status']='unknown';
846
+			$this->trapToDb=true;
847
+			return;
848
+		}
849
+		//print_r($rules);
850
+		// Evaluate all rules in sequence
851
+		$this->trapAction=null;
852
+		foreach ($rules as $rule)
853
+		{
854 854
             
855
-            $host_name=$rule['host_name'];
856
-            $service_name=$rule['service_name'];
855
+			$host_name=$rule['host_name'];
856
+			$service_name=$rule['service_name'];
857 857
             
858
-            $display=$this->applyDisplay($rule['display']);
859
-            $this->trapAction = ($this->trapAction==null)? '' : $this->trapAction . ', ';
860
-            try
861
-            {
862
-                $this->logging->log('Rule to eval : '.$rule['rule'],INFO );
863
-                $evalr=$this->ruleClass->eval_rule($rule['rule'], $this->trapDataExt) ;
864
-                //->eval_rule($rule['rule']);
858
+			$display=$this->applyDisplay($rule['display']);
859
+			$this->trapAction = ($this->trapAction==null)? '' : $this->trapAction . ', ';
860
+			try
861
+			{
862
+				$this->logging->log('Rule to eval : '.$rule['rule'],INFO );
863
+				$evalr=$this->ruleClass->eval_rule($rule['rule'], $this->trapDataExt) ;
864
+				//->eval_rule($rule['rule']);
865 865
                 
866
-                if ($evalr == true)
867
-                {
868
-                    //$this->logging->log('rules OOK: '.print_r($rule),INFO );
869
-                    $action=$rule['action_match'];
870
-                    $this->logging->log('action OK : '.$action,INFO );
871
-                    if ($action >= 0)
872
-                    {
873
-                        if ($this->serviceCheckResult($host_name,$service_name,$action,$display) == false)
874
-                        {
875
-                            $this->trapAction.='Error sending status : check cmd/API';
876
-                        }
877
-                        else
878
-                        {
879
-                            $this->add_rule_match($rule['id'],$rule['num_match']+1);
880
-                            $this->trapAction.='Status '.$action.' to '.$host_name.'/'.$service_name;
881
-                        }
882
-                    }
883
-                    else
884
-                    {
885
-                        $this->add_rule_match($rule['id'],$rule['num_match']+1);
886
-                    }
887
-                    $this->trapToDb=($action==-2)?false:true;
888
-                }
889
-                else
890
-                {
891
-                    //$this->logging->log('rules KOO : '.print_r($rule),INFO );
866
+				if ($evalr == true)
867
+				{
868
+					//$this->logging->log('rules OOK: '.print_r($rule),INFO );
869
+					$action=$rule['action_match'];
870
+					$this->logging->log('action OK : '.$action,INFO );
871
+					if ($action >= 0)
872
+					{
873
+						if ($this->serviceCheckResult($host_name,$service_name,$action,$display) == false)
874
+						{
875
+							$this->trapAction.='Error sending status : check cmd/API';
876
+						}
877
+						else
878
+						{
879
+							$this->add_rule_match($rule['id'],$rule['num_match']+1);
880
+							$this->trapAction.='Status '.$action.' to '.$host_name.'/'.$service_name;
881
+						}
882
+					}
883
+					else
884
+					{
885
+						$this->add_rule_match($rule['id'],$rule['num_match']+1);
886
+					}
887
+					$this->trapToDb=($action==-2)?false:true;
888
+				}
889
+				else
890
+				{
891
+					//$this->logging->log('rules KOO : '.print_r($rule),INFO );
892 892
                     
893
-                    $action=$rule['action_nomatch'];
894
-                    $this->logging->log('action NOK : '.$action,INFO );
895
-                    if ($action >= 0)
896
-                    {
897
-                        if ($this->serviceCheckResult($host_name,$service_name,$action,$display)==false)
898
-                        {
899
-                            $this->trapAction.='Error sending status : check cmd/API';
900
-                        }
901
-                        else
902
-                        {
903
-                            $this->add_rule_match($rule['id'],$rule['num_match']+1);
904
-                            $this->trapAction.='Status '.$action.' to '.$host_name.'/'.$service_name;
905
-                        }
906
-                    }
907
-                    else
908
-                    {
909
-                        $this->add_rule_match($rule['id'],$rule['num_match']+1);
910
-                    }
911
-                    $this->trapToDb=($action==-2)?false:true;
912
-                }
913
-                // Put name in source_name
914
-                if (!isset($this->trapData['source_name']))
915
-                {
916
-                    $this->trapData['source_name']=$rule['host_name'];
917
-                }
918
-                else
919
-                {
920
-                    if (!preg_match('/'.$rule['host_name'].'/',$this->trapData['source_name']))
921
-                    { // only add if not present
922
-                        $this->trapData['source_name'].=','.$rule['host_name'];
923
-                    }
924
-                }
925
-            }
926
-            catch (Exception $e)
927
-            {
928
-                $this->logging->log('Error in rule eval : '.$e->getMessage(),WARN,'');
929
-                $this->trapAction.=' ERR : '.$e->getMessage();
930
-                $this->trapData['status']='error';
931
-            }
893
+					$action=$rule['action_nomatch'];
894
+					$this->logging->log('action NOK : '.$action,INFO );
895
+					if ($action >= 0)
896
+					{
897
+						if ($this->serviceCheckResult($host_name,$service_name,$action,$display)==false)
898
+						{
899
+							$this->trapAction.='Error sending status : check cmd/API';
900
+						}
901
+						else
902
+						{
903
+							$this->add_rule_match($rule['id'],$rule['num_match']+1);
904
+							$this->trapAction.='Status '.$action.' to '.$host_name.'/'.$service_name;
905
+						}
906
+					}
907
+					else
908
+					{
909
+						$this->add_rule_match($rule['id'],$rule['num_match']+1);
910
+					}
911
+					$this->trapToDb=($action==-2)?false:true;
912
+				}
913
+				// Put name in source_name
914
+				if (!isset($this->trapData['source_name']))
915
+				{
916
+					$this->trapData['source_name']=$rule['host_name'];
917
+				}
918
+				else
919
+				{
920
+					if (!preg_match('/'.$rule['host_name'].'/',$this->trapData['source_name']))
921
+					{ // only add if not present
922
+						$this->trapData['source_name'].=','.$rule['host_name'];
923
+					}
924
+				}
925
+			}
926
+			catch (Exception $e)
927
+			{
928
+				$this->logging->log('Error in rule eval : '.$e->getMessage(),WARN,'');
929
+				$this->trapAction.=' ERR : '.$e->getMessage();
930
+				$this->trapData['status']='error';
931
+			}
932 932
             
933
-        }
934
-        if ($this->trapData['status']=='error')
935
-        {
936
-            $this->trapToDb=true; // Always put errors in DB for the use can see
937
-        }
938
-        else
939
-        {
940
-            $this->trapData['status']='done';
941
-        }
942
-    }
943
-    
944
-    /** Add Time a action to rule
945
-     *	@param string $time : time to process to insert in SQL
946
-     */
947
-    public function add_rule_final($time)
948
-    {
949
-        $db_conn=$this->trapsDB->db_connect_trap();
950
-        if ($this->trapAction==null)
951
-        {
952
-            $this->trapAction='No action';
953
-        }
954
-        $sql="UPDATE ".$this->dbPrefix."received SET process_time = '".$time."' , status_detail='".$this->trapAction."'  WHERE (id = '".$this->trapId."');";
955
-        if ($db_conn->query($sql) === false) {
956
-            $this->logging->log('Error in update query : ' . $sql,WARN,'');
957
-        }
958
-    }
959
-    
960
-    /*********** UTILITIES *********************/
961
-    
962
-    /** reset service to OK after time defined in rule
963
-     *	TODO logic is : get all service in error + all rules, see if getting all rules then select services is better
964
-     *	@return integer : not in use
965
-     **/
966
-    public function reset_services()
967
-    {
968
-        // Get all services not in 'ok' state
969
-        $sql_query="SELECT s.service_object_id,
933
+		}
934
+		if ($this->trapData['status']=='error')
935
+		{
936
+			$this->trapToDb=true; // Always put errors in DB for the use can see
937
+		}
938
+		else
939
+		{
940
+			$this->trapData['status']='done';
941
+		}
942
+	}
943
+    
944
+	/** Add Time a action to rule
945
+	 *	@param string $time : time to process to insert in SQL
946
+	 */
947
+	public function add_rule_final($time)
948
+	{
949
+		$db_conn=$this->trapsDB->db_connect_trap();
950
+		if ($this->trapAction==null)
951
+		{
952
+			$this->trapAction='No action';
953
+		}
954
+		$sql="UPDATE ".$this->dbPrefix."received SET process_time = '".$time."' , status_detail='".$this->trapAction."'  WHERE (id = '".$this->trapId."');";
955
+		if ($db_conn->query($sql) === false) {
956
+			$this->logging->log('Error in update query : ' . $sql,WARN,'');
957
+		}
958
+	}
959
+    
960
+	/*********** UTILITIES *********************/
961
+    
962
+	/** reset service to OK after time defined in rule
963
+	 *	TODO logic is : get all service in error + all rules, see if getting all rules then select services is better
964
+	 *	@return integer : not in use
965
+	 **/
966
+	public function reset_services()
967
+	{
968
+		// Get all services not in 'ok' state
969
+		$sql_query="SELECT s.service_object_id,
970 970
 	 UNIX_TIMESTAMP(s.last_check) AS last_check,
971 971
 	s.current_state as state,
972 972
 	v.name1 as host_name,
@@ -974,43 +974,43 @@  discard block
 block discarded – undo
974 974
 	FROM icinga_servicestatus AS s
975 975
     LEFT JOIN icinga_objects as v ON s.service_object_id=v.object_id
976 976
     WHERE s.current_state != 0;";
977
-        $db_conn=$this->trapsDB->db_connect_ido();
978
-        if (($services_db=$db_conn->query($sql_query)) === false) { // set err to 1 to throw exception.
979
-            $this->logging->log('No result in query : ' . $sql_query,ERROR,'');
980
-            return 0;
981
-        }
982
-        $services=$services_db->fetchAll();
983
-        
984
-        // Get all rules
985
-        $sql_query="SELECT host_name, service_name, revert_ok FROM ".$this->dbPrefix."rules where revert_ok != 0;";
986
-        $db_conn2=$this->trapsDB->db_connect_trap();
987
-        if (($rules_db=$db_conn2->query($sql_query)) === false) {
988
-            $this->logging->log('No result in query : ' . $sql_query,ERROR,'');
989
-            return 0;
990
-        }
991
-        $rules=$rules_db->fetchAll();
992
-        
993
-        $now=date('U');
994
-        
995
-        $numreset=0;
996
-        foreach ($rules as $rule)
997
-        {
998
-            foreach ($services as $service)
999
-            {
1000
-                if ($service['service_name'] == $rule['service_name'] &&
1001
-                    $service['host_name'] == $rule['host_name'] &&
1002
-                    ($service['last_check'] + $rule['revert_ok']) < $now)
1003
-                {
1004
-                    $this->serviceCheckResult($service['host_name'],$service['service_name'],0,'Reset service to OK after '.$rule['revert_ok'].' seconds');
1005
-                    $numreset++;
1006
-                }
1007
-            }
1008
-        }
1009
-        echo "\n";
1010
-        echo $numreset . " service(s) reset to OK\n";
1011
-        return 0;
1012
-        
1013
-    }
977
+		$db_conn=$this->trapsDB->db_connect_ido();
978
+		if (($services_db=$db_conn->query($sql_query)) === false) { // set err to 1 to throw exception.
979
+			$this->logging->log('No result in query : ' . $sql_query,ERROR,'');
980
+			return 0;
981
+		}
982
+		$services=$services_db->fetchAll();
983
+        
984
+		// Get all rules
985
+		$sql_query="SELECT host_name, service_name, revert_ok FROM ".$this->dbPrefix."rules where revert_ok != 0;";
986
+		$db_conn2=$this->trapsDB->db_connect_trap();
987
+		if (($rules_db=$db_conn2->query($sql_query)) === false) {
988
+			$this->logging->log('No result in query : ' . $sql_query,ERROR,'');
989
+			return 0;
990
+		}
991
+		$rules=$rules_db->fetchAll();
992
+        
993
+		$now=date('U');
994
+        
995
+		$numreset=0;
996
+		foreach ($rules as $rule)
997
+		{
998
+			foreach ($services as $service)
999
+			{
1000
+				if ($service['service_name'] == $rule['service_name'] &&
1001
+					$service['host_name'] == $rule['host_name'] &&
1002
+					($service['last_check'] + $rule['revert_ok']) < $now)
1003
+				{
1004
+					$this->serviceCheckResult($service['host_name'],$service['service_name'],0,'Reset service to OK after '.$rule['revert_ok'].' seconds');
1005
+					$numreset++;
1006
+				}
1007
+			}
1008
+		}
1009
+		echo "\n";
1010
+		echo $numreset . " service(s) reset to OK\n";
1011
+		return 0;
1012
+        
1013
+	}
1014 1014
     
1015 1015
     
1016 1016
 }
1017 1017
\ No newline at end of file
Please login to merge, or discard this patch.