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