Passed
Push — master ( ff53ce...185c6a )
by Patrick
01:57
created
library/Trapdirector/TrapsController.php 3 patches
Indentation   +116 added lines, -116 removed lines patch added patch discarded remove patch
@@ -32,8 +32,8 @@  discard block
 block discarded – undo
32 32
 	protected $trapClass;		//< Trap class for bin/trap_class.php
33 33
 		
34 34
 	/** Get instance of TrapModuleConfig class
35
-	*	@return TrapModuleConfig
36
-	*/
35
+	 *	@return TrapModuleConfig
36
+	 */
37 37
 	public function getModuleConfig() 
38 38
 	{
39 39
 		if ($this->moduleConfig == Null) 
@@ -58,12 +58,12 @@  discard block
 block discarded – undo
58 58
 	
59 59
 	public function getTrapHostListTable()
60 60
 	{
61
-	    if ($this->trapTableHostList == Null) 
61
+		if ($this->trapTableHostList == Null) 
62 62
 		{
63
-	        $this->trapTableHostList = new TrapTableHostList();
64
-	        $this->trapTableHostList->setConfig($this->getModuleConfig());
65
-	    }
66
-	    return $this->trapTableHostList;
63
+			$this->trapTableHostList = new TrapTableHostList();
64
+			$this->trapTableHostList->setConfig($this->getModuleConfig());
65
+		}
66
+		return $this->trapTableHostList;
67 67
 	}
68 68
 	
69 69
 	public function getHandlerListTable() 
@@ -77,11 +77,11 @@  discard block
 block discarded – undo
77 77
 	}	
78 78
 	
79 79
 	/**	Get Database connexion
80
-	*	@param $DBname string DB name in resource.ini_ge
81
-	*	@param $test bool if set to true, returns error code and not database
82
-	*	@param $test_version bool if set to flase, does not test database version of trapDB
83
-	*	@return array<integer,mixed>|mixed : if test=false, returns DB connexion, else array(error_num,message) or null on error.
84
-	*/
80
+	 *	@param $DBname string DB name in resource.ini_ge
81
+	 *	@param $test bool if set to true, returns error code and not database
82
+	 *	@param $test_version bool if set to flase, does not test database version of trapDB
83
+	 *	@return array<integer,mixed>|mixed : if test=false, returns DB connexion, else array(error_num,message) or null on error.
84
+	 */
85 85
 	public function getDbByName($DBname,$test=false,$test_version=true)
86 86
 	{
87 87
 		try 
@@ -166,20 +166,20 @@  discard block
 block discarded – undo
166 166
 
167 167
 		if ( ! $dbresource )
168 168
 		{
169
-		    if ($test) return array(1,'No database in config.ini');
170
-		    $this->redirectNow('trapdirector/settings?idodberror=1');
171
-		    return null;
169
+			if ($test) return array(1,'No database in config.ini');
170
+			$this->redirectNow('trapdirector/settings?idodberror=1');
171
+			return null;
172 172
 		}
173 173
 		
174 174
 		try
175 175
 		{
176
-		    $dbconn = IcingaDbConnection::fromResourceName($dbresource);
176
+			$dbconn = IcingaDbConnection::fromResourceName($dbresource);
177 177
 		}
178 178
 		catch (Exception $e)
179 179
 		{
180
-		    if ($test) return array(2,"Database $dbresource does not exists in IcingaWeb2");
181
-		    $this->redirectNow('trapdirector/settings?idodberror=2');
182
-		    return null;
180
+			if ($test) return array(2,"Database $dbresource does not exists in IcingaWeb2");
181
+			$this->redirectNow('trapdirector/settings?idodberror=2');
182
+			return null;
183 183
 		}
184 184
 		
185 185
 		if ($test == false) 
@@ -190,13 +190,13 @@  discard block
 block discarded – undo
190 190
 		
191 191
 		try
192 192
 		{
193
-		    $query = $dbconn->select()
194
-		    ->from('icinga_dbversion',array('version'));
195
-		    $version=$dbconn->fetchRow($query);
196
-		    if ( ($version == null) || ! property_exists($version,'version') )
197
-		    {
198
-		        return array(4,"$dbresource does not look like an IDO database");
199
-		    }
193
+			$query = $dbconn->select()
194
+			->from('icinga_dbversion',array('version'));
195
+			$version=$dbconn->fetchRow($query);
196
+			if ( ($version == null) || ! property_exists($version,'version') )
197
+			{
198
+				return array(4,"$dbresource does not look like an IDO database");
199
+			}
200 200
 		}
201 201
 		catch (Exception $e)
202 202
 		{
@@ -206,15 +206,15 @@  discard block
 block discarded – undo
206 206
 		return array(0,'');
207 207
 	}
208 208
 	
209
-    protected function applyPaginationLimits(Paginatable $paginatable, $limit = 25, $offset = null)
210
-    {
211
-        $limit = $this->params->get('limit', $limit);
212
-        $page = $this->params->get('page', $offset);
209
+	protected function applyPaginationLimits(Paginatable $paginatable, $limit = 25, $offset = null)
210
+	{
211
+		$limit = $this->params->get('limit', $limit);
212
+		$page = $this->params->get('page', $offset);
213 213
 
214
-        $paginatable->limit($limit, $page > 0 ? ($page - 1) * $limit : 0);
214
+		$paginatable->limit($limit, $page > 0 ? ($page - 1) * $limit : 0);
215 215
 
216
-        return $paginatable;
217
-    }	
216
+		return $paginatable;
217
+	}	
218 218
 	
219 219
 	public function displayExitError($source,$message)
220 220
 	{	// TODO : check better ways to transmit data (with POST ?)
@@ -223,33 +223,33 @@  discard block
 block discarded – undo
223 223
 	
224 224
 	protected function checkReadPermission()
225 225
 	{
226
-        if (! $this->Auth()->hasPermission('trapdirector/view')) {
227
-            $this->displayExitError('Permissions','No permission fo view content');
228
-        }		
226
+		if (! $this->Auth()->hasPermission('trapdirector/view')) {
227
+			$this->displayExitError('Permissions','No permission fo view content');
228
+		}		
229 229
 	}
230 230
 
231 231
 	protected function checkConfigPermission()
232 232
 	{
233
-        if (! $this->Auth()->hasPermission('trapdirector/config')) {
234
-            $this->displayExitError('Permissions','No permission fo configure');
235
-        }		
233
+		if (! $this->Auth()->hasPermission('trapdirector/config')) {
234
+			$this->displayExitError('Permissions','No permission fo configure');
235
+		}		
236 236
 	}
237 237
 	
238
-    /**
239
-     * Check if user has write permission
240
-     * @param number $check optional : if set to 1, return true (user has permission) or false instead of displaying error page
241
-     * @return boolean : user has permission
242
-     */
238
+	/**
239
+	 * Check if user has write permission
240
+	 * @param number $check optional : if set to 1, return true (user has permission) or false instead of displaying error page
241
+	 * @return boolean : user has permission
242
+	 */
243 243
 	protected function checkModuleConfigPermission($check=0)
244 244
 	{
245
-        if (! $this->Auth()->hasPermission('trapdirector/module_config')) {
246
-            if ($check == 0)
247
-            {
248
-                $this->displayExitError('Permissions','No permission fo configure module');
249
-            }
250
-            return false;
251
-        }
252
-        return true;
245
+		if (! $this->Auth()->hasPermission('trapdirector/module_config')) {
246
+			if ($check == 0)
247
+			{
248
+				$this->displayExitError('Permissions','No permission fo configure module');
249
+			}
250
+			return false;
251
+		}
252
+		return true;
253 253
 	}
254 254
 
255 255
 	/*************************  Trap class get **********************/
@@ -269,8 +269,8 @@  discard block
 block discarded – undo
269 269
 	/************************** MIB related **************************/
270 270
 	
271 271
 	/** Get MIBLoader class
272
-	*	@return MIBLoader class
273
-	*/
272
+	 *	@return MIBLoader class
273
+	 */
274 274
 	protected function getMIB()
275 275
 	{
276 276
 		if ($this->MIBData == null)
@@ -288,9 +288,9 @@  discard block
 block discarded – undo
288 288
 	/**************************  Database queries *******************/
289 289
 	
290 290
 	/** Get host(s) by IP (v4 or v6) or by name in IDO database
291
-	*	does not catch exceptions
292
-	*	@return array of objects ( name, id (object_id), display_name)
293
-	*/
291
+	 *	does not catch exceptions
292
+	 *	@return array of objects ( name, id (object_id), display_name)
293
+	 */
294 294
 	protected function getHostByIP($ip) 
295 295
 	{
296 296
 		// select a.name1, b.display_name from icinga.icinga_objects AS a , icinga.icinga_hosts AS b WHERE (b.address = '192.168.56.101' OR b.address6= '123456') and b.host_object_id=a.object_id
@@ -309,9 +309,9 @@  discard block
 block discarded – undo
309 309
 	}
310 310
 
311 311
 	/** Get host(s) by name in IDO database
312
-	*	does not catch exceptions
313
-	*	@return array of objects ( name, id (object_id), display_name)
314
-	*/
312
+	 *	does not catch exceptions
313
+	 *	@return array of objects ( name, id (object_id), display_name)
314
+	 */
315 315
 	protected function getHostByName($name) 
316 316
 	{
317 317
 		// select a.name1, b.display_name from icinga.icinga_objects AS a , icinga.icinga_hosts AS b WHERE (b.address = '192.168.56.101' OR b.address6= '123456') and b.host_object_id=a.object_id
@@ -330,9 +330,9 @@  discard block
 block discarded – undo
330 330
 	}	
331 331
 	
332 332
 	/** Get host groups by  name in IDO database
333
-	*	does not catch exceptions
334
-	*	@return array of objects ( name, id (object_id), display_name)
335
-	*/
333
+	 *	does not catch exceptions
334
+	 *	@return array of objects ( name, id (object_id), display_name)
335
+	 */
336 336
 	protected function getHostGroupByName($ip) 
337 337
 	{
338 338
 		// select a.name1, b.display_name from icinga.icinga_objects AS a , icinga.icinga_hosts AS b WHERE (b.address = '192.168.56.101' OR b.address6= '123456') and b.host_object_id=a.object_id
@@ -352,9 +352,9 @@  discard block
 block discarded – undo
352 352
 
353 353
 	
354 354
 	/** Get host IP (v4 and v6) by name in IDO database
355
-	*	does not catch exceptions
356
-	*	@return array ( name, display_name, ip4, ip6)
357
-	*/
355
+	 *	does not catch exceptions
356
+	 *	@return array ( name, display_name, ip4, ip6)
357
+	 */
358 358
 	protected function getHostInfoByID($id) 
359 359
 	{
360 360
 		if (!preg_match('/^[0-9]+$/',$id)) { throw new Exception('Invalid id');  }
@@ -373,9 +373,9 @@  discard block
 block discarded – undo
373 373
 
374 374
 	
375 375
 	/** Get host by objectid  in IDO database
376
-	*	does not catch exceptions
377
-	*	@return array of objects ( id, name, display_name, ip, ip6,  )
378
-	*/
376
+	 *	does not catch exceptions
377
+	 *	@return array of objects ( id, name, display_name, ip, ip6,  )
378
+	 */
379 379
 	protected function getHostByObjectID($id) // TODO : duplicate of getHostInfoByID above
380 380
 	{
381 381
 		if (!preg_match('/^[0-9]+$/',$id)) { throw new Exception('Invalid id');  }
@@ -393,10 +393,10 @@  discard block
 block discarded – undo
393 393
 	}	
394 394
 	
395 395
 	/** Get services from object ( host_object_id) in IDO database
396
-	*	does not catch exceptions
397
-	*	@param $id	int object_id
398
-	*	@return array display_name (of service), service_object_id
399
-	*/
396
+	 *	does not catch exceptions
397
+	 *	@param $id	int object_id
398
+	 *	@return array display_name (of service), service_object_id
399
+	 */
400 400
 	protected function getServicesByHostid($id) 
401 401
 	{
402 402
 		// select a.name1, b.display_name from icinga.icinga_objects AS a , icinga.icinga_hosts AS b WHERE (b.address = '192.168.56.101' OR b.address6= '123456') and b.host_object_id=a.object_id
@@ -416,11 +416,11 @@  discard block
 block discarded – undo
416 416
 	}	
417 417
 	
418 418
 	/** Get services from hostgroup object id ( hostgroup_object_id) in IDO database
419
-	* 	gets all hosts in hostgroup and return common services
420
-	*	does not catch exceptions
421
-	*	@param $id	int object_id
422
-	*	@return array display_name (of service), service_object_id
423
-	*/
419
+	 * 	gets all hosts in hostgroup and return common services
420
+	 *	does not catch exceptions
421
+	 *	@param $id	int object_id
422
+	 *	@return array display_name (of service), service_object_id
423
+	 */
424 424
 	protected function getServicesByHostGroupid($id) 
425 425
 	{		
426 426
 		if (!preg_match('/^[0-9]+$/',$id)) { throw new Exception('Invalid id');  }
@@ -459,7 +459,7 @@  discard block
 block discarded – undo
459 459
 		//print_r($common_services);
460 460
 		foreach (array_keys($common_services) as $key)
461 461
 		{
462
-		    if ($common_services[$key]['num'] == $num_hosts)
462
+			if ($common_services[$key]['num'] == $num_hosts)
463 463
 			{
464 464
 				array_push($result,array($key,$common_services[$key]['name']));
465 465
 			}
@@ -469,11 +469,11 @@  discard block
 block discarded – undo
469 469
 	}	
470 470
 
471 471
 	/** Get services object id by host name / service name in IDO database
472
-	*	does not catch exceptions
473
-	*	@param $hostname string host name
474
-	*	@param $name string service name
475
-	*	@return array  service id
476
-	*/
472
+	 *	does not catch exceptions
473
+	 *	@param $hostname string host name
474
+	 *	@param $name string service name
475
+	 *	@return array  service id
476
+	 */
477 477
 	protected function getServiceIDByName($hostname,$name) 
478 478
 	{
479 479
 		$db = $this->getIdoDb()->getConnection();
@@ -496,10 +496,10 @@  discard block
 block discarded – undo
496 496
 	}
497 497
 	
498 498
 	/** Get object name from object_id  in IDO database
499
-	*	does not catch exceptions
500
-	*	@param int $id object_id (default to null, used first if not null)
501
-	*	@return array name1 (host) name2 (service)
502
-	*/
499
+	 *	does not catch exceptions
500
+	 *	@param int $id object_id (default to null, used first if not null)
501
+	 *	@return array name1 (host) name2 (service)
502
+	 */
503 503
 	protected function getObjectNameByid($id) 
504 504
 	{
505 505
 		// select a.name1, b.display_name from icinga.icinga_objects AS a , icinga.icinga_hosts AS b WHERE (b.address = '192.168.56.101' OR b.address6= '123456') and b.host_object_id=a.object_id
@@ -515,9 +515,9 @@  discard block
 block discarded – undo
515 515
 	}		
516 516
 
517 517
 	/** Add handler rule in traps DB
518
-	*	@param array $params : array(<db item>=><value>)
519
-	*	@return int inserted id
520
-	*/
518
+	 *	@param array $params : array(<db item>=><value>)
519
+	 *	@return int inserted id
520
+	 */
521 521
 	protected function addHandlerRule($params)
522 522
 	{
523 523
 		// TODO Check for rule consistency
@@ -539,10 +539,10 @@  discard block
 block discarded – undo
539 539
 	}	
540 540
 
541 541
 	/** Update handler rule in traps DB
542
-	*	@param array $params : (<db item>=><value>)
543
-	*   @param integer $ruleID : rule id in db
544
-	*	@return array affected rows
545
-	*/
542
+	 *	@param array $params : (<db item>=><value>)
543
+	 *   @param integer $ruleID : rule id in db
544
+	 *	@return array affected rows
545
+	 */
546 546
 	protected function updateHandlerRule($params,$ruleID)
547 547
 	{
548 548
 		// TODO Check for rule consistency
@@ -560,8 +560,8 @@  discard block
 block discarded – undo
560 560
 	}	
561 561
 	
562 562
 	/** Delete rule by id
563
-	*	@param int $ruleID rule id
564
-	*/
563
+	 *	@param int $ruleID rule id
564
+	 */
565 565
 	protected function deleteRule($ruleID)
566 566
 	{
567 567
 		if (!preg_match('/^[0-9]+$/',$ruleID)) { throw new Exception('Invalid id');  }
@@ -575,9 +575,9 @@  discard block
 block discarded – undo
575 575
 	}
576 576
 
577 577
 	/** Delete trap by ip & oid
578
-	*	@param $ip string source IP (v4 or v6)
579
-	*	@param $oid string oid
580
-	*/
578
+	 *	@param $ip string source IP (v4 or v6)
579
+	 *	@param $oid string oid
580
+	 */
581 581
 	protected function deleteTrap($ip,$oid)
582 582
 	{
583 583
 		
@@ -603,9 +603,9 @@  discard block
 block discarded – undo
603 603
    
604 604
 
605 605
 	/** count trap by ip & oid
606
-	*	@param $ip string source IP (v4 or v6)
607
-	*	@param $oid string oid
608
-	*/
606
+	 *	@param $ip string source IP (v4 or v6)
607
+	 *	@param $oid string oid
608
+	 */
609 609
 	protected function countTrap($ip,$oid)
610 610
 	{
611 611
 		
@@ -631,8 +631,8 @@  discard block
 block discarded – undo
631 631
 	}		
632 632
 	
633 633
 	/** get configuration value
634
-	*	@param string $element : configuration name in db
635
-	*/
634
+	 *	@param string $element : configuration name in db
635
+	 */
636 636
 	protected function getDBConfigValue($element)
637 637
 	{
638 638
 	
@@ -663,9 +663,9 @@  discard block
 block discarded – undo
663 663
 	}
664 664
 
665 665
 	/** add configuration value
666
-	*	@param string $element : name of config element
667
-	*   @param string $value : value
668
-	*/
666
+	 *	@param string $element : name of config element
667
+	 *   @param string $value : value
668
+	 */
669 669
 		
670 670
 	protected function addDBConfigValue($element,$value)
671 671
 	{
@@ -683,9 +683,9 @@  discard block
 block discarded – undo
683 683
 	}
684 684
 
685 685
 	/** set configuration value
686
-	*	@param string $element : name of config element
687
-	*   @param string $value : value
688
-	*/
686
+	 *	@param string $element : name of config element
687
+	 *   @param string $value : value
688
+	 */
689 689
 	protected function setDBConfigValue($element,$value)
690 690
 	{
691 691
 	
@@ -699,13 +699,13 @@  discard block
 block discarded – undo
699 699
 	}
700 700
 	
701 701
 	/** Check if director is installed
702
-	*	@return bool true/false
703
-	*/
702
+	 *	@return bool true/false
703
+	 */
704 704
 	protected function isDirectorInstalled()
705 705
 	{
706
-	    $output=array();
707
-	    exec('icingacli module list',$output);
708
-	    foreach ($output as $line)
706
+		$output=array();
707
+		exec('icingacli module list',$output);
708
+		foreach ($output as $line)
709 709
 		{
710 710
 			if (preg_match('/^director .*enabled/',$line))
711 711
 			{
Please login to merge, or discard this patch.
Spacing   +112 added lines, -112 removed lines patch added patch discarded remove patch
@@ -22,14 +22,14 @@  discard block
 block discarded – undo
22 22
 
23 23
 class TrapsController extends Controller
24 24
 {
25
-	protected $moduleConfig;  	//< TrapModuleConfig instance
26
-	protected $trapTableList; 	//< TrapTableList (by date)
27
-	protected $trapTableHostList; 	//< TrapTableList (by hosts)
28
-	protected $handlerTableList; 	//< HandlerTableList instance
29
-	protected $trapDB;			//< Trap database
30
-	protected $icingaDB;		//< Icinga IDO database;
31
-	protected $MIBData; 		//< MIBLoader class
32
-	protected $trapClass;		//< Trap class for bin/trap_class.php
25
+	protected $moduleConfig; //< TrapModuleConfig instance
26
+	protected $trapTableList; //< TrapTableList (by date)
27
+	protected $trapTableHostList; //< TrapTableList (by hosts)
28
+	protected $handlerTableList; //< HandlerTableList instance
29
+	protected $trapDB; //< Trap database
30
+	protected $icingaDB; //< Icinga IDO database;
31
+	protected $MIBData; //< MIBLoader class
32
+	protected $trapClass; //< Trap class for bin/trap_class.php
33 33
 		
34 34
 	/** Get instance of TrapModuleConfig class
35 35
 	*	@return TrapModuleConfig
@@ -43,14 +43,14 @@  discard block
 block discarded – undo
43 43
 			{
44 44
 				$this->redirectNow('trapdirector/settings?message=No database prefix');
45 45
 			}
46
-			$this->moduleConfig = new TrapModuleConfig($db_prefix);
46
+			$this->moduleConfig=new TrapModuleConfig($db_prefix);
47 47
 		}
48 48
 		return $this->moduleConfig;
49 49
 	}
50 50
 	
51 51
 	public function getTrapListTable() {
52 52
 		if ($this->trapTableList == Null) {
53
-			$this->trapTableList = new TrapTableList();
53
+			$this->trapTableList=new TrapTableList();
54 54
 			$this->trapTableList->setConfig($this->getModuleConfig());
55 55
 		}
56 56
 		return $this->trapTableList;
@@ -60,7 +60,7 @@  discard block
 block discarded – undo
60 60
 	{
61 61
 	    if ($this->trapTableHostList == Null) 
62 62
 		{
63
-	        $this->trapTableHostList = new TrapTableHostList();
63
+	        $this->trapTableHostList=new TrapTableHostList();
64 64
 	        $this->trapTableHostList->setConfig($this->getModuleConfig());
65 65
 	    }
66 66
 	    return $this->trapTableHostList;
@@ -70,7 +70,7 @@  discard block
 block discarded – undo
70 70
 	{
71 71
 		if ($this->handlerTableList == Null) 
72 72
 		{
73
-			$this->handlerTableList = new HandlerTableList();
73
+			$this->handlerTableList=new HandlerTableList();
74 74
 			$this->handlerTableList->setConfig($this->getModuleConfig());
75 75
 		}
76 76
 		return $this->handlerTableList;
@@ -82,15 +82,15 @@  discard block
 block discarded – undo
82 82
 	*	@param $test_version bool if set to flase, does not test database version of trapDB
83 83
 	*	@return array<integer,mixed>|mixed : if test=false, returns DB connexion, else array(error_num,message) or null on error.
84 84
 	*/
85
-	public function getDbByName($DBname,$test=false,$test_version=true)
85
+	public function getDbByName($DBname, $test=false, $test_version=true)
86 86
 	{
87 87
 		try 
88 88
 		{
89
-			$dbconn = IcingaDbConnection::fromResourceName($DBname);
89
+			$dbconn=IcingaDbConnection::fromResourceName($DBname);
90 90
 		} 
91 91
 		catch (Exception $e)
92 92
 		{
93
-			if ($test) return array(2,$DBname);
93
+			if ($test) return array(2, $DBname);
94 94
 			$this->redirectNow('trapdirector/settings?dberror=2');
95 95
 			return null;
96 96
 		}
@@ -101,37 +101,37 @@  discard block
 block discarded – undo
101 101
 			}
102 102
 			catch (Exception $e) 
103 103
 			{
104
-				if ($test) return array(3,$DBname,$e->getMessage());
104
+				if ($test) return array(3, $DBname, $e->getMessage());
105 105
 				$this->redirectNow('trapdirector/settings?dberror=3');
106 106
 				return null;
107 107
 			}
108 108
 			try
109 109
 			{
110
-				$query = $db->select()
111
-					->from($this->getModuleConfig()->getDbConfigTableName(),'value')
110
+				$query=$db->select()
111
+					->from($this->getModuleConfig()->getDbConfigTableName(), 'value')
112 112
 					->where('name=\'db_version\'');
113 113
 				$version=$db->fetchRow($query);
114
-				if ( ($version == null) || ! property_exists($version,'value') )
114
+				if (($version == null) || !property_exists($version, 'value'))
115 115
 				{
116
-					if ($test) return array(4,$DBname);
116
+					if ($test) return array(4, $DBname);
117 117
 					$this->redirectNow('trapdirector/settings?dberror=4');
118 118
 					return null;
119 119
 				}
120 120
 				if ($version->value < $this->getModuleConfig()->getDbMinVersion()) 
121 121
 				{
122
-					if ($test) return array(5,$version->value,$this->getModuleConfig()->getDbMinVersion());
122
+					if ($test) return array(5, $version->value, $this->getModuleConfig()->getDbMinVersion());
123 123
 					$this->redirectNow('trapdirector/settings?dberror=5');
124 124
 					return null;
125 125
 				}
126 126
 			}
127 127
 			catch (Exception $e) 
128 128
 			{
129
-				if ($test) return array(3,$DBname,$e->getMessage());
129
+				if ($test) return array(3, $DBname, $e->getMessage());
130 130
 				$this->redirectNow('trapdirector/settings?dberror=4');
131 131
 				return null;
132 132
 			}
133 133
 		}
134
-		if ($test) return array(0,'');
134
+		if ($test) return array(0, '');
135 135
 		return $dbconn;
136 136
 	}
137 137
 
@@ -142,17 +142,17 @@  discard block
 block discarded – undo
142 142
 	 */
143 143
 	public function getDb($test=false)
144 144
 	{
145
-		if ($this->trapDB != null && $test = false) return $this->trapDB;
145
+		if ($this->trapDB != null && $test=false) return $this->trapDB;
146 146
 		
147 147
 		$dbresource=$this->Config()->get('config', 'database');
148 148
 		
149
-		if ( ! $dbresource )
149
+		if (!$dbresource)
150 150
 		{	
151
-			if ($test) return array(1,'');
151
+			if ($test) return array(1, '');
152 152
 			$this->redirectNow('trapdirector/settings?dberror=1');
153 153
 			return null;
154 154
 		}
155
-		$retDB=$this->getDbByName($dbresource,$test,true);
155
+		$retDB=$this->getDbByName($dbresource, $test, true);
156 156
 		if ($test == true) return $retDB;
157 157
 		$this->trapDB=$retDB;
158 158
 		return $this->trapDB;
@@ -160,78 +160,78 @@  discard block
 block discarded – undo
160 160
 	
161 161
 	public function getIdoDb($test=false)
162 162
 	{
163
-		if ($this->icingaDB != null && $test = false) return $this->icingaDB;
163
+		if ($this->icingaDB != null && $test=false) return $this->icingaDB;
164 164
 		// TODO : get ido database directly from icingaweb2 config -> (or not if using only API)
165
-		$dbresource=$this->Config()->get('config', 'IDOdatabase');;
165
+		$dbresource=$this->Config()->get('config', 'IDOdatabase'); ;
166 166
 
167
-		if ( ! $dbresource )
167
+		if (!$dbresource)
168 168
 		{
169
-		    if ($test) return array(1,'No database in config.ini');
169
+		    if ($test) return array(1, 'No database in config.ini');
170 170
 		    $this->redirectNow('trapdirector/settings?idodberror=1');
171 171
 		    return null;
172 172
 		}
173 173
 		
174 174
 		try
175 175
 		{
176
-		    $dbconn = IcingaDbConnection::fromResourceName($dbresource);
176
+		    $dbconn=IcingaDbConnection::fromResourceName($dbresource);
177 177
 		}
178 178
 		catch (Exception $e)
179 179
 		{
180
-		    if ($test) return array(2,"Database $dbresource does not exists in IcingaWeb2");
180
+		    if ($test) return array(2, "Database $dbresource does not exists in IcingaWeb2");
181 181
 		    $this->redirectNow('trapdirector/settings?idodberror=2');
182 182
 		    return null;
183 183
 		}
184 184
 		
185 185
 		if ($test == false) 
186 186
 		{ 
187
-			$this->icingaDB = $dbconn; 
187
+			$this->icingaDB=$dbconn; 
188 188
 			return $this->icingaDB;
189 189
 		}
190 190
 		
191 191
 		try
192 192
 		{
193
-		    $query = $dbconn->select()
194
-		    ->from('icinga_dbversion',array('version'));
193
+		    $query=$dbconn->select()
194
+		    ->from('icinga_dbversion', array('version'));
195 195
 		    $version=$dbconn->fetchRow($query);
196
-		    if ( ($version == null) || ! property_exists($version,'version') )
196
+		    if (($version == null) || !property_exists($version, 'version'))
197 197
 		    {
198
-		        return array(4,"$dbresource does not look like an IDO database");
198
+		        return array(4, "$dbresource does not look like an IDO database");
199 199
 		    }
200 200
 		}
201 201
 		catch (Exception $e)
202 202
 		{
203
-			return array(3,"Error connecting to $dbresource : " . $e->getMessage());
203
+			return array(3, "Error connecting to $dbresource : ".$e->getMessage());
204 204
 		}
205 205
 		
206
-		return array(0,'');
206
+		return array(0, '');
207 207
 	}
208 208
 	
209
-    protected function applyPaginationLimits(Paginatable $paginatable, $limit = 25, $offset = null)
209
+    protected function applyPaginationLimits(Paginatable $paginatable, $limit=25, $offset=null)
210 210
     {
211
-        $limit = $this->params->get('limit', $limit);
212
-        $page = $this->params->get('page', $offset);
211
+        $limit=$this->params->get('limit', $limit);
212
+        $page=$this->params->get('page', $offset);
213 213
 
214 214
         $paginatable->limit($limit, $page > 0 ? ($page - 1) * $limit : 0);
215 215
 
216 216
         return $paginatable;
217 217
     }	
218 218
 	
219
-	public function displayExitError($source,$message)
219
+	public function displayExitError($source, $message)
220 220
 	{	// TODO : check better ways to transmit data (with POST ?)
221 221
 		$this->redirectNow('trapdirector/error?source='.$source.'&message='.$message);
222 222
 	}
223 223
 	
224 224
 	protected function checkReadPermission()
225 225
 	{
226
-        if (! $this->Auth()->hasPermission('trapdirector/view')) {
227
-            $this->displayExitError('Permissions','No permission fo view content');
226
+        if (!$this->Auth()->hasPermission('trapdirector/view')) {
227
+            $this->displayExitError('Permissions', 'No permission fo view content');
228 228
         }		
229 229
 	}
230 230
 
231 231
 	protected function checkConfigPermission()
232 232
 	{
233
-        if (! $this->Auth()->hasPermission('trapdirector/config')) {
234
-            $this->displayExitError('Permissions','No permission fo configure');
233
+        if (!$this->Auth()->hasPermission('trapdirector/config')) {
234
+            $this->displayExitError('Permissions', 'No permission fo configure');
235 235
         }		
236 236
 	}
237 237
 	
@@ -242,10 +242,10 @@  discard block
 block discarded – undo
242 242
      */
243 243
 	protected function checkModuleConfigPermission($check=0)
244 244
 	{
245
-        if (! $this->Auth()->hasPermission('trapdirector/module_config')) {
245
+        if (!$this->Auth()->hasPermission('trapdirector/module_config')) {
246 246
             if ($check == 0)
247 247
             {
248
-                $this->displayExitError('Permissions','No permission fo configure module');
248
+                $this->displayExitError('Permissions', 'No permission fo configure module');
249 249
             }
250 250
             return false;
251 251
         }
@@ -257,10 +257,10 @@  discard block
 block discarded – undo
257 257
 	{ // TODO : try/catch here ? or within caller
258 258
 		if ($this->trapClass == null)
259 259
 		{
260
-			require_once($this->Module()->getBaseDir() .'/bin/trap_class.php');
260
+			require_once($this->Module()->getBaseDir().'/bin/trap_class.php');
261 261
 			$icingaweb2_etc=$this->Config()->get('config', 'icingaweb2_etc');
262 262
 			//$debug_level=4;
263
-			$this->trapClass = new Trap($icingaweb2_etc);
263
+			$this->trapClass=new Trap($icingaweb2_etc);
264 264
 			//$Trap->setLogging($debug_level,'syslog');
265 265
 		}
266 266
 		return $this->trapClass;
@@ -294,12 +294,12 @@  discard block
 block discarded – undo
294 294
 	protected function getHostByIP($ip) 
295 295
 	{
296 296
 		// select a.name1, b.display_name from icinga.icinga_objects AS a , icinga.icinga_hosts AS b WHERE (b.address = '192.168.56.101' OR b.address6= '123456') and b.host_object_id=a.object_id
297
-		$db = $this->getIdoDb()->getConnection();
297
+		$db=$this->getIdoDb()->getConnection();
298 298
 		// TODO : check for SQL injections
299 299
 		$query=$db->select()
300 300
 				->from(
301 301
 					array('a' => 'icinga_objects'),
302
-					array('name' => 'a.name1','id' => 'object_id'))
302
+					array('name' => 'a.name1', 'id' => 'object_id'))
303 303
 				->join(
304 304
 					array('b' => 'icinga_hosts'),
305 305
 					'b.host_object_id=a.object_id',
@@ -315,12 +315,12 @@  discard block
 block discarded – undo
315 315
 	protected function getHostByName($name) 
316 316
 	{
317 317
 		// select a.name1, b.display_name from icinga.icinga_objects AS a , icinga.icinga_hosts AS b WHERE (b.address = '192.168.56.101' OR b.address6= '123456') and b.host_object_id=a.object_id
318
-		$db = $this->getIdoDb()->getConnection();
318
+		$db=$this->getIdoDb()->getConnection();
319 319
 		// TODO : check for SQL injections
320 320
 		$query=$db->select()
321 321
 				->from(
322 322
 					array('a' => 'icinga_objects'),
323
-					array('name' => 'a.name1','id' => 'object_id'))
323
+					array('name' => 'a.name1', 'id' => 'object_id'))
324 324
 				->join(
325 325
 					array('b' => 'icinga_hosts'),
326 326
 					'b.host_object_id=a.object_id',
@@ -336,12 +336,12 @@  discard block
 block discarded – undo
336 336
 	protected function getHostGroupByName($ip) 
337 337
 	{
338 338
 		// select a.name1, b.display_name from icinga.icinga_objects AS a , icinga.icinga_hosts AS b WHERE (b.address = '192.168.56.101' OR b.address6= '123456') and b.host_object_id=a.object_id
339
-		$db = $this->getIdoDb()->getConnection();
339
+		$db=$this->getIdoDb()->getConnection();
340 340
 		// TODO : check for SQL injections
341 341
 		$query=$db->select()
342 342
 				->from(
343 343
 					array('a' => 'icinga_objects'),
344
-					array('name' => 'a.name1','id' => 'object_id'))
344
+					array('name' => 'a.name1', 'id' => 'object_id'))
345 345
 				->join(
346 346
 					array('b' => 'icinga_hostgroups'),
347 347
 					'b.hostgroup_object_id=a.object_id',
@@ -357,8 +357,8 @@  discard block
 block discarded – undo
357 357
 	*/
358 358
 	protected function getHostInfoByID($id) 
359 359
 	{
360
-		if (!preg_match('/^[0-9]+$/',$id)) { throw new Exception('Invalid id');  }
361
-		$db = $this->getIdoDb()->getConnection();
360
+		if (!preg_match('/^[0-9]+$/', $id)) { throw new Exception('Invalid id'); }
361
+		$db=$this->getIdoDb()->getConnection();
362 362
 		$query=$db->select()
363 363
 				->from(
364 364
 					array('a' => 'icinga_objects'),
@@ -378,17 +378,17 @@  discard block
 block discarded – undo
378 378
 	*/
379 379
 	protected function getHostByObjectID($id) // TODO : duplicate of getHostInfoByID above
380 380
 	{
381
-		if (!preg_match('/^[0-9]+$/',$id)) { throw new Exception('Invalid id');  }
382
-		$db = $this->getIdoDb()->getConnection();
381
+		if (!preg_match('/^[0-9]+$/', $id)) { throw new Exception('Invalid id'); }
382
+		$db=$this->getIdoDb()->getConnection();
383 383
 		$query=$db->select()
384 384
 				->from(
385 385
 					array('a' => 'icinga_objects'),
386
-					array('name' => 'a.name1','id' => 'a.object_id'))
386
+					array('name' => 'a.name1', 'id' => 'a.object_id'))
387 387
 				->join(
388 388
 					array('b' => 'icinga_hosts'),
389 389
 					'b.host_object_id=a.object_id',
390
-					array('display_name' => 'b.display_name' , 'ip' => 'b.address', 'ip6' => 'b.address6'))
391
-				->where('a.object_id = ?',$id);
390
+					array('display_name' => 'b.display_name', 'ip' => 'b.address', 'ip6' => 'b.address6'))
391
+				->where('a.object_id = ?', $id);
392 392
 		return $db->fetchRow($query);
393 393
 	}	
394 394
 	
@@ -400,16 +400,16 @@  discard block
 block discarded – undo
400 400
 	protected function getServicesByHostid($id) 
401 401
 	{
402 402
 		// select a.name1, b.display_name from icinga.icinga_objects AS a , icinga.icinga_hosts AS b WHERE (b.address = '192.168.56.101' OR b.address6= '123456') and b.host_object_id=a.object_id
403
-		if (!preg_match('/^[0-9]+$/',$id)) { throw new Exception('Invalid id');  }
404
-		$db = $this->getIdoDb()->getConnection();
403
+		if (!preg_match('/^[0-9]+$/', $id)) { throw new Exception('Invalid id'); }
404
+		$db=$this->getIdoDb()->getConnection();
405 405
 		$query=$db->select()
406 406
 				->from(
407 407
 					array('s' => 'icinga_services'),
408
-					array('name' => 's.display_name','id' => 's.service_object_id'))
408
+					array('name' => 's.display_name', 'id' => 's.service_object_id'))
409 409
 				->join(
410 410
 					array('a' => 'icinga_objects'),
411 411
 					's.service_object_id=a.object_id',
412
-					array('is_active'=>'a.is_active','name2'=>'a.name2'))
412
+					array('is_active'=>'a.is_active', 'name2'=>'a.name2'))
413 413
 				->where('s.host_object_id='.$id.' AND a.is_active = 1');
414 414
 
415 415
 		return $db->fetchAll($query);
@@ -423,8 +423,8 @@  discard block
 block discarded – undo
423 423
 	*/
424 424
 	protected function getServicesByHostGroupid($id) 
425 425
 	{		
426
-		if (!preg_match('/^[0-9]+$/',$id)) { throw new Exception('Invalid id');  }
427
-		$db = $this->getIdoDb()->getConnection();
426
+		if (!preg_match('/^[0-9]+$/', $id)) { throw new Exception('Invalid id'); }
427
+		$db=$this->getIdoDb()->getConnection();
428 428
 		$query=$db->select()
429 429
 				->from(
430 430
 					array('s' => 'icinga_hostgroup_members'),
@@ -441,11 +441,11 @@  discard block
 block discarded – undo
441 441
 		foreach ($hosts as $key => $host)
442 442
 		{ // For each host, get all services and add in common_services if not found or add counter
443 443
 			$host_services=$this->getServicesByHostid($host->host_object_id);
444
-			foreach($host_services as $service)
444
+			foreach ($host_services as $service)
445 445
 			{
446 446
 				if (isset($common_services[$service->name2]['num']))
447 447
 				{
448
-					$common_services[$service->name2]['num'] +=1;
448
+					$common_services[$service->name2]['num']+=1;
449 449
 				}
450 450
 				else
451 451
 				{
@@ -461,7 +461,7 @@  discard block
 block discarded – undo
461 461
 		{
462 462
 		    if ($common_services[$key]['num'] == $num_hosts)
463 463
 			{
464
-				array_push($result,array($key,$common_services[$key]['name']));
464
+				array_push($result, array($key, $common_services[$key]['name']));
465 465
 			}
466 466
 		}
467 467
 		
@@ -474,9 +474,9 @@  discard block
 block discarded – undo
474 474
 	*	@param $name string service name
475 475
 	*	@return array  service id
476 476
 	*/
477
-	protected function getServiceIDByName($hostname,$name) 
477
+	protected function getServiceIDByName($hostname, $name) 
478 478
 	{
479
-		$db = $this->getIdoDb()->getConnection();
479
+		$db=$this->getIdoDb()->getConnection();
480 480
 		if ($name == null)
481 481
 		{
482 482
 			return array();
@@ -485,7 +485,7 @@  discard block
 block discarded – undo
485 485
 		$query=$db->select()
486 486
 				->from(
487 487
 					array('s' => 'icinga_services'),
488
-					array('name' => 's.display_name','id' => 's.service_object_id'))
488
+					array('name' => 's.display_name', 'id' => 's.service_object_id'))
489 489
 				->join(
490 490
 					array('a' => 'icinga_objects'),
491 491
 					's.service_object_id=a.object_id',
@@ -503,12 +503,12 @@  discard block
 block discarded – undo
503 503
 	protected function getObjectNameByid($id) 
504 504
 	{
505 505
 		// select a.name1, b.display_name from icinga.icinga_objects AS a , icinga.icinga_hosts AS b WHERE (b.address = '192.168.56.101' OR b.address6= '123456') and b.host_object_id=a.object_id
506
-		if (!preg_match('/^[0-9]+$/',$id)) { throw new Exception('Invalid id');  }
507
-		$db = $this->getIdoDb()->getConnection();
506
+		if (!preg_match('/^[0-9]+$/', $id)) { throw new Exception('Invalid id'); }
507
+		$db=$this->getIdoDb()->getConnection();
508 508
 		$query=$db->select()
509 509
 				->from(
510 510
 					array('a' => 'icinga_objects'),
511
-					array('name1' => 'a.name1','name2' => 'a.name2'))
511
+					array('name1' => 'a.name1', 'name2' => 'a.name2'))
512 512
 				->where('a.object_id='.$id.' AND a.is_active = 1');
513 513
 
514 514
 		return $db->fetchRow($query);
@@ -521,17 +521,17 @@  discard block
 block discarded – undo
521 521
 	protected function addHandlerRule($params)
522 522
 	{
523 523
 		// TODO Check for rule consistency
524
-		$db = $this->getDb()->getConnection();
524
+		$db=$this->getDb()->getConnection();
525 525
 		// Add last modified date = creation date and username
526
-		$params['created'] = new Zend_Db_Expr('NOW()');
527
-		$params['modified'] = new 	Zend_Db_Expr('NOW()');
528
-		$params['modifier'] = $this->Auth()->getUser()->getUsername();
526
+		$params['created']=new Zend_Db_Expr('NOW()');
527
+		$params['modified']=new 	Zend_Db_Expr('NOW()');
528
+		$params['modifier']=$this->Auth()->getUser()->getUsername();
529 529
 		
530 530
 		$query=$db->insert(
531 531
 			$this->getModuleConfig()->getTrapRuleName(),
532 532
 			$params
533 533
 		);
534
-		if($query==false)
534
+		if ($query == false)
535 535
 		{
536 536
 		  return null;
537 537
 		}
@@ -543,13 +543,13 @@  discard block
 block discarded – undo
543 543
 	*   @param integer $ruleID : rule id in db
544 544
 	*	@return array affected rows
545 545
 	*/
546
-	protected function updateHandlerRule($params,$ruleID)
546
+	protected function updateHandlerRule($params, $ruleID)
547 547
 	{
548 548
 		// TODO Check for rule consistency
549
-		$db = $this->getDb()->getConnection();
549
+		$db=$this->getDb()->getConnection();
550 550
 		// Add last modified date = creation date and username
551
-		$params['modified'] = new 	Zend_Db_Expr('NOW()');
552
-		$params['modifier'] = $this->Auth()->getUser()->getUsername();
551
+		$params['modified']=new 	Zend_Db_Expr('NOW()');
552
+		$params['modifier']=$this->Auth()->getUser()->getUsername();
553 553
 		
554 554
 		$numRows=$db->update(
555 555
 			$this->getModuleConfig()->getTrapRuleName(),
@@ -564,8 +564,8 @@  discard block
 block discarded – undo
564 564
 	*/
565 565
 	protected function deleteRule($ruleID)
566 566
 	{
567
-		if (!preg_match('/^[0-9]+$/',$ruleID)) { throw new Exception('Invalid id');  }
568
-		$db = $this->getDb()->getConnection();
567
+		if (!preg_match('/^[0-9]+$/', $ruleID)) { throw new Exception('Invalid id'); }
568
+		$db=$this->getDb()->getConnection();
569 569
 		
570 570
 		$query=$db->delete(
571 571
 			$this->getModuleConfig()->getTrapRuleName(),
@@ -578,10 +578,10 @@  discard block
 block discarded – undo
578 578
 	*	@param $ip string source IP (v4 or v6)
579 579
 	*	@param $oid string oid
580 580
 	*/
581
-	protected function deleteTrap($ip,$oid)
581
+	protected function deleteTrap($ip, $oid)
582 582
 	{
583 583
 		
584
-		$db = $this->getDb()->getConnection();
584
+		$db=$this->getDb()->getConnection();
585 585
 		$condition=null;
586 586
 		if ($ip != null)
587 587
 		{
@@ -589,10 +589,10 @@  discard block
 block discarded – undo
589 589
 		}
590 590
 		if ($oid != null)
591 591
 		{
592
-			$condition=($condition===null)?'':$condition.' AND ';
592
+			$condition=($condition === null) ? '' : $condition.' AND ';
593 593
 			$condition.="trap_oid='$oid'";
594 594
 		}
595
-		if($condition === null) return null;
595
+		if ($condition === null) return null;
596 596
 		$query=$db->delete(
597 597
 			$this->getModuleConfig()->getTrapTableName(),
598 598
 			$condition
@@ -606,10 +606,10 @@  discard block
 block discarded – undo
606 606
 	*	@param $ip string source IP (v4 or v6)
607 607
 	*	@param $oid string oid
608 608
 	*/
609
-	protected function countTrap($ip,$oid)
609
+	protected function countTrap($ip, $oid)
610 610
 	{
611 611
 		
612
-		$db = $this->getDb()->getConnection();
612
+		$db=$this->getDb()->getConnection();
613 613
 		$condition=null;
614 614
 		if ($ip != null)
615 615
 		{
@@ -617,10 +617,10 @@  discard block
 block discarded – undo
617 617
 		}
618 618
 		if ($oid != null)
619 619
 		{
620
-			$condition=($condition===null)?'':$condition.' AND ';
620
+			$condition=($condition === null) ? '' : $condition.' AND ';
621 621
 			$condition.="trap_oid='$oid'";
622 622
 		}
623
-		if($condition === null) return 0;
623
+		if ($condition === null) return 0;
624 624
 		$query=$db->select()
625 625
 			->from(
626 626
 				$this->getModuleConfig()->getTrapTableName(),
@@ -636,27 +636,27 @@  discard block
 block discarded – undo
636 636
 	protected function getDBConfigValue($element)
637 637
 	{
638 638
 	
639
-		$db = $this->getDb()->getConnection();
639
+		$db=$this->getDb()->getConnection();
640 640
 		
641 641
 		$query=$db->select()
642 642
 			->from(
643 643
 				$this->getModuleConfig()->getDbConfigTableName(),
644 644
 				array('value'=>'value'))
645
-			->where('name=?',$element);
645
+			->where('name=?', $element);
646 646
 		$return_row=$db->fetchRow($query);
647
-		if ($return_row==null)  // value does not exists
647
+		if ($return_row == null)  // value does not exists
648 648
 		{
649 649
 			$default=$this->getModuleConfig()->getDBConfigDefaults();
650
-			if ( ! isset($default[$element])) return null; // no default and not value
650
+			if (!isset($default[$element])) return null; // no default and not value
651 651
 			
652
-			$this->addDBConfigValue($element,$default[$element]);
652
+			$this->addDBConfigValue($element, $default[$element]);
653 653
 			return $default[$element];
654 654
 		}
655 655
 		if ($return_row->value == null) // value id empty
656 656
 		{
657 657
 			$default=$this->getModuleConfig()->getDBConfigDefaults();
658
-			if ( ! isset($default[$element])) return null; // no default and not value
659
-			$this->setDBConfigValue($element,$default[$element]);
658
+			if (!isset($default[$element])) return null; // no default and not value
659
+			$this->setDBConfigValue($element, $default[$element]);
660 660
 			return $default[$element];			
661 661
 		}
662 662
 		return $return_row->value;		
@@ -667,10 +667,10 @@  discard block
 block discarded – undo
667 667
 	*   @param string $value : value
668 668
 	*/
669 669
 		
670
-	protected function addDBConfigValue($element,$value)
670
+	protected function addDBConfigValue($element, $value)
671 671
 	{
672 672
 	
673
-		$db = $this->getDb()->getConnection();
673
+		$db=$this->getDb()->getConnection();
674 674
 		
675 675
 		$query=$db->insert(
676 676
 				$this->getModuleConfig()->getDbConfigTableName(),
@@ -686,10 +686,10 @@  discard block
 block discarded – undo
686 686
 	*	@param string $element : name of config element
687 687
 	*   @param string $value : value
688 688
 	*/
689
-	protected function setDBConfigValue($element,$value)
689
+	protected function setDBConfigValue($element, $value)
690 690
 	{
691 691
 	
692
-		$db = $this->getDb()->getConnection();
692
+		$db=$this->getDb()->getConnection();
693 693
 		$query=$db->update(
694 694
 				$this->getModuleConfig()->getDbConfigTableName(),
695 695
 				array('value'=>$value),
@@ -704,10 +704,10 @@  discard block
 block discarded – undo
704 704
 	protected function isDirectorInstalled()
705 705
 	{
706 706
 	    $output=array();
707
-	    exec('icingacli module list',$output);
707
+	    exec('icingacli module list', $output);
708 708
 	    foreach ($output as $line)
709 709
 		{
710
-			if (preg_match('/^director .*enabled/',$line))
710
+			if (preg_match('/^director .*enabled/', $line))
711 711
 			{
712 712
 				return true;
713 713
 			}
Please login to merge, or discard this patch.
Braces   +62 added lines, -30 removed lines patch added patch discarded remove patch
@@ -87,10 +87,11 @@  discard block
 block discarded – undo
87 87
 		try 
88 88
 		{
89 89
 			$dbconn = IcingaDbConnection::fromResourceName($DBname);
90
-		} 
91
-		catch (Exception $e)
90
+		} catch (Exception $e)
92 91
 		{
93
-			if ($test) return array(2,$DBname);
92
+			if ($test) {
93
+				return array(2,$DBname);
94
+			}
94 95
 			$this->redirectNow('trapdirector/settings?dberror=2');
95 96
 			return null;
96 97
 		}
@@ -98,10 +99,11 @@  discard block
 block discarded – undo
98 99
 			try 
99 100
 			{
100 101
 				$db=$dbconn->getConnection();
101
-			}
102
-			catch (Exception $e) 
102
+			} catch (Exception $e) 
103 103
 			{
104
-				if ($test) return array(3,$DBname,$e->getMessage());
104
+				if ($test) {
105
+					return array(3,$DBname,$e->getMessage());
106
+				}
105 107
 				$this->redirectNow('trapdirector/settings?dberror=3');
106 108
 				return null;
107 109
 			}
@@ -113,25 +115,32 @@  discard block
 block discarded – undo
113 115
 				$version=$db->fetchRow($query);
114 116
 				if ( ($version == null) || ! property_exists($version,'value') )
115 117
 				{
116
-					if ($test) return array(4,$DBname);
118
+					if ($test) {
119
+						return array(4,$DBname);
120
+					}
117 121
 					$this->redirectNow('trapdirector/settings?dberror=4');
118 122
 					return null;
119 123
 				}
120 124
 				if ($version->value < $this->getModuleConfig()->getDbMinVersion()) 
121 125
 				{
122
-					if ($test) return array(5,$version->value,$this->getModuleConfig()->getDbMinVersion());
126
+					if ($test) {
127
+						return array(5,$version->value,$this->getModuleConfig()->getDbMinVersion());
128
+					}
123 129
 					$this->redirectNow('trapdirector/settings?dberror=5');
124 130
 					return null;
125 131
 				}
126
-			}
127
-			catch (Exception $e) 
132
+			} catch (Exception $e) 
128 133
 			{
129
-				if ($test) return array(3,$DBname,$e->getMessage());
134
+				if ($test) {
135
+					return array(3,$DBname,$e->getMessage());
136
+				}
130 137
 				$this->redirectNow('trapdirector/settings?dberror=4');
131 138
 				return null;
132 139
 			}
133 140
 		}
134
-		if ($test) return array(0,'');
141
+		if ($test) {
142
+			return array(0,'');
143
+		}
135 144
 		return $dbconn;
136 145
 	}
137 146
 
@@ -142,31 +151,41 @@  discard block
 block discarded – undo
142 151
 	 */
143 152
 	public function getDb($test=false)
144 153
 	{
145
-		if ($this->trapDB != null && $test = false) return $this->trapDB;
154
+		if ($this->trapDB != null && $test = false) {
155
+			return $this->trapDB;
156
+		}
146 157
 		
147 158
 		$dbresource=$this->Config()->get('config', 'database');
148 159
 		
149 160
 		if ( ! $dbresource )
150 161
 		{	
151
-			if ($test) return array(1,'');
162
+			if ($test) {
163
+				return array(1,'');
164
+			}
152 165
 			$this->redirectNow('trapdirector/settings?dberror=1');
153 166
 			return null;
154 167
 		}
155 168
 		$retDB=$this->getDbByName($dbresource,$test,true);
156
-		if ($test == true) return $retDB;
169
+		if ($test == true) {
170
+			return $retDB;
171
+		}
157 172
 		$this->trapDB=$retDB;
158 173
 		return $this->trapDB;
159 174
 	}
160 175
 	
161 176
 	public function getIdoDb($test=false)
162 177
 	{
163
-		if ($this->icingaDB != null && $test = false) return $this->icingaDB;
178
+		if ($this->icingaDB != null && $test = false) {
179
+			return $this->icingaDB;
180
+		}
164 181
 		// TODO : get ido database directly from icingaweb2 config -> (or not if using only API)
165 182
 		$dbresource=$this->Config()->get('config', 'IDOdatabase');;
166 183
 
167 184
 		if ( ! $dbresource )
168 185
 		{
169
-		    if ($test) return array(1,'No database in config.ini');
186
+		    if ($test) {
187
+		    	return array(1,'No database in config.ini');
188
+		    }
170 189
 		    $this->redirectNow('trapdirector/settings?idodberror=1');
171 190
 		    return null;
172 191
 		}
@@ -174,10 +193,11 @@  discard block
 block discarded – undo
174 193
 		try
175 194
 		{
176 195
 		    $dbconn = IcingaDbConnection::fromResourceName($dbresource);
177
-		}
178
-		catch (Exception $e)
196
+		} catch (Exception $e)
179 197
 		{
180
-		    if ($test) return array(2,"Database $dbresource does not exists in IcingaWeb2");
198
+		    if ($test) {
199
+		    	return array(2,"Database $dbresource does not exists in IcingaWeb2");
200
+		    }
181 201
 		    $this->redirectNow('trapdirector/settings?idodberror=2');
182 202
 		    return null;
183 203
 		}
@@ -197,8 +217,7 @@  discard block
 block discarded – undo
197 217
 		    {
198 218
 		        return array(4,"$dbresource does not look like an IDO database");
199 219
 		    }
200
-		}
201
-		catch (Exception $e)
220
+		} catch (Exception $e)
202 221
 		{
203 222
 			return array(3,"Error connecting to $dbresource : " . $e->getMessage());
204 223
 		}
@@ -446,8 +465,7 @@  discard block
 block discarded – undo
446 465
 				if (isset($common_services[$service->name2]['num']))
447 466
 				{
448 467
 					$common_services[$service->name2]['num'] +=1;
449
-				}
450
-				else
468
+				} else
451 469
 				{
452 470
 					$common_services[$service->name2]['num']=1;
453 471
 					$common_services[$service->name2]['name']=$service->name;
@@ -592,7 +610,9 @@  discard block
 block discarded – undo
592 610
 			$condition=($condition===null)?'':$condition.' AND ';
593 611
 			$condition.="trap_oid='$oid'";
594 612
 		}
595
-		if($condition === null) return null;
613
+		if($condition === null) {
614
+			return null;
615
+		}
596 616
 		$query=$db->delete(
597 617
 			$this->getModuleConfig()->getTrapTableName(),
598 618
 			$condition
@@ -620,7 +640,9 @@  discard block
 block discarded – undo
620 640
 			$condition=($condition===null)?'':$condition.' AND ';
621 641
 			$condition.="trap_oid='$oid'";
622 642
 		}
623
-		if($condition === null) return 0;
643
+		if($condition === null) {
644
+			return 0;
645
+		}
624 646
 		$query=$db->select()
625 647
 			->from(
626 648
 				$this->getModuleConfig()->getTrapTableName(),
@@ -644,18 +666,28 @@  discard block
 block discarded – undo
644 666
 				array('value'=>'value'))
645 667
 			->where('name=?',$element);
646 668
 		$return_row=$db->fetchRow($query);
647
-		if ($return_row==null)  // value does not exists
669
+		if ($return_row==null) {
670
+			// value does not exists
648 671
 		{
649 672
 			$default=$this->getModuleConfig()->getDBConfigDefaults();
650
-			if ( ! isset($default[$element])) return null; // no default and not value
673
+		}
674
+			if ( ! isset($default[$element])) {
675
+				return null;
676
+			}
677
+			// no default and not value
651 678
 			
652 679
 			$this->addDBConfigValue($element,$default[$element]);
653 680
 			return $default[$element];
654 681
 		}
655
-		if ($return_row->value == null) // value id empty
682
+		if ($return_row->value == null) {
683
+			// value id empty
656 684
 		{
657 685
 			$default=$this->getModuleConfig()->getDBConfigDefaults();
658
-			if ( ! isset($default[$element])) return null; // no default and not value
686
+		}
687
+			if ( ! isset($default[$element])) {
688
+				return null;
689
+			}
690
+			// no default and not value
659 691
 			$this->setDBConfigValue($element,$default[$element]);
660 692
 			return $default[$element];			
661 693
 		}
Please login to merge, or discard this patch.
library/Trapdirector/TrapsProcess/Database.php 3 patches
Braces   +7 added lines, -7 removed lines patch added patch discarded remove patch
@@ -171,8 +171,7 @@  discard block
 block discarded – undo
171 171
                 if (preg_match('/^ *CREATE TABLE ([^ ]+)/',$newline,$cur_table_array))
172 172
                 {
173 173
                     $cur_table='table '.$cur_table_array[1];
174
-                }
175
-                else
174
+                } else
176 175
                 {
177 176
                     $cur_table='secret SQL stuff :-)';
178 177
                 }
@@ -217,8 +216,7 @@  discard block
 block discarded – undo
217 216
         if ($this->trapDBType == 'pgsql')
218 217
         {
219 218
             $prefix .= 'update_pgsql/schema_';
220
-        }
221
-        else
219
+        } else
222 220
         {
223 221
             $prefix .= 'update_sql/schema_';
224 222
         }
@@ -264,7 +262,10 @@  discard block
 block discarded – undo
264 262
             $db_conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
265 263
             while (($line=fgets($input_stream)) !== false)
266 264
             {
267
-                if (preg_match('/^#/', $line)) continue; // ignore comment lines
265
+                if (preg_match('/^#/', $line)) {
266
+                	continue;
267
+                }
268
+                // ignore comment lines
268 269
                 $newline.=chop(preg_replace('/#PREFIX#/',$table_prefix,$line));
269 270
                 if (preg_match('/; *$/', $newline))
270 271
                 {
@@ -276,8 +277,7 @@  discard block
 block discarded – undo
276 277
                     if (preg_match('/^ *([^ ]+) TABLE ([^ ]+)/',$newline,$cur_table_array))
277 278
                     {
278 279
                         $cur_table=$cur_table_array[1] . ' SQL table '.$cur_table_array[2];
279
-                    }
280
-                    else
280
+                    } else
281 281
                     {
282 282
                         $cur_table='secret SQL stuff :-)';
283 283
                         //$cur_table=$newline;
Please login to merge, or discard this patch.
Indentation   +296 added lines, -296 removed lines patch added patch discarded remove patch
@@ -11,330 +11,330 @@
 block discarded – undo
11 11
 class Database
12 12
 {
13 13
 
14
-    // Databases
15
-    protected $trapDB=null; //< trap database
16
-    protected $idoDB=null; //< ido database
17
-    public $trapDBType; //< Type of database for traps (mysql, pgsql)
18
-    public $idoDBType; //< Type of database for ido (mysql, pgsql)
14
+	// Databases
15
+	protected $trapDB=null; //< trap database
16
+	protected $idoDB=null; //< ido database
17
+	public $trapDBType; //< Type of database for traps (mysql, pgsql)
18
+	public $idoDBType; //< Type of database for ido (mysql, pgsql)
19 19
     
20
-    protected $trapDSN; //< trap database connection params
21
-    protected $trapUsername; //< trap database connection params
22
-    protected $trapPass; //< trap database connection params
23
-    public $dbPrefix; //< database tables prefix
20
+	protected $trapDSN; //< trap database connection params
21
+	protected $trapUsername; //< trap database connection params
22
+	protected $trapPass; //< trap database connection params
23
+	public $dbPrefix; //< database tables prefix
24 24
     
25
-    protected $idoSet; //< bool true is ido database set
26
-    protected $idoDSN; //< trap database connection params
27
-    protected $idoUsername; //< trap database connection params
28
-    protected $idoPass; //< trap database connection params
25
+	protected $idoSet; //< bool true is ido database set
26
+	protected $idoDSN; //< trap database connection params
27
+	protected $idoUsername; //< trap database connection params
28
+	protected $idoPass; //< trap database connection params
29 29
     
30
-    // Logging function
30
+	// Logging function
31 31
     
32
-    protected $logging; //< logging class
32
+	protected $logging; //< logging class
33 33
     
34
-    /**
35
-     * @param Logging $logClass : where to log
36
-     * @param array $dbParam : array of named params  type,host,dbname,username,[port],[password]
37
-     */
38
-    function __construct($logClass,$dbParam,$dbPrefix)
39
-    {
40
-        $this->logging=$logClass;
41
-        $this->dbPrefix=$dbPrefix;
34
+	/**
35
+	 * @param Logging $logClass : where to log
36
+	 * @param array $dbParam : array of named params  type,host,dbname,username,[port],[password]
37
+	 */
38
+	function __construct($logClass,$dbParam,$dbPrefix)
39
+	{
40
+		$this->logging=$logClass;
41
+		$this->dbPrefix=$dbPrefix;
42 42
         
43
-        $this->trapDSN=$this->setupDSN($dbParam);
44
-        $this->trapUsername = $dbParam['username'];
45
-        $this->trapPass = (array_key_exists('password', $dbParam)) ? $dbParam['password']:'';
46
-        $this->trapDBType=$dbParam['db'];
47
-        $this->logging->log('DSN : '.$this->trapDSN. ';user '.$this->trapUsername.' / prefix : '. $this->dbPrefix,INFO);
48
-        $this->db_connect_trap();
43
+		$this->trapDSN=$this->setupDSN($dbParam);
44
+		$this->trapUsername = $dbParam['username'];
45
+		$this->trapPass = (array_key_exists('password', $dbParam)) ? $dbParam['password']:'';
46
+		$this->trapDBType=$dbParam['db'];
47
+		$this->logging->log('DSN : '.$this->trapDSN. ';user '.$this->trapUsername.' / prefix : '. $this->dbPrefix,INFO);
48
+		$this->db_connect_trap();
49 49
         
50
-    }
50
+	}
51 51
     
52
-    /**
53
-     * Setup and connect to IDO database
54
-     * @param array $dbParam : array of named params
55
-     */
56
-    public function setupIDO($dbParam)
57
-    {
58
-        $this->idoDSN=$this->setupDSN($dbParam);
59
-        $this->idoUsername = $dbParam['username'];
60
-        $this->idoPass = (array_key_exists('password', $dbParam)) ? $dbParam['password']:'';
61
-        $this->logging->log('DSN : '.$this->idoDSN. ';user '.$this->idoUsername,INFO);
62
-        $this->idoDBType=$dbParam['db'];
63
-        $this->db_connect_ido();
64
-    }
52
+	/**
53
+	 * Setup and connect to IDO database
54
+	 * @param array $dbParam : array of named params
55
+	 */
56
+	public function setupIDO($dbParam)
57
+	{
58
+		$this->idoDSN=$this->setupDSN($dbParam);
59
+		$this->idoUsername = $dbParam['username'];
60
+		$this->idoPass = (array_key_exists('password', $dbParam)) ? $dbParam['password']:'';
61
+		$this->logging->log('DSN : '.$this->idoDSN. ';user '.$this->idoUsername,INFO);
62
+		$this->idoDBType=$dbParam['db'];
63
+		$this->db_connect_ido();
64
+	}
65 65
     
66
-    /**
67
-     * Connect to IDO database
68
-     * @return \PDO
69
-     */
70
-    public function db_connect_ido()
71
-    {
72
-        if ($this->idoDB != null) {
73
-            // Check if connection is still alive
74
-            try {
75
-                $this->idoDB->query('select 1')->fetchColumn();
76
-                return $this->idoDB;
77
-            } catch (Exception $e) {
78
-                // select 1 failed, try to reconnect.
79
-                $this->logging->log('Database IDO connection lost, reconnecting',WARN);
80
-            }
81
-        }
82
-        try {
83
-            $this->idoDB = new PDO($this->idoDSN,$this->idoUsername,$this->idoPass);
84
-        } catch (PDOException $e) {
85
-            $this->logging->log('Connection failed to IDO : ' . $e->getMessage(),ERROR,'');
86
-        }
87
-        return $this->idoDB;
88
-    }
66
+	/**
67
+	 * Connect to IDO database
68
+	 * @return \PDO
69
+	 */
70
+	public function db_connect_ido()
71
+	{
72
+		if ($this->idoDB != null) {
73
+			// Check if connection is still alive
74
+			try {
75
+				$this->idoDB->query('select 1')->fetchColumn();
76
+				return $this->idoDB;
77
+			} catch (Exception $e) {
78
+				// select 1 failed, try to reconnect.
79
+				$this->logging->log('Database IDO connection lost, reconnecting',WARN);
80
+			}
81
+		}
82
+		try {
83
+			$this->idoDB = new PDO($this->idoDSN,$this->idoUsername,$this->idoPass);
84
+		} catch (PDOException $e) {
85
+			$this->logging->log('Connection failed to IDO : ' . $e->getMessage(),ERROR,'');
86
+		}
87
+		return $this->idoDB;
88
+	}
89 89
     
90
-    /**
91
-     * Connect to Trap database
92
-     * @return \PDO
93
-     */
94
-    public function db_connect_trap()
95
-    {
90
+	/**
91
+	 * Connect to Trap database
92
+	 * @return \PDO
93
+	 */
94
+	public function db_connect_trap()
95
+	{
96 96
         
97
-        if ($this->trapDB != null) {
98
-            // Check if connection is still alive
99
-            try {
100
-                $this->trapDB->query('select 1')->fetchColumn();
101
-                return $this->trapDB;
102
-            } catch (Exception $e) {
103
-                // select 1 failed, try to reconnect.
104
-                $this->logging->log('Database connection lost, reconnecting',WARN);
105
-            }           
106
-        }       
107
-        try {
108
-            $this->trapDB = new PDO($this->trapDSN,$this->trapUsername,$this->trapPass);
109
-        } catch (PDOException $e) {
110
-            $this->logging->log('Connection failed : ' . $e->getMessage(),ERROR,'');
111
-        }
112
-        return $this->trapDB;
113
-    }
97
+		if ($this->trapDB != null) {
98
+			// Check if connection is still alive
99
+			try {
100
+				$this->trapDB->query('select 1')->fetchColumn();
101
+				return $this->trapDB;
102
+			} catch (Exception $e) {
103
+				// select 1 failed, try to reconnect.
104
+				$this->logging->log('Database connection lost, reconnecting',WARN);
105
+			}           
106
+		}       
107
+		try {
108
+			$this->trapDB = new PDO($this->trapDSN,$this->trapUsername,$this->trapPass);
109
+		} catch (PDOException $e) {
110
+			$this->logging->log('Connection failed : ' . $e->getMessage(),ERROR,'');
111
+		}
112
+		return $this->trapDB;
113
+	}
114 114
     
115
-    /**
116
-     * Setup dsn and check parameters
117
-     * @param array $configElmt
118
-     * @return string
119
-     */
120
-    protected function setupDSN($configElmt)  
121
-    {
122
-        if (!array_key_exists('db',$configElmt) ||
123
-            !array_key_exists('host',$configElmt) ||
124
-            !array_key_exists('dbname',$configElmt) ||
125
-            !array_key_exists('username',$configElmt))
126
-        {
127
-            $this->logging->log('Missing DB params',ERROR);
128
-            return ''; 
129
-        }
115
+	/**
116
+	 * Setup dsn and check parameters
117
+	 * @param array $configElmt
118
+	 * @return string
119
+	 */
120
+	protected function setupDSN($configElmt)  
121
+	{
122
+		if (!array_key_exists('db',$configElmt) ||
123
+			!array_key_exists('host',$configElmt) ||
124
+			!array_key_exists('dbname',$configElmt) ||
125
+			!array_key_exists('username',$configElmt))
126
+		{
127
+			$this->logging->log('Missing DB params',ERROR);
128
+			return ''; 
129
+		}
130 130
         
131
-        //	$dsn = 'mysql:dbname=traps;host=127.0.0.1';
132
-        $dsn= $configElmt['db'].':dbname='.$configElmt['dbname'].';host='.$configElmt['host'];
131
+		//	$dsn = 'mysql:dbname=traps;host=127.0.0.1';
132
+		$dsn= $configElmt['db'].':dbname='.$configElmt['dbname'].';host='.$configElmt['host'];
133 133
         
134
-        if (array_key_exists('port', $configElmt))
135
-        {
136
-            $dsn .= ';port='.$configElmt['port'];
137
-        }
138
-        return $dsn;
139
-    }
134
+		if (array_key_exists('port', $configElmt))
135
+		{
136
+			$dsn .= ';port='.$configElmt['port'];
137
+		}
138
+		return $dsn;
139
+	}
140 140
 
141 141
     
142
-    /** Create database schema
143
-     *	@param $schema_file	string File to read schema from
144
-     *	@param $table_prefix string to replace #PREFIX# in schema file by this
145
-     */
146
-    public function create_schema($schema_file,$table_prefix)
147
-    {
148
-        //Read data from snmptrapd from stdin
149
-        $input_stream=fopen($schema_file, 'r');
142
+	/** Create database schema
143
+	 *	@param $schema_file	string File to read schema from
144
+	 *	@param $table_prefix string to replace #PREFIX# in schema file by this
145
+	 */
146
+	public function create_schema($schema_file,$table_prefix)
147
+	{
148
+		//Read data from snmptrapd from stdin
149
+		$input_stream=fopen($schema_file, 'r');
150 150
         
151
-        if ($input_stream=== false)
152
-        {
153
-            $this->logging->log("Error reading schema !",ERROR,'');
154
-            return;
155
-        }
156
-        $newline='';
157
-        $cur_table='';
158
-        $cur_table_array=array();
159
-        $db_conn=$this->db_connect_trap();
151
+		if ($input_stream=== false)
152
+		{
153
+			$this->logging->log("Error reading schema !",ERROR,'');
154
+			return;
155
+		}
156
+		$newline='';
157
+		$cur_table='';
158
+		$cur_table_array=array();
159
+		$db_conn=$this->db_connect_trap();
160 160
         
161
-        while (($line=fgets($input_stream)) !== false)
162
-        {
163
-            $newline.=chop(preg_replace('/#PREFIX#/',$table_prefix,$line));
164
-            if (preg_match('/; *$/', $newline))
165
-            {
166
-                $sql= $newline;
167
-                if ($db_conn->query($sql) === false) {
168
-                    $this->logging->log('Error create schema : '.$sql,ERROR,'');
169
-                    return;
170
-                }
171
-                if (preg_match('/^ *CREATE TABLE ([^ ]+)/',$newline,$cur_table_array))
172
-                {
173
-                    $cur_table='table '.$cur_table_array[1];
174
-                }
175
-                else
176
-                {
177
-                    $cur_table='secret SQL stuff :-)';
178
-                }
179
-                $this->logging->log('Creating : ' . $cur_table,INFO );
180
-                $newline='';
181
-            }
182
-        }
161
+		while (($line=fgets($input_stream)) !== false)
162
+		{
163
+			$newline.=chop(preg_replace('/#PREFIX#/',$table_prefix,$line));
164
+			if (preg_match('/; *$/', $newline))
165
+			{
166
+				$sql= $newline;
167
+				if ($db_conn->query($sql) === false) {
168
+					$this->logging->log('Error create schema : '.$sql,ERROR,'');
169
+					return;
170
+				}
171
+				if (preg_match('/^ *CREATE TABLE ([^ ]+)/',$newline,$cur_table_array))
172
+				{
173
+					$cur_table='table '.$cur_table_array[1];
174
+				}
175
+				else
176
+				{
177
+					$cur_table='secret SQL stuff :-)';
178
+				}
179
+				$this->logging->log('Creating : ' . $cur_table,INFO );
180
+				$newline='';
181
+			}
182
+		}
183 183
         
184
-        $sql= $newline;
185
-        if ($sql != '' )
186
-        {
187
-            if ($db_conn->query($sql) === false) {
188
-                $this->logging->log('Error create schema : '.$sql,ERROR,'');
189
-                return;
190
-            }
191
-        }
192
-        $this->logging->log('Schema created',INFO);
193
-    }
184
+		$sql= $newline;
185
+		if ($sql != '' )
186
+		{
187
+			if ($db_conn->query($sql) === false) {
188
+				$this->logging->log('Error create schema : '.$sql,ERROR,'');
189
+				return;
190
+			}
191
+		}
192
+		$this->logging->log('Schema created',INFO);
193
+	}
194 194
     
195
-    /**
196
-     * Update database schema from current (as set in db) to $target_version
197
-     *     @param $prefix string file prefix of sql update File
198
-     *     @param $target_version int target db version number
199
-     *     @param $table_prefix string to replace #PREFIX# in schema file by this
200
-     *     @param bool $getmsg : only get messages from version upgrades
201
-     *     @return string : if $getmsg=true, return messages or 'ERROR' on error.
202
-     */
203
-    public function update_schema($prefix,$target_version,$table_prefix,$getmsg=false)
204
-    {
205
-        // Get current db number
206
-        $db_conn=$this->db_connect_trap();
207
-        $sql='SELECT value from '.$this->dbPrefix.'db_config WHERE name=\'db_version\' ';
208
-        $this->logging->log('SQL query : '.$sql,DEBUG );
209
-        if (($ret_code=$db_conn->query($sql)) === false) {
210
-            $this->logging->log('Cannot get db version. Query : ' . $sql,2,'');
211
-            return 'ERROR';
212
-        }
213
-        $version=$ret_code->fetchAll();
214
-        $cur_version=$version[0]['value'];
195
+	/**
196
+	 * Update database schema from current (as set in db) to $target_version
197
+	 *     @param $prefix string file prefix of sql update File
198
+	 *     @param $target_version int target db version number
199
+	 *     @param $table_prefix string to replace #PREFIX# in schema file by this
200
+	 *     @param bool $getmsg : only get messages from version upgrades
201
+	 *     @return string : if $getmsg=true, return messages or 'ERROR' on error.
202
+	 */
203
+	public function update_schema($prefix,$target_version,$table_prefix,$getmsg=false)
204
+	{
205
+		// Get current db number
206
+		$db_conn=$this->db_connect_trap();
207
+		$sql='SELECT value from '.$this->dbPrefix.'db_config WHERE name=\'db_version\' ';
208
+		$this->logging->log('SQL query : '.$sql,DEBUG );
209
+		if (($ret_code=$db_conn->query($sql)) === false) {
210
+			$this->logging->log('Cannot get db version. Query : ' . $sql,2,'');
211
+			return 'ERROR';
212
+		}
213
+		$version=$ret_code->fetchAll();
214
+		$cur_version=$version[0]['value'];
215 215
         
216
-        if ($this->trapDBType == 'pgsql')
217
-        {
218
-            $prefix .= 'update_pgsql/schema_';
219
-        }
220
-        else
221
-        {
222
-            $prefix .= 'update_sql/schema_';
223
-        }
224
-        //echo "version all :\n";print_r($version);echo " \n $cur_ver \n";
225
-        if ($getmsg === true)
226
-        {
227
-            return $this->update_schema_message($prefix, $cur_version, $target_version);
228
-        }
216
+		if ($this->trapDBType == 'pgsql')
217
+		{
218
+			$prefix .= 'update_pgsql/schema_';
219
+		}
220
+		else
221
+		{
222
+			$prefix .= 'update_sql/schema_';
223
+		}
224
+		//echo "version all :\n";print_r($version);echo " \n $cur_ver \n";
225
+		if ($getmsg === true)
226
+		{
227
+			return $this->update_schema_message($prefix, $cur_version, $target_version);
228
+		}
229 229
         
230
-        if ($this->update_schema_do($prefix, $cur_version, $target_version, $table_prefix) === true)
231
-        {
232
-            return 'ERROR';
233
-        }
234
-        return '';
230
+		if ($this->update_schema_do($prefix, $cur_version, $target_version, $table_prefix) === true)
231
+		{
232
+			return 'ERROR';
233
+		}
234
+		return '';
235 235
 
236
-    }
236
+	}
237 237
 
238
-    /**
239
-     * Update database schema from current (as set in db) to $target_version
240
-     *     @param string $prefix  file prefix of sql update File
241
-     *     @param int $cur_version  current db version number
242
-     *     @param int $target_version  target db version number
243
-     *     @param string $table_prefix   to replace #PREFIX# in schema file by this
244
-     *     @return bool : true on error
245
-     */
246
-    public function update_schema_do($prefix,$cur_version,$target_version,$table_prefix)
247
-    {
248
-        while($cur_version<$target_version)
249
-        { // TODO : execute pre & post scripts
250
-            $cur_version++;
251
-            $this->logging->log('Updating to version : ' .$cur_version ,INFO );
252
-            $updateFile=$prefix.'v'.($cur_version-1).'_v'.$cur_version.'.sql';
253
-            $input_stream=fopen($updateFile, 'r');
254
-            if ($input_stream=== false)
255
-            {
256
-                $this->logging->log("Error reading update file ". $updateFile,ERROR);
257
-                return true;
258
-            }
259
-            $newline='';
260
-            $db_conn=$this->db_connect_trap();
261
-            $db_conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
262
-            while (($line=fgets($input_stream)) !== false)
263
-            {
264
-                if (preg_match('/^#/', $line)) continue; // ignore comment lines
265
-                $newline.=chop(preg_replace('/#PREFIX#/',$table_prefix,$line));
266
-                if (preg_match('/; *$/', $newline))
267
-                {
268
-                    $sql_req=$db_conn->prepare($newline);
269
-                    if ($sql_req->execute() === false) {
270
-                        $this->logging->log('Error create schema : '.$newline,ERROR);
271
-                        return true;
272
-                    }
273
-                    $cur_table_array=array();
274
-                    if (preg_match('/^ *([^ ]+) TABLE ([^ ]+)/',$newline,$cur_table_array))
275
-                    {
276
-                        $cur_table=$cur_table_array[1] . ' SQL table '.$cur_table_array[2];
277
-                    }
278
-                    else
279
-                    {
280
-                        $cur_table='secret SQL stuff :-)';
281
-                        //$cur_table=$newline;
282
-                    }
283
-                    $this->logging->log('Doing : ' . $cur_table,INFO );
238
+	/**
239
+	 * Update database schema from current (as set in db) to $target_version
240
+	 *     @param string $prefix  file prefix of sql update File
241
+	 *     @param int $cur_version  current db version number
242
+	 *     @param int $target_version  target db version number
243
+	 *     @param string $table_prefix   to replace #PREFIX# in schema file by this
244
+	 *     @return bool : true on error
245
+	 */
246
+	public function update_schema_do($prefix,$cur_version,$target_version,$table_prefix)
247
+	{
248
+		while($cur_version<$target_version)
249
+		{ // TODO : execute pre & post scripts
250
+			$cur_version++;
251
+			$this->logging->log('Updating to version : ' .$cur_version ,INFO );
252
+			$updateFile=$prefix.'v'.($cur_version-1).'_v'.$cur_version.'.sql';
253
+			$input_stream=fopen($updateFile, 'r');
254
+			if ($input_stream=== false)
255
+			{
256
+				$this->logging->log("Error reading update file ". $updateFile,ERROR);
257
+				return true;
258
+			}
259
+			$newline='';
260
+			$db_conn=$this->db_connect_trap();
261
+			$db_conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
262
+			while (($line=fgets($input_stream)) !== false)
263
+			{
264
+				if (preg_match('/^#/', $line)) continue; // ignore comment lines
265
+				$newline.=chop(preg_replace('/#PREFIX#/',$table_prefix,$line));
266
+				if (preg_match('/; *$/', $newline))
267
+				{
268
+					$sql_req=$db_conn->prepare($newline);
269
+					if ($sql_req->execute() === false) {
270
+						$this->logging->log('Error create schema : '.$newline,ERROR);
271
+						return true;
272
+					}
273
+					$cur_table_array=array();
274
+					if (preg_match('/^ *([^ ]+) TABLE ([^ ]+)/',$newline,$cur_table_array))
275
+					{
276
+						$cur_table=$cur_table_array[1] . ' SQL table '.$cur_table_array[2];
277
+					}
278
+					else
279
+					{
280
+						$cur_table='secret SQL stuff :-)';
281
+						//$cur_table=$newline;
282
+					}
283
+					$this->logging->log('Doing : ' . $cur_table,INFO );
284 284
                     
285
-                    $newline='';
286
-                }
287
-            }
288
-            fclose($input_stream);
285
+					$newline='';
286
+				}
287
+			}
288
+			fclose($input_stream);
289 289
             
290
-            $sql='UPDATE '.$this->dbPrefix.'db_config SET value='.$cur_version.' WHERE ( name=\'db_version\' )';
291
-            $this->logging->log('SQL query : '.$sql,DEBUG );
292
-            if ($db_conn->query($sql) === false) {
293
-                $this->logging->log('Cannot update db version. Query : ' . $sql,WARN);
294
-                return true;
295
-            }
290
+			$sql='UPDATE '.$this->dbPrefix.'db_config SET value='.$cur_version.' WHERE ( name=\'db_version\' )';
291
+			$this->logging->log('SQL query : '.$sql,DEBUG );
292
+			if ($db_conn->query($sql) === false) {
293
+				$this->logging->log('Cannot update db version. Query : ' . $sql,WARN);
294
+				return true;
295
+			}
296 296
             
297
-            $this->logging->log('Schema updated to version : '.$cur_version ,INFO);
298
-        }
299
-        return false;
300
-    }
297
+			$this->logging->log('Schema updated to version : '.$cur_version ,INFO);
298
+		}
299
+		return false;
300
+	}
301 301
     
302
-    /**
303
-     * Get database message for update to $target_version
304
-     *     @param string $prefix  file prefix of sql update File
305
-     *     @param int $cur_version  current db version number
306
-     *     @param int $target_version  target db version number
307
-     *     @return string : return messages or 'ERROR'.
308
-     */
309
-    private function update_schema_message($prefix,$cur_version,$target_version)
310
-    {
302
+	/**
303
+	 * Get database message for update to $target_version
304
+	 *     @param string $prefix  file prefix of sql update File
305
+	 *     @param int $cur_version  current db version number
306
+	 *     @param int $target_version  target db version number
307
+	 *     @return string : return messages or 'ERROR'.
308
+	 */
309
+	private function update_schema_message($prefix,$cur_version,$target_version)
310
+	{
311 311
  
312
-        $message='';
313
-        $this->logging->log('getting message for upgrade',DEBUG );
314
-        while($cur_version<$target_version)
315
-        {
316
-            $cur_version++;
317
-            $updateFile=$prefix.'v'.($cur_version-1).'_v'.$cur_version.'.sql';
318
-            $input_stream=fopen($updateFile, 'r');
319
-            if ($input_stream=== false)
320
-            {
321
-                $this->logging->log("Error reading update file ". $updateFile,2,'');
322
-                return 'ERROR';
323
-            }
324
-            do 
325
-            { 
326
-                $line=fgets($input_stream); 
327
-            }
328
-            while ($line !== false && !preg_match('/#MESSAGE/',$line));
329
-            fclose($input_stream);
330
-            if ($line === false)
331
-            {
332
-                $this->logging->log("No message in file ". $updateFile,2,'');
333
-                return '';
334
-            }
335
-            $message .= ($cur_version-1) . '->' . $cur_version. ' : ' . preg_replace('/#MESSAGE : /','',$line)."\n";
336
-        }
337
-        return $message;
338
-    }
312
+		$message='';
313
+		$this->logging->log('getting message for upgrade',DEBUG );
314
+		while($cur_version<$target_version)
315
+		{
316
+			$cur_version++;
317
+			$updateFile=$prefix.'v'.($cur_version-1).'_v'.$cur_version.'.sql';
318
+			$input_stream=fopen($updateFile, 'r');
319
+			if ($input_stream=== false)
320
+			{
321
+				$this->logging->log("Error reading update file ". $updateFile,2,'');
322
+				return 'ERROR';
323
+			}
324
+			do 
325
+			{ 
326
+				$line=fgets($input_stream); 
327
+			}
328
+			while ($line !== false && !preg_match('/#MESSAGE/',$line));
329
+			fclose($input_stream);
330
+			if ($line === false)
331
+			{
332
+				$this->logging->log("No message in file ". $updateFile,2,'');
333
+				return '';
334
+			}
335
+			$message .= ($cur_version-1) . '->' . $cur_version. ' : ' . preg_replace('/#MESSAGE : /','',$line)."\n";
336
+		}
337
+		return $message;
338
+	}
339 339
     
340 340
 }
341 341
\ No newline at end of file
Please login to merge, or discard this patch.
Spacing   +60 added lines, -60 removed lines patch added patch discarded remove patch
@@ -35,16 +35,16 @@  discard block
 block discarded – undo
35 35
      * @param Logging $logClass : where to log
36 36
      * @param array $dbParam : array of named params  type,host,dbname,username,[port],[password]
37 37
      */
38
-    function __construct($logClass,$dbParam,$dbPrefix)
38
+    function __construct($logClass, $dbParam, $dbPrefix)
39 39
     {
40 40
         $this->logging=$logClass;
41 41
         $this->dbPrefix=$dbPrefix;
42 42
         
43 43
         $this->trapDSN=$this->setupDSN($dbParam);
44
-        $this->trapUsername = $dbParam['username'];
45
-        $this->trapPass = (array_key_exists('password', $dbParam)) ? $dbParam['password']:'';
44
+        $this->trapUsername=$dbParam['username'];
45
+        $this->trapPass=(array_key_exists('password', $dbParam)) ? $dbParam['password'] : '';
46 46
         $this->trapDBType=$dbParam['db'];
47
-        $this->logging->log('DSN : '.$this->trapDSN. ';user '.$this->trapUsername.' / prefix : '. $this->dbPrefix,INFO);
47
+        $this->logging->log('DSN : '.$this->trapDSN.';user '.$this->trapUsername.' / prefix : '.$this->dbPrefix, INFO);
48 48
         $this->db_connect_trap();
49 49
         
50 50
     }
@@ -56,9 +56,9 @@  discard block
 block discarded – undo
56 56
     public function setupIDO($dbParam)
57 57
     {
58 58
         $this->idoDSN=$this->setupDSN($dbParam);
59
-        $this->idoUsername = $dbParam['username'];
60
-        $this->idoPass = (array_key_exists('password', $dbParam)) ? $dbParam['password']:'';
61
-        $this->logging->log('DSN : '.$this->idoDSN. ';user '.$this->idoUsername,INFO);
59
+        $this->idoUsername=$dbParam['username'];
60
+        $this->idoPass=(array_key_exists('password', $dbParam)) ? $dbParam['password'] : '';
61
+        $this->logging->log('DSN : '.$this->idoDSN.';user '.$this->idoUsername, INFO);
62 62
         $this->idoDBType=$dbParam['db'];
63 63
         $this->db_connect_ido();
64 64
     }
@@ -76,13 +76,13 @@  discard block
 block discarded – undo
76 76
                 return $this->idoDB;
77 77
             } catch (Exception $e) {
78 78
                 // select 1 failed, try to reconnect.
79
-                $this->logging->log('Database IDO connection lost, reconnecting',WARN);
79
+                $this->logging->log('Database IDO connection lost, reconnecting', WARN);
80 80
             }
81 81
         }
82 82
         try {
83
-            $this->idoDB = new PDO($this->idoDSN,$this->idoUsername,$this->idoPass);
83
+            $this->idoDB=new PDO($this->idoDSN, $this->idoUsername, $this->idoPass);
84 84
         } catch (PDOException $e) {
85
-            $this->logging->log('Connection failed to IDO : ' . $e->getMessage(),ERROR,'');
85
+            $this->logging->log('Connection failed to IDO : '.$e->getMessage(), ERROR, '');
86 86
         }
87 87
         return $this->idoDB;
88 88
     }
@@ -101,13 +101,13 @@  discard block
 block discarded – undo
101 101
                 return $this->trapDB;
102 102
             } catch (Exception $e) {
103 103
                 // select 1 failed, try to reconnect.
104
-                $this->logging->log('Database connection lost, reconnecting',WARN);
104
+                $this->logging->log('Database connection lost, reconnecting', WARN);
105 105
             }           
106 106
         }       
107 107
         try {
108
-            $this->trapDB = new PDO($this->trapDSN,$this->trapUsername,$this->trapPass);
108
+            $this->trapDB=new PDO($this->trapDSN, $this->trapUsername, $this->trapPass);
109 109
         } catch (PDOException $e) {
110
-            $this->logging->log('Connection failed : ' . $e->getMessage(),ERROR,'');
110
+            $this->logging->log('Connection failed : '.$e->getMessage(), ERROR, '');
111 111
         }
112 112
         return $this->trapDB;
113 113
     }
@@ -119,21 +119,21 @@  discard block
 block discarded – undo
119 119
      */
120 120
     protected function setupDSN($configElmt)  
121 121
     {
122
-        if (!array_key_exists('db',$configElmt) ||
123
-            !array_key_exists('host',$configElmt) ||
124
-            !array_key_exists('dbname',$configElmt) ||
125
-            !array_key_exists('username',$configElmt))
122
+        if (!array_key_exists('db', $configElmt) ||
123
+            !array_key_exists('host', $configElmt) ||
124
+            !array_key_exists('dbname', $configElmt) ||
125
+            !array_key_exists('username', $configElmt))
126 126
         {
127
-            $this->logging->log('Missing DB params',ERROR);
127
+            $this->logging->log('Missing DB params', ERROR);
128 128
             return ''; 
129 129
         }
130 130
         
131 131
         //	$dsn = 'mysql:dbname=traps;host=127.0.0.1';
132
-        $dsn= $configElmt['db'].':dbname='.$configElmt['dbname'].';host='.$configElmt['host'];
132
+        $dsn=$configElmt['db'].':dbname='.$configElmt['dbname'].';host='.$configElmt['host'];
133 133
         
134 134
         if (array_key_exists('port', $configElmt))
135 135
         {
136
-            $dsn .= ';port='.$configElmt['port'];
136
+            $dsn.=';port='.$configElmt['port'];
137 137
         }
138 138
         return $dsn;
139 139
     }
@@ -143,14 +143,14 @@  discard block
 block discarded – undo
143 143
      *	@param $schema_file	string File to read schema from
144 144
      *	@param $table_prefix string to replace #PREFIX# in schema file by this
145 145
      */
146
-    public function create_schema($schema_file,$table_prefix)
146
+    public function create_schema($schema_file, $table_prefix)
147 147
     {
148 148
         //Read data from snmptrapd from stdin
149 149
         $input_stream=fopen($schema_file, 'r');
150 150
         
151
-        if ($input_stream=== false)
151
+        if ($input_stream === false)
152 152
         {
153
-            $this->logging->log("Error reading schema !",ERROR,'');
153
+            $this->logging->log("Error reading schema !", ERROR, '');
154 154
             return;
155 155
         }
156 156
         $newline='';
@@ -160,15 +160,15 @@  discard block
 block discarded – undo
160 160
         
161 161
         while (($line=fgets($input_stream)) !== false)
162 162
         {
163
-            $newline.=chop(preg_replace('/#PREFIX#/',$table_prefix,$line));
163
+            $newline.=chop(preg_replace('/#PREFIX#/', $table_prefix, $line));
164 164
             if (preg_match('/; *$/', $newline))
165 165
             {
166
-                $sql= $newline;
166
+                $sql=$newline;
167 167
                 if ($db_conn->query($sql) === false) {
168
-                    $this->logging->log('Error create schema : '.$sql,ERROR,'');
168
+                    $this->logging->log('Error create schema : '.$sql, ERROR, '');
169 169
                     return;
170 170
                 }
171
-                if (preg_match('/^ *CREATE TABLE ([^ ]+)/',$newline,$cur_table_array))
171
+                if (preg_match('/^ *CREATE TABLE ([^ ]+)/', $newline, $cur_table_array))
172 172
                 {
173 173
                     $cur_table='table '.$cur_table_array[1];
174 174
                 }
@@ -176,20 +176,20 @@  discard block
 block discarded – undo
176 176
                 {
177 177
                     $cur_table='secret SQL stuff :-)';
178 178
                 }
179
-                $this->logging->log('Creating : ' . $cur_table,INFO );
179
+                $this->logging->log('Creating : '.$cur_table, INFO);
180 180
                 $newline='';
181 181
             }
182 182
         }
183 183
         
184
-        $sql= $newline;
185
-        if ($sql != '' )
184
+        $sql=$newline;
185
+        if ($sql != '')
186 186
         {
187 187
             if ($db_conn->query($sql) === false) {
188
-                $this->logging->log('Error create schema : '.$sql,ERROR,'');
188
+                $this->logging->log('Error create schema : '.$sql, ERROR, '');
189 189
                 return;
190 190
             }
191 191
         }
192
-        $this->logging->log('Schema created',INFO);
192
+        $this->logging->log('Schema created', INFO);
193 193
     }
194 194
     
195 195
     /**
@@ -200,14 +200,14 @@  discard block
 block discarded – undo
200 200
      *     @param bool $getmsg : only get messages from version upgrades
201 201
      *     @return string : if $getmsg=true, return messages or 'ERROR' on error.
202 202
      */
203
-    public function update_schema($prefix,$target_version,$table_prefix,$getmsg=false)
203
+    public function update_schema($prefix, $target_version, $table_prefix, $getmsg=false)
204 204
     {
205 205
         // Get current db number
206 206
         $db_conn=$this->db_connect_trap();
207 207
         $sql='SELECT value from '.$this->dbPrefix.'db_config WHERE name=\'db_version\' ';
208
-        $this->logging->log('SQL query : '.$sql,DEBUG );
208
+        $this->logging->log('SQL query : '.$sql, DEBUG);
209 209
         if (($ret_code=$db_conn->query($sql)) === false) {
210
-            $this->logging->log('Cannot get db version. Query : ' . $sql,2,'');
210
+            $this->logging->log('Cannot get db version. Query : '.$sql, 2, '');
211 211
             return 'ERROR';
212 212
         }
213 213
         $version=$ret_code->fetchAll();
@@ -215,11 +215,11 @@  discard block
 block discarded – undo
215 215
         
216 216
         if ($this->trapDBType == 'pgsql')
217 217
         {
218
-            $prefix .= 'update_pgsql/schema_';
218
+            $prefix.='update_pgsql/schema_';
219 219
         }
220 220
         else
221 221
         {
222
-            $prefix .= 'update_sql/schema_';
222
+            $prefix.='update_sql/schema_';
223 223
         }
224 224
         //echo "version all :\n";print_r($version);echo " \n $cur_ver \n";
225 225
         if ($getmsg === true)
@@ -243,17 +243,17 @@  discard block
 block discarded – undo
243 243
      *     @param string $table_prefix   to replace #PREFIX# in schema file by this
244 244
      *     @return bool : true on error
245 245
      */
246
-    public function update_schema_do($prefix,$cur_version,$target_version,$table_prefix)
246
+    public function update_schema_do($prefix, $cur_version, $target_version, $table_prefix)
247 247
     {
248
-        while($cur_version<$target_version)
248
+        while ($cur_version < $target_version)
249 249
         { // TODO : execute pre & post scripts
250 250
             $cur_version++;
251
-            $this->logging->log('Updating to version : ' .$cur_version ,INFO );
252
-            $updateFile=$prefix.'v'.($cur_version-1).'_v'.$cur_version.'.sql';
251
+            $this->logging->log('Updating to version : '.$cur_version, INFO);
252
+            $updateFile=$prefix.'v'.($cur_version - 1).'_v'.$cur_version.'.sql';
253 253
             $input_stream=fopen($updateFile, 'r');
254
-            if ($input_stream=== false)
254
+            if ($input_stream === false)
255 255
             {
256
-                $this->logging->log("Error reading update file ". $updateFile,ERROR);
256
+                $this->logging->log("Error reading update file ".$updateFile, ERROR);
257 257
                 return true;
258 258
             }
259 259
             $newline='';
@@ -262,25 +262,25 @@  discard block
 block discarded – undo
262 262
             while (($line=fgets($input_stream)) !== false)
263 263
             {
264 264
                 if (preg_match('/^#/', $line)) continue; // ignore comment lines
265
-                $newline.=chop(preg_replace('/#PREFIX#/',$table_prefix,$line));
265
+                $newline.=chop(preg_replace('/#PREFIX#/', $table_prefix, $line));
266 266
                 if (preg_match('/; *$/', $newline))
267 267
                 {
268 268
                     $sql_req=$db_conn->prepare($newline);
269 269
                     if ($sql_req->execute() === false) {
270
-                        $this->logging->log('Error create schema : '.$newline,ERROR);
270
+                        $this->logging->log('Error create schema : '.$newline, ERROR);
271 271
                         return true;
272 272
                     }
273 273
                     $cur_table_array=array();
274
-                    if (preg_match('/^ *([^ ]+) TABLE ([^ ]+)/',$newline,$cur_table_array))
274
+                    if (preg_match('/^ *([^ ]+) TABLE ([^ ]+)/', $newline, $cur_table_array))
275 275
                     {
276
-                        $cur_table=$cur_table_array[1] . ' SQL table '.$cur_table_array[2];
276
+                        $cur_table=$cur_table_array[1].' SQL table '.$cur_table_array[2];
277 277
                     }
278 278
                     else
279 279
                     {
280 280
                         $cur_table='secret SQL stuff :-)';
281 281
                         //$cur_table=$newline;
282 282
                     }
283
-                    $this->logging->log('Doing : ' . $cur_table,INFO );
283
+                    $this->logging->log('Doing : '.$cur_table, INFO);
284 284
                     
285 285
                     $newline='';
286 286
                 }
@@ -288,13 +288,13 @@  discard block
 block discarded – undo
288 288
             fclose($input_stream);
289 289
             
290 290
             $sql='UPDATE '.$this->dbPrefix.'db_config SET value='.$cur_version.' WHERE ( name=\'db_version\' )';
291
-            $this->logging->log('SQL query : '.$sql,DEBUG );
291
+            $this->logging->log('SQL query : '.$sql, DEBUG);
292 292
             if ($db_conn->query($sql) === false) {
293
-                $this->logging->log('Cannot update db version. Query : ' . $sql,WARN);
293
+                $this->logging->log('Cannot update db version. Query : '.$sql, WARN);
294 294
                 return true;
295 295
             }
296 296
             
297
-            $this->logging->log('Schema updated to version : '.$cur_version ,INFO);
297
+            $this->logging->log('Schema updated to version : '.$cur_version, INFO);
298 298
         }
299 299
         return false;
300 300
     }
@@ -306,33 +306,33 @@  discard block
 block discarded – undo
306 306
      *     @param int $target_version  target db version number
307 307
      *     @return string : return messages or 'ERROR'.
308 308
      */
309
-    private function update_schema_message($prefix,$cur_version,$target_version)
309
+    private function update_schema_message($prefix, $cur_version, $target_version)
310 310
     {
311 311
  
312 312
         $message='';
313
-        $this->logging->log('getting message for upgrade',DEBUG );
314
-        while($cur_version<$target_version)
313
+        $this->logging->log('getting message for upgrade', DEBUG);
314
+        while ($cur_version < $target_version)
315 315
         {
316 316
             $cur_version++;
317
-            $updateFile=$prefix.'v'.($cur_version-1).'_v'.$cur_version.'.sql';
317
+            $updateFile=$prefix.'v'.($cur_version - 1).'_v'.$cur_version.'.sql';
318 318
             $input_stream=fopen($updateFile, 'r');
319
-            if ($input_stream=== false)
319
+            if ($input_stream === false)
320 320
             {
321
-                $this->logging->log("Error reading update file ". $updateFile,2,'');
321
+                $this->logging->log("Error reading update file ".$updateFile, 2, '');
322 322
                 return 'ERROR';
323 323
             }
324 324
             do 
325 325
             { 
326 326
                 $line=fgets($input_stream); 
327 327
             }
328
-            while ($line !== false && !preg_match('/#MESSAGE/',$line));
328
+            while ($line !== false && !preg_match('/#MESSAGE/', $line));
329 329
             fclose($input_stream);
330 330
             if ($line === false)
331 331
             {
332
-                $this->logging->log("No message in file ". $updateFile,2,'');
332
+                $this->logging->log("No message in file ".$updateFile, 2, '');
333 333
                 return '';
334 334
             }
335
-            $message .= ($cur_version-1) . '->' . $cur_version. ' : ' . preg_replace('/#MESSAGE : /','',$line)."\n";
335
+            $message.=($cur_version - 1).'->'.$cur_version.' : '.preg_replace('/#MESSAGE : /', '', $line)."\n";
336 336
         }
337 337
         return $message;
338 338
     }
Please login to merge, or discard this patch.
tests/db_test.php 2 patches
Indentation   +29 added lines, -29 removed lines patch added patch discarded remove patch
@@ -14,40 +14,40 @@
 block discarded – undo
14 14
 
15 15
 if (!array_key_exists('v',$options) || !array_key_exists('c',$options) || !array_key_exists('b',$options)|| !array_key_exists('a',$options))
16 16
 {
17
-    printf("Need version -v, path -a, database -b (mysql,pgsql) command -c (create/update)\n");
18
-    exit(1);
17
+	printf("Need version -v, path -a, database -b (mysql,pgsql) command -c (create/update)\n");
18
+	exit(1);
19 19
 }
20 20
 $command=$options['c'];
21 21
 $path=$options['a'];
22 22
 try {
23
-    switch($command)
24
-    {
25
-        case 'create':
26
-            $schema=($options['b']=='mysql')?'schema_v'.$options['v'].'.sql':'schema_v'.$options['v'].'.pgsql';
27
-            $schema=$path.'/SQL/'.$schema;
28
-            $trap->trapsDB->create_schema($schema, 'traps_');
29
-            break;
30
-        case 'update':
31
-            $message=$trap->trapsDB->update_schema($path."/SQL/",$options['v'], 'traps_',true);
32
-            printf("Update message : %s\n",$message);
33
-            if ($message == 'ERROR')
34
-            {
35
-                exit(1);
36
-            }
37
-            printf("Messages DONE, updating : \n");
38
-            $message=$trap->trapsDB->update_schema($path."/SQL/",$options['v'], 'traps_');
39
-            if ($message == 'ERROR')
40
-            {
41
-                exit(1);
42
-            }
43
-            break;
44
-        default:
45
-            printf("Unknown command\n");
46
-            exit(1);
47
-    }
23
+	switch($command)
24
+	{
25
+		case 'create':
26
+			$schema=($options['b']=='mysql')?'schema_v'.$options['v'].'.sql':'schema_v'.$options['v'].'.pgsql';
27
+			$schema=$path.'/SQL/'.$schema;
28
+			$trap->trapsDB->create_schema($schema, 'traps_');
29
+			break;
30
+		case 'update':
31
+			$message=$trap->trapsDB->update_schema($path."/SQL/",$options['v'], 'traps_',true);
32
+			printf("Update message : %s\n",$message);
33
+			if ($message == 'ERROR')
34
+			{
35
+				exit(1);
36
+			}
37
+			printf("Messages DONE, updating : \n");
38
+			$message=$trap->trapsDB->update_schema($path."/SQL/",$options['v'], 'traps_');
39
+			if ($message == 'ERROR')
40
+			{
41
+				exit(1);
42
+			}
43
+			break;
44
+		default:
45
+			printf("Unknown command\n");
46
+			exit(1);
47
+	}
48 48
 } catch (Exception $e) {
49
-    printf("Caught Exception %s\n",$e->getMessage());
50
-    exit (1);
49
+	printf("Caught Exception %s\n",$e->getMessage());
50
+	exit (1);
51 51
 }
52 52
 
53 53
 exit(0);
Please login to merge, or discard this patch.
Spacing   +12 added lines, -12 removed lines patch added patch discarded remove patch
@@ -3,16 +3,16 @@  discard block
 block discarded – undo
3 3
 
4 4
 require_once 'bin/trap_class.php';
5 5
 
6
-$options = getopt("c:v:d:b:a:");
6
+$options=getopt("c:v:d:b:a:");
7 7
 
8
-$icingaweb2Etc=(array_key_exists('d',$options))?$options['d']:"/etc/icingaweb2";
8
+$icingaweb2Etc=(array_key_exists('d', $options)) ? $options['d'] : "/etc/icingaweb2";
9 9
 
10
-$debugLevel=4;// 0=No output 1=critical 2=warning 3=trace 4=ALL
10
+$debugLevel=4; // 0=No output 1=critical 2=warning 3=trace 4=ALL
11 11
 
12
-$trap = new trap($icingaweb2Etc,$debugLevel,'display');
13
-$trap->setLogging($debugLevel,'display');
12
+$trap=new trap($icingaweb2Etc, $debugLevel, 'display');
13
+$trap->setLogging($debugLevel, 'display');
14 14
 
15
-if (!array_key_exists('v',$options) || !array_key_exists('c',$options) || !array_key_exists('b',$options)|| !array_key_exists('a',$options))
15
+if (!array_key_exists('v', $options) || !array_key_exists('c', $options) || !array_key_exists('b', $options) || !array_key_exists('a', $options))
16 16
 {
17 17
     printf("Need version -v, path -a, database -b (mysql,pgsql) command -c (create/update)\n");
18 18
     exit(1);
@@ -20,22 +20,22 @@  discard block
 block discarded – undo
20 20
 $command=$options['c'];
21 21
 $path=$options['a'];
22 22
 try {
23
-    switch($command)
23
+    switch ($command)
24 24
     {
25 25
         case 'create':
26
-            $schema=($options['b']=='mysql')?'schema_v'.$options['v'].'.sql':'schema_v'.$options['v'].'.pgsql';
26
+            $schema=($options['b'] == 'mysql') ? 'schema_v'.$options['v'].'.sql' : 'schema_v'.$options['v'].'.pgsql';
27 27
             $schema=$path.'/SQL/'.$schema;
28 28
             $trap->trapsDB->create_schema($schema, 'traps_');
29 29
             break;
30 30
         case 'update':
31
-            $message=$trap->trapsDB->update_schema($path."/SQL/",$options['v'], 'traps_',true);
32
-            printf("Update message : %s\n",$message);
31
+            $message=$trap->trapsDB->update_schema($path."/SQL/", $options['v'], 'traps_', true);
32
+            printf("Update message : %s\n", $message);
33 33
             if ($message == 'ERROR')
34 34
             {
35 35
                 exit(1);
36 36
             }
37 37
             printf("Messages DONE, updating : \n");
38
-            $message=$trap->trapsDB->update_schema($path."/SQL/",$options['v'], 'traps_');
38
+            $message=$trap->trapsDB->update_schema($path."/SQL/", $options['v'], 'traps_');
39 39
             if ($message == 'ERROR')
40 40
             {
41 41
                 exit(1);
@@ -46,7 +46,7 @@  discard block
 block discarded – undo
46 46
             exit(1);
47 47
     }
48 48
 } catch (Exception $e) {
49
-    printf("Caught Exception %s\n",$e->getMessage());
49
+    printf("Caught Exception %s\n", $e->getMessage());
50 50
     exit (1);
51 51
 }
52 52
 
Please login to merge, or discard this patch.
bin/trap_class.php 3 patches
Indentation   +241 added lines, -241 removed lines patch added patch discarded remove patch
@@ -57,7 +57,7 @@  discard block
 block discarded – undo
57 57
 	
58 58
 	function __construct($etc_dir='/etc/icingaweb2',$baseLogLevel=null,$baseLogMode='syslog',$baseLogFile='')
59 59
 	{
60
-	    // Paths of ini files
60
+		// Paths of ini files
61 61
 		$this->icingaweb2_etc=$etc_dir;
62 62
 		$this->trap_module_config=$this->icingaweb2_etc."/modules/trapdirector/config.ini";		
63 63
 		$this->icingaweb2_ressources=$this->icingaweb2_etc."/resources.ini";
@@ -66,18 +66,18 @@  discard block
 block discarded – undo
66 66
 		$this->logging = new Logging();
67 67
 		if ($baseLogLevel != null)
68 68
 		{
69
-		    $this->logging->setLogging($baseLogLevel, $baseLogMode,$baseLogFile);
70
-		    $this->logSetup=true;
69
+			$this->logging->setLogging($baseLogLevel, $baseLogMode,$baseLogFile);
70
+			$this->logSetup=true;
71 71
 		}
72 72
 		else
73
-		    $this->logSetup=false;
73
+			$this->logSetup=false;
74 74
 		$this->logging->log('Loggin started', INFO);
75 75
 
76 76
 		// Get options from ini files
77 77
 		$trapConfig=parse_ini_file($this->trap_module_config,true);
78 78
 		if ($trapConfig == false)
79 79
 		{
80
-		    $this->logging->log("Error reading ini file : ".$this->trap_module_config,ERROR,'syslog');
80
+			$this->logging->log("Error reading ini file : ".$this->trap_module_config,ERROR,'syslog');
81 81
 		}
82 82
 		$this->getMainOptions($trapConfig); // Get main options from ini file
83 83
 		$this->setupDatabase($trapConfig); // Setup database class
@@ -109,26 +109,26 @@  discard block
 block discarded – undo
109 109
 	 */
110 110
 	protected function getOptionIfSet($option_array,$option_category,$option_name, &$option_var, $log_level = 2, $message = null)
111 111
 	{
112
-	    if (!isset($option_array[$option_category][$option_name]))
113
-	    {
114
-	        if ($message === null)
115
-	        {
116
-	            $message='No ' . $option_name . ' in config file: '. $this->trap_module_config;
117
-	        }
118
-	        $this->logging->log($message,$log_level,'syslog');
119
-	        return false;
120
-	    }
121
-	    else
122
-	    {
123
-	        $option_var=$option_array[$option_category][$option_name];
124
-	        return true;
125
-	    }
112
+		if (!isset($option_array[$option_category][$option_name]))
113
+		{
114
+			if ($message === null)
115
+			{
116
+				$message='No ' . $option_name . ' in config file: '. $this->trap_module_config;
117
+			}
118
+			$this->logging->log($message,$log_level,'syslog');
119
+			return false;
120
+		}
121
+		else
122
+		{
123
+			$option_var=$option_array[$option_category][$option_name];
124
+			return true;
125
+		}
126 126
 	}
127 127
 	
128 128
 	/** 
129 129
 	 * Get options from ini file
130 130
 	 * @param array $trap_config : ini file array
131
-	*/
131
+	 */
132 132
 	protected function getMainOptions($trapConfig)
133 133
 	{
134 134
 
@@ -147,10 +147,10 @@  discard block
 block discarded – undo
147 147
 		// API options
148 148
 		if ($this->getOptionIfSet($trapConfig,'config','icingaAPI_host', $this->api_hostname))
149 149
 		{
150
-		    $this->api_use=true;
151
-		    $this->getOptionIfSet($trapConfig,'config','icingaAPI_port', $this->api_port);
152
-		    $this->getOptionIfSet($trapConfig,'config','icingaAPI_user', $this->api_username);
153
-		    $this->getOptionIfSet($trapConfig,'config','icingaAPI_password', $this->api_password);
150
+			$this->api_use=true;
151
+			$this->getOptionIfSet($trapConfig,'config','icingaAPI_port', $this->api_port);
152
+			$this->getOptionIfSet($trapConfig,'config','icingaAPI_user', $this->api_username);
153
+			$this->getOptionIfSet($trapConfig,'config','icingaAPI_password', $this->api_password);
154 154
 		}
155 155
 	}
156 156
 	
@@ -160,45 +160,45 @@  discard block
 block discarded – undo
160 160
 	 */
161 161
 	protected function setupDatabase($trapConfig)
162 162
 	{
163
-	    // Trap database
164
-	    if (!array_key_exists('database',$trapConfig['config']))
165
-        {
166
-            $this->logging->log("No database in config file: ".$this->trap_module_config,ERROR,'');
167
-            return;
168
-        }
169
-        $dbTrapName=$trapConfig['config']['database'];
170
-        $this->logging->log("Found database in config file: ".$dbTrapName,INFO );
163
+		// Trap database
164
+		if (!array_key_exists('database',$trapConfig['config']))
165
+		{
166
+			$this->logging->log("No database in config file: ".$this->trap_module_config,ERROR,'');
167
+			return;
168
+		}
169
+		$dbTrapName=$trapConfig['config']['database'];
170
+		$this->logging->log("Found database in config file: ".$dbTrapName,INFO );
171 171
 	    
172 172
 	   if ( ($dbConfig=parse_ini_file($this->icingaweb2_ressources,true)) === false)
173
-	    {
174
-	        $this->logging->log("Error reading ini file : ".$this->icingaweb2_ressources,ERROR,'');
175
-	        return;
176
-	    }
177
-	    if (!array_key_exists($dbTrapName,$dbConfig))
178
-	    {
179
-	        $this->logging->log("No database '.$dbTrapName.' in config file: ".$this->icingaweb2_ressources,ERROR,'');
180
-	        return;
181
-	    }
173
+		{
174
+			$this->logging->log("Error reading ini file : ".$this->icingaweb2_ressources,ERROR,'');
175
+			return;
176
+		}
177
+		if (!array_key_exists($dbTrapName,$dbConfig))
178
+		{
179
+			$this->logging->log("No database '.$dbTrapName.' in config file: ".$this->icingaweb2_ressources,ERROR,'');
180
+			return;
181
+		}
182 182
 	    
183
-	    $this->trapsDB = new Database($this->logging,$dbConfig[$dbTrapName],$this->db_prefix);
183
+		$this->trapsDB = new Database($this->logging,$dbConfig[$dbTrapName],$this->db_prefix);
184 184
 	    
185
-	    if ($this->api_use === true) return; // In case of API use, no IDO is necessary
185
+		if ($this->api_use === true) return; // In case of API use, no IDO is necessary
186 186
         
187
-	    // IDO Database
188
-	    if (!array_key_exists('IDOdatabase',$trapConfig['config']))
189
-	    {
190
-	        $this->logging->log("No IDOdatabase in config file: ".$this->trap_module_config,ERROR,'');
191
-	    }
192
-	    $dbIdoName=$trapConfig['config']['IDOdatabase'];		
187
+		// IDO Database
188
+		if (!array_key_exists('IDOdatabase',$trapConfig['config']))
189
+		{
190
+			$this->logging->log("No IDOdatabase in config file: ".$this->trap_module_config,ERROR,'');
191
+		}
192
+		$dbIdoName=$trapConfig['config']['IDOdatabase'];		
193 193
 
194
-	    $this->logging->log("Found IDO database in config file: ".$dbIdoName,INFO );
195
-        if (!array_key_exists($dbIdoName,$dbConfig))
196
-	    {
197
-	        $this->logging->log("No database '.$dbIdoName.' in config file: ".$this->icingaweb2_ressources,ERROR,'');
198
-	        return;
199
-	    }
194
+		$this->logging->log("Found IDO database in config file: ".$dbIdoName,INFO );
195
+		if (!array_key_exists($dbIdoName,$dbConfig))
196
+		{
197
+			$this->logging->log("No database '.$dbIdoName.' in config file: ".$this->icingaweb2_ressources,ERROR,'');
198
+			return;
199
+		}
200 200
 	    
201
-	    $this->trapsDB->setupIDO($dbConfig[$dbIdoName]);
201
+		$this->trapsDB->setupIDO($dbConfig[$dbIdoName]);
202 202
 	}
203 203
 	
204 204
 	/**
@@ -209,9 +209,9 @@  discard block
 block discarded – undo
209 209
 		// Database options
210 210
 		if ($this->logSetup === false) // Only if logging was no setup in constructor
211 211
 		{
212
-    		$this->getDBConfigIfSet('log_level',$this->logging->debugLevel);
213
-    		$this->getDBConfigIfSet('log_destination',$this->logging->outputMode);
214
-    		$this->getDBConfigIfSet('log_file',$this->logging->outputFile);
212
+			$this->getDBConfigIfSet('log_level',$this->logging->debugLevel);
213
+			$this->getDBConfigIfSet('log_destination',$this->logging->outputMode);
214
+			$this->getDBConfigIfSet('log_file',$this->logging->outputFile);
215 215
 		}
216 216
 	}
217 217
 
@@ -222,10 +222,10 @@  discard block
 block discarded – undo
222 222
 	}
223 223
 	
224 224
 	/** 
225
-	*   Get data from db_config
226
-	*	@param $element string name of param
227
-	*	@return mixed : value (or null)
228
-	*/	
225
+	 *   Get data from db_config
226
+	 *	@param $element string name of param
227
+	 *	@return mixed : value (or null)
228
+	 */	
229 229
 	protected function getDBConfig($element)
230 230
 	{
231 231
 		$db_conn=$this->trapsDB->db_connect_trap();
@@ -243,15 +243,15 @@  discard block
 block discarded – undo
243 243
 	}
244 244
 	
245 245
 	/** OBSOLETE Send log. Throws exception on critical error
246
-	*	@param	string $message Message to log
247
-	*	@param	int $level 1=critical 2=warning 3=trace 4=debug
248
-	*	@param  string $destination file/syslog/display
249
-	*	@return void
250
-	**/	
246
+	 *	@param	string $message Message to log
247
+	 *	@param	int $level 1=critical 2=warning 3=trace 4=debug
248
+	 *	@param  string $destination file/syslog/display
249
+	 *	@return void
250
+	 **/	
251 251
 	public function trapLog( $message, $level, $destination ='') // OBSOLETE
252 252
 	{	
253 253
 		// TODO : replace ref with $this->logging->log 
254
-	    $this->logging->log($message, $level, $destination);
254
+		$this->logging->log($message, $level, $destination);
255 255
 	}
256 256
 	
257 257
 	public function setLogging($debugLvl,$outputType,$outputOption=null)  // OBSOLETE
@@ -261,19 +261,19 @@  discard block
 block discarded – undo
261 261
 	
262 262
 	protected function getAPI()
263 263
 	{
264
-	    if ($this->icinga2api == null)
265
-	    {
266
-	        $this->icinga2api = new Icinga2API($this->api_hostname,$this->api_port);
267
-	    }
268
-	    return $this->icinga2api;
264
+		if ($this->icinga2api == null)
265
+		{
266
+			$this->icinga2api = new Icinga2API($this->api_hostname,$this->api_port);
267
+		}
268
+		return $this->icinga2api;
269 269
 	}
270 270
 	
271 271
 	
272 272
 	/** 
273 273
 	 * read data from stream
274
-	*	@param $stream string input stream, defaults to "php://stdin"
275
-	*	@return mixed array trap data or exception with error
276
-	*/
274
+	 *	@param $stream string input stream, defaults to "php://stdin"
275
+	 *	@return mixed array trap data or exception with error
276
+	 */
277 277
 	public function read_trap($stream='php://stdin')
278 278
 	{
279 279
 		//Read data from snmptrapd from stdin
@@ -281,7 +281,7 @@  discard block
 block discarded – undo
281 281
 
282 282
 		if ($input_stream === false)
283 283
 		{
284
-		    $this->writeTrapErrorToDB("Error reading trap (code 1/Stdin)");
284
+			$this->writeTrapErrorToDB("Error reading trap (code 1/Stdin)");
285 285
 			$this->logging->log("Error reading stdin !",ERROR,'');
286 286
 			return null; // note : exception thrown by logging
287 287
 		}
@@ -290,21 +290,21 @@  discard block
 block discarded – undo
290 290
 		$this->receivingHost=chop(fgets($input_stream));
291 291
 		if ($this->receivingHost === false)
292 292
 		{
293
-		    $this->writeTrapErrorToDB("Error reading trap (code 1/Line Host)");
293
+			$this->writeTrapErrorToDB("Error reading trap (code 1/Line Host)");
294 294
 			$this->logging->log("Error reading Host !",ERROR,''); 
295 295
 		}
296 296
 		// line 2 IP:port=>IP:port
297 297
 		$IP=chop(fgets($input_stream));
298 298
 		if ($IP === false)
299 299
 		{
300
-		    $this->writeTrapErrorToDB("Error reading trap (code 1/Line IP)");
300
+			$this->writeTrapErrorToDB("Error reading trap (code 1/Line IP)");
301 301
 			$this->logging->log("Error reading IP !",ERROR,''); 
302 302
 		}
303 303
 		$matches=array();
304 304
 		$ret_code=preg_match('/.DP: \[(.*)\]:(.*)->\[(.*)\]:(.*)/',$IP,$matches);
305 305
 		if ($ret_code===0 || $ret_code===false) 
306 306
 		{
307
-		    $this->writeTrapErrorToDB("Error parsing trap (code 2/IP)");
307
+			$this->writeTrapErrorToDB("Error parsing trap (code 2/IP)");
308 308
 			$this->logging->log('Error parsing IP : '.$IP,ERROR,'');
309 309
 		} 
310 310
 		else 
@@ -325,7 +325,7 @@  discard block
 block discarded – undo
325 325
 			}
326 326
 			else 
327 327
 			{
328
-			    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'))
328
+				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'))
329 329
 				{
330 330
 					$this->trap_data['trap_oid']=$matches[2];				
331 331
 				}
@@ -341,7 +341,7 @@  discard block
 block discarded – undo
341 341
 
342 342
 		if ($this->trap_data['trap_oid']=='unknown') 
343 343
 		{
344
-		    $this->writeTrapErrorToDB("No trap oid found : check snmptrapd configuration (code 3/OID)",$this->trap_data['source_ip']);
344
+			$this->writeTrapErrorToDB("No trap oid found : check snmptrapd configuration (code 3/OID)",$this->trap_data['source_ip']);
345 345
 			$this->logging->log('no trap oid found',ERROR,'');
346 346
 		} 
347 347
 
@@ -371,9 +371,9 @@  discard block
 block discarded – undo
371 371
 
372 372
 	/** 
373 373
 	 * Translate oid into array(MIB,Name)
374
-	* @param $oid string oid to translate
375
-	* @return mixed : null if not found or array(MIB,Name)
376
-	*/
374
+	 * @param $oid string oid to translate
375
+	 * @return mixed : null if not found or array(MIB,Name)
376
+	 */
377 377
 	public function translateOID($oid)
378 378
 	{
379 379
 		// try from database
@@ -406,7 +406,7 @@  discard block
 block discarded – undo
406 406
 		
407 407
 		// Try to get oid name from snmptranslate
408 408
 		$translate=exec($this->snmptranslate . ' -m ALL -M +'.$this->snmptranslate_dirs.
409
-		    ' '.$oid);
409
+			' '.$oid);
410 410
 		$matches=array();
411 411
 		$ret_code=preg_match('/(.*)::(.*)/',$translate,$matches);
412 412
 		if ($ret_code===0 || $ret_code === false) {
@@ -419,9 +419,9 @@  discard block
 block discarded – undo
419 419
 	
420 420
 	/** 
421 421
 	 * Erase old trap records 
422
-	*	@param integer $days : erase traps when more than $days old
423
-	*	@return integer : number of lines deleted
424
-	**/
422
+	 *	@param integer $days : erase traps when more than $days old
423
+	 *	@return integer : number of lines deleted
424
+	 **/
425 425
 	public function eraseOldTraps($days=0)
426 426
 	{
427 427
 		if ($days==0)
@@ -446,72 +446,72 @@  discard block
 block discarded – undo
446 446
 	public function writeTrapErrorToDB($message,$sourceIP=null,$trapoid=null)
447 447
 	{
448 448
 	    
449
-	    $db_conn=$this->trapsDB->db_connect_trap();
449
+		$db_conn=$this->trapsDB->db_connect_trap();
450 450
 	    
451
-	    // add date time
452
-	    $insert_col ='date_received,status';
453
-	    $insert_val = "'" . date("Y-m-d H:i:s")."','error'";
451
+		// add date time
452
+		$insert_col ='date_received,status';
453
+		$insert_val = "'" . date("Y-m-d H:i:s")."','error'";
454 454
         
455
-	    if ($sourceIP !=null)
456
-	    {
457
-	        $insert_col .=',source_ip';
458
-	        $insert_val .=",'". $sourceIP ."'";
459
-	    }
460
-	    if ($trapoid !=null)
461
-	    {
462
-	        $insert_col .=',trap_oid';
463
-	        $insert_val .=",'". $trapoid ."'";
464
-	    }
465
-	    $insert_col .=',status_detail';
466
-	    $insert_val .=",'". $message ."'";
455
+		if ($sourceIP !=null)
456
+		{
457
+			$insert_col .=',source_ip';
458
+			$insert_val .=",'". $sourceIP ."'";
459
+		}
460
+		if ($trapoid !=null)
461
+		{
462
+			$insert_col .=',trap_oid';
463
+			$insert_val .=",'". $trapoid ."'";
464
+		}
465
+		$insert_col .=',status_detail';
466
+		$insert_val .=",'". $message ."'";
467 467
 	    
468
-	    $sql= 'INSERT INTO '.$this->db_prefix.'received (' . $insert_col . ') VALUES ('.$insert_val.')';
468
+		$sql= 'INSERT INTO '.$this->db_prefix.'received (' . $insert_col . ') VALUES ('.$insert_val.')';
469 469
 	    
470
-	    switch ($this->trapsDB->trapDBType)
471
-	    {
472
-	        case 'pgsql':
473
-	            $sql .= ' RETURNING id;';
474
-	            $this->logging->log('sql : '.$sql,INFO);
475
-	            if (($ret_code=$db_conn->query($sql)) === false) {
476
-	                $this->logging->log('Error SQL insert : '.$sql,1,'');
477
-	            }
478
-	            $this->logging->log('SQL insertion OK',INFO );
479
-	            // Get last id to insert oid/values in secondary table
480
-	            if (($inserted_id_ret=$ret_code->fetch(PDO::FETCH_ASSOC)) === false) {
470
+		switch ($this->trapsDB->trapDBType)
471
+		{
472
+			case 'pgsql':
473
+				$sql .= ' RETURNING id;';
474
+				$this->logging->log('sql : '.$sql,INFO);
475
+				if (($ret_code=$db_conn->query($sql)) === false) {
476
+					$this->logging->log('Error SQL insert : '.$sql,1,'');
477
+				}
478
+				$this->logging->log('SQL insertion OK',INFO );
479
+				// Get last id to insert oid/values in secondary table
480
+				if (($inserted_id_ret=$ret_code->fetch(PDO::FETCH_ASSOC)) === false) {
481 481
 	                
482
-	                $this->logging->log('Erreur recuperation id',1,'');
483
-	            }
484
-	            if (! isset($inserted_id_ret['id'])) {
485
-	                $this->logging->log('Error getting id',1,'');
486
-	            }
487
-	            $this->trap_id=$inserted_id_ret['id'];
488
-	            break;
489
-	        case 'mysql':
490
-	            $sql .= ';';
491
-	            $this->logging->log('sql : '.$sql,INFO );
492
-	            if ($db_conn->query($sql) === false) {
493
-	                $this->logging->log('Error SQL insert : '.$sql,1,'');
494
-	            }
495
-	            $this->logging->log('SQL insertion OK',INFO );
496
-	            // Get last id to insert oid/values in secondary table
497
-	            $sql='SELECT LAST_INSERT_ID();';
498
-	            if (($ret_code=$db_conn->query($sql)) === false) {
499
-	                $this->logging->log('Erreur recuperation id',1,'');
500
-	            }
482
+					$this->logging->log('Erreur recuperation id',1,'');
483
+				}
484
+				if (! isset($inserted_id_ret['id'])) {
485
+					$this->logging->log('Error getting id',1,'');
486
+				}
487
+				$this->trap_id=$inserted_id_ret['id'];
488
+				break;
489
+			case 'mysql':
490
+				$sql .= ';';
491
+				$this->logging->log('sql : '.$sql,INFO );
492
+				if ($db_conn->query($sql) === false) {
493
+					$this->logging->log('Error SQL insert : '.$sql,1,'');
494
+				}
495
+				$this->logging->log('SQL insertion OK',INFO );
496
+				// Get last id to insert oid/values in secondary table
497
+				$sql='SELECT LAST_INSERT_ID();';
498
+				if (($ret_code=$db_conn->query($sql)) === false) {
499
+					$this->logging->log('Erreur recuperation id',1,'');
500
+				}
501 501
 	            
502
-	            $inserted_id=$ret_code->fetch(PDO::FETCH_ASSOC)['LAST_INSERT_ID()'];
503
-	            if ($inserted_id==false) throw new Exception("Weird SQL error : last_insert_id returned false : open issue");
504
-	            $this->trap_id=$inserted_id;
505
-	            break;
506
-	        default:
507
-	            $this->logging->log('Error SQL type unknown  : '.$this->trapsDB->trapDBType,1,'');
508
-	    }
502
+				$inserted_id=$ret_code->fetch(PDO::FETCH_ASSOC)['LAST_INSERT_ID()'];
503
+				if ($inserted_id==false) throw new Exception("Weird SQL error : last_insert_id returned false : open issue");
504
+				$this->trap_id=$inserted_id;
505
+				break;
506
+			default:
507
+				$this->logging->log('Error SQL type unknown  : '.$this->trapsDB->trapDBType,1,'');
508
+		}
509 509
 	    
510
-	    $this->logging->log('id found: '. $this->trap_id,INFO );    
510
+		$this->logging->log('id found: '. $this->trap_id,INFO );    
511 511
 	}
512 512
 	
513 513
 	/** Write trap data to trap database
514
-	*/
514
+	 */
515 515
 	public function writeTrapToDB()
516 516
 	{
517 517
 		
@@ -609,10 +609,10 @@  discard block
 block discarded – undo
609 609
 	}
610 610
 
611 611
 	/** Get rules from rule database with ip and oid
612
-	*	@param $ip string ipv4 or ipv6
613
-	*	@param $oid string oid in numeric
614
-	*	@return mixed : PDO object or false
615
-	*/	
612
+	 *	@param $ip string ipv4 or ipv6
613
+	 *	@param $oid string oid in numeric
614
+	 *	@return mixed : PDO object or false
615
+	 */	
616 616
 	protected function getRules($ip,$oid)
617 617
 	{
618 618
 		$db_conn=$this->trapsDB->db_connect_trap();
@@ -671,9 +671,9 @@  discard block
 block discarded – undo
671 671
 	}
672 672
 
673 673
 	/** Add rule match to rule
674
-	*	@param id int : rule id
675
-	*   @param set int : value to set
676
-	*/
674
+	 *	@param id int : rule id
675
+	 *   @param set int : value to set
676
+	 */
677 677
 	protected function add_rule_match($id, $set)
678 678
 	{
679 679
 		$db_conn=$this->trapsDB->db_connect_trap();
@@ -690,53 +690,53 @@  discard block
 block discarded – undo
690 690
 	 * @param integer $state numerical staus 
691 691
 	 * @param string $display
692 692
 	 * @returnn bool true is service check was sent without error
693
-	*/
693
+	 */
694 694
 	public function serviceCheckResult($host,$service,$state,$display)
695 695
 	{
696
-	    if ($this->api_use === false)
697
-	    {
698
-    		$send = '[' . date('U') .'] PROCESS_SERVICE_CHECK_RESULT;' .
699
-    			$host.';' .$service .';' . $state . ';'.$display;
700
-    		$this->logging->log( $send." : to : " .$this->icinga2cmd,INFO );
696
+		if ($this->api_use === false)
697
+		{
698
+			$send = '[' . date('U') .'] PROCESS_SERVICE_CHECK_RESULT;' .
699
+				$host.';' .$service .';' . $state . ';'.$display;
700
+			$this->logging->log( $send." : to : " .$this->icinga2cmd,INFO );
701 701
     		
702
-    		// TODO : file_put_contents & fopen (,'w' or 'a') does not work. See why. Or not as using API will be by default....
703
-    		exec('echo "'.$send.'" > ' .$this->icinga2cmd);
704
-    		return true;
705
-	    }
706
-	    else
707
-	    {
708
-	        $api = $this->getAPI();
709
-	        $api->setCredentials($this->api_username, $this->api_password);
710
-	        list($retcode,$retmessage)=$api->serviceCheckResult($host,$service,$state,$display);
711
-	        if ($retcode == false)
712
-	        {
713
-	            $this->logging->log( "Error sending result : " .$retmessage,WARN,'');
714
-	            return false;
715
-	        }
716
-	        else 
717
-	        {
718
-	            $this->logging->log( "Sent result : " .$retmessage,INFO );
719
-	            return true;
720
-	        }
721
-	    }
702
+			// TODO : file_put_contents & fopen (,'w' or 'a') does not work. See why. Or not as using API will be by default....
703
+			exec('echo "'.$send.'" > ' .$this->icinga2cmd);
704
+			return true;
705
+		}
706
+		else
707
+		{
708
+			$api = $this->getAPI();
709
+			$api->setCredentials($this->api_username, $this->api_password);
710
+			list($retcode,$retmessage)=$api->serviceCheckResult($host,$service,$state,$display);
711
+			if ($retcode == false)
712
+			{
713
+				$this->logging->log( "Error sending result : " .$retmessage,WARN,'');
714
+				return false;
715
+			}
716
+			else 
717
+			{
718
+				$this->logging->log( "Sent result : " .$retmessage,INFO );
719
+				return true;
720
+			}
721
+		}
722 722
 	}
723 723
 	
724 724
 	public function getHostByIP($ip)
725 725
 	{
726
-	    $api = $this->getAPI();
727
-	    $api->setCredentials($this->api_username, $this->api_password);
728
-	    return $api->getHostByIP($ip);
726
+		$api = $this->getAPI();
727
+		$api->setCredentials($this->api_username, $this->api_password);
728
+		return $api->getHostByIP($ip);
729 729
 	}
730 730
 	
731 731
 	/** Resolve display. 
732
-	*	Changes OID(<oid>) to value if found or text "<not in trap>"
733
-	*	@param $display string
734
-	*	@return string display
735
-	*/
732
+	 *	Changes OID(<oid>) to value if found or text "<not in trap>"
733
+	 *	@param $display string
734
+	 *	@return string display
735
+	 */
736 736
 	protected function applyDisplay($display)
737 737
 	{
738
-	    $matches=array();
739
-	    while (preg_match('/_OID\(([0-9\.]+)\)/',$display,$matches) == 1)
738
+		$matches=array();
739
+		while (preg_match('/_OID\(([0-9\.]+)\)/',$display,$matches) == 1)
740 740
 		{
741 741
 			$oid=$matches[1];
742 742
 			$found=0;
@@ -796,11 +796,11 @@  discard block
 block discarded – undo
796 796
 		
797 797
 		if ($rule[$item] == '(')
798 798
 		{ // grouping
799
-		    $item++;
799
+			$item++;
800 800
 			$start=$item;
801 801
 			$parenthesis_count=0; 
802 802
 			while (($item < strlen($rule)) // Not end of string AND
803
-			      && ( ($rule[$item] != ')' ) || $parenthesis_count > 0) ) // Closing ')' or embeded ()
803
+				  && ( ($rule[$item] != ')' ) || $parenthesis_count > 0) ) // Closing ')' or embeded ()
804 804
 			{ 
805 805
 				if ($rule[$item] == '"' )
806 806
 				{ // pass through string
@@ -808,14 +808,14 @@  discard block
 block discarded – undo
808 808
 					$item=$this->eval_getNext($rule,$item,'"');
809 809
 				} 
810 810
 				else{
811
-				    if ($rule[$item] == '(')
812
-				    {
813
-				        $parenthesis_count++;
814
-				    }
815
-				    if ($rule[$item] == ')')
816
-				    {
817
-				        $parenthesis_count--;
818
-				    }
811
+					if ($rule[$item] == '(')
812
+					{
813
+						$parenthesis_count++;
814
+					}
815
+					if ($rule[$item] == ')')
816
+					{
817
+						$parenthesis_count--;
818
+					}
819 819
 					$item++;
820 820
 				}
821 821
 			}
@@ -867,24 +867,24 @@  discard block
 block discarded – undo
867 867
 	}
868 868
 	
869 869
 	/** Evaluation : makes token and evaluate. 
870
-	*	Public function for expressions testing
871
-	*	accepts : < > = <= >= !=  (typec = 0)
872
-	*	operators : & | (typec=1)
873
-	*	with : integers/float  (type 0) or strings "" (type 1) or results (type 2)
874
-	*   comparison int vs strings will return null (error)
875
-	*	return : bool or null on error
876
-	*/
870
+	 *	Public function for expressions testing
871
+	 *	accepts : < > = <= >= !=  (typec = 0)
872
+	 *	operators : & | (typec=1)
873
+	 *	with : integers/float  (type 0) or strings "" (type 1) or results (type 2)
874
+	 *   comparison int vs strings will return null (error)
875
+	 *	return : bool or null on error
876
+	 */
877 877
 	public function evaluation($rule,&$item)
878 878
 	{
879
-	    //echo "Evaluation of ".substr($rule,$item)."\n";
879
+		//echo "Evaluation of ".substr($rule,$item)."\n";
880 880
 		if ( $rule[$item] == '!') // If '!' found, negate next expression.
881 881
 		{
882
-		    $negate=true;
883
-		    $item++;
882
+			$negate=true;
883
+			$item++;
884 884
 		}
885 885
 		else
886 886
 		{
887
-		    $negate=false;
887
+			$negate=false;
888 888
 		}
889 889
 		// First element : number, string or ()
890 890
 		list($type1,$val1) = $this->eval_getElement($rule,$item);
@@ -904,24 +904,24 @@  discard block
 block discarded – undo
904 904
 		// Third element : number, string or ()
905 905
 		if ( $rule[$item] == '!') // starts with a ! so evaluate whats next
906 906
 		{
907
-		    $item++;
908
-		    if ($typec != 1) throw new Exception("Mixing boolean and comparison : ".$rule);
909
-		    $val2= ! $this->evaluation($rule,$item);
910
-		    $type2=2; // result is a boolean 
907
+			$item++;
908
+			if ($typec != 1) throw new Exception("Mixing boolean and comparison : ".$rule);
909
+			$val2= ! $this->evaluation($rule,$item);
910
+			$type2=2; // result is a boolean 
911 911
 		}
912 912
 		else 
913 913
 		{
914
-		    list($type2,$val2) = $this->eval_getElement($rule,$item);
914
+			list($type2,$val2) = $this->eval_getElement($rule,$item);
915 915
 		}
916 916
 		//echo "Elmt2: ".$val2."/".$type2." : ".substr($rule,$item)."\n";
917 917
 		
918 918
 		if ($type1!=$type2)  // cannot compare different types
919 919
 		{ 
920
-		    throw new Exception("Cannot compare string & number : ".$rule);
920
+			throw new Exception("Cannot compare string & number : ".$rule);
921 921
 		}
922 922
 		if ($typec==1 && $type1 !=2) // cannot use & or | with string/number
923 923
 		{
924
-		    throw new Exception("Cannot use boolean operators with string & number : ".$rule);
924
+			throw new Exception("Cannot use boolean operators with string & number : ".$rule);
925 925
 		}
926 926
 		
927 927
 		switch ($comp){
@@ -979,9 +979,9 @@  discard block
 block discarded – undo
979 979
 	}		
980 980
 	
981 981
 	/** Evaluation rule (uses eval_* functions recursively)
982
-	*	@param $rule string rule ( _OID(.1.3.6.1.4.1.8072.2.3.2.1)=_OID(.1.3.6.1.2.1.1.3.0) )
983
-	*	@return bool : true : rule match, false : rule don't match , throw exception on error.
984
-	*/
982
+	 *	@param $rule string rule ( _OID(.1.3.6.1.4.1.8072.2.3.2.1)=_OID(.1.3.6.1.2.1.1.3.0) )
983
+	 *	@return bool : true : rule match, false : rule don't match , throw exception on error.
984
+	 */
985 985
 	
986 986
 	protected function eval_rule($rule)
987 987
 	{
@@ -1026,7 +1026,7 @@  discard block
 block discarded – undo
1026 1026
 			}
1027 1027
 			if ($found==0)
1028 1028
 			{	// OID not found : throw error
1029
-			    throw new Exception('OID '.$oid.' not found in trap');
1029
+				throw new Exception('OID '.$oid.' not found in trap');
1030 1030
 			}
1031 1031
 		}
1032 1032
 		$item=0;
@@ -1037,7 +1037,7 @@  discard block
 block discarded – undo
1037 1037
 	}
1038 1038
 	
1039 1039
 	/** Match rules for current trap and do action
1040
-	*/
1040
+	 */
1041 1041
 	public function applyRules()
1042 1042
 	{
1043 1043
 		$rules = $this->getRules($this->trap_data['source_ip'],$this->trap_data['trap_oid']);
@@ -1074,12 +1074,12 @@  discard block
 block discarded – undo
1074 1074
 					{
1075 1075
 						if ($this->serviceCheckResult($host_name,$service_name,$action,$display) == false)
1076 1076
 						{
1077
-						    $this->trap_action.='Error sending status : check cmd/API';
1077
+							$this->trap_action.='Error sending status : check cmd/API';
1078 1078
 						}
1079 1079
 						else
1080 1080
 						{
1081
-						    $this->add_rule_match($rule['id'],$rule['num_match']+1);
1082
-						    $this->trap_action.='Status '.$action.' to '.$host_name.'/'.$service_name;
1081
+							$this->add_rule_match($rule['id'],$rule['num_match']+1);
1082
+							$this->trap_action.='Status '.$action.' to '.$host_name.'/'.$service_name;
1083 1083
 						}
1084 1084
 					}
1085 1085
 					else
@@ -1096,15 +1096,15 @@  discard block
 block discarded – undo
1096 1096
 					$this->logging->log('action NOK : '.$action,INFO );
1097 1097
 					if ($action >= 0)
1098 1098
 					{
1099
-					    if ($this->serviceCheckResult($host_name,$service_name,$action,$display)==false)
1100
-					    {
1101
-					        $this->trap_action.='Error sending status : check cmd/API';
1102
-					    }
1103
-					    else
1104
-					    {
1105
-    						$this->add_rule_match($rule['id'],$rule['num_match']+1);
1106
-    						$this->trap_action.='Status '.$action.' to '.$host_name.'/'.$service_name;
1107
-					    }
1099
+						if ($this->serviceCheckResult($host_name,$service_name,$action,$display)==false)
1100
+						{
1101
+							$this->trap_action.='Error sending status : check cmd/API';
1102
+						}
1103
+						else
1104
+						{
1105
+							$this->add_rule_match($rule['id'],$rule['num_match']+1);
1106
+							$this->trap_action.='Status '.$action.' to '.$host_name.'/'.$service_name;
1107
+						}
1108 1108
 					}
1109 1109
 					else
1110 1110
 					{
@@ -1127,9 +1127,9 @@  discard block
 block discarded – undo
1127 1127
 			}
1128 1128
 			catch (Exception $e) 
1129 1129
 			{ 
1130
-			    $this->logging->log('Error in rule eval : '.$e->getMessage(),WARN,'');
1131
-			    $this->trap_action.=' ERR : '.$e->getMessage();
1132
-			    $this->trap_data['status']='error';
1130
+				$this->logging->log('Error in rule eval : '.$e->getMessage(),WARN,'');
1131
+				$this->trap_action.=' ERR : '.$e->getMessage();
1132
+				$this->trap_data['status']='error';
1133 1133
 			}
1134 1134
 			
1135 1135
 		}
@@ -1144,8 +1144,8 @@  discard block
 block discarded – undo
1144 1144
 	}
1145 1145
 
1146 1146
 	/** Add Time a action to rule
1147
-	*	@param string $time : time to process to insert in SQL
1148
-	*/
1147
+	 *	@param string $time : time to process to insert in SQL
1148
+	 */
1149 1149
 	public function add_rule_final($time)
1150 1150
 	{
1151 1151
 		$db_conn=$this->trapsDB->db_connect_trap();
@@ -1162,9 +1162,9 @@  discard block
 block discarded – undo
1162 1162
 	/*********** UTILITIES *********************/
1163 1163
 	
1164 1164
 	/** reset service to OK after time defined in rule
1165
-	*	TODO logic is : get all service in error + all rules, see if getting all rules then select services is better 
1166
-	*	@return integer : not in use
1167
-	**/
1165
+	 *	TODO logic is : get all service in error + all rules, see if getting all rules then select services is better 
1166
+	 *	@return integer : not in use
1167
+	 **/
1168 1168
 	public function reset_services()
1169 1169
 	{
1170 1170
 		// Get all services not in 'ok' state
Please login to merge, or discard this patch.
Braces   +89 added lines, -58 removed lines patch added patch discarded remove patch
@@ -68,9 +68,9 @@  discard block
 block discarded – undo
68 68
 		{
69 69
 		    $this->logging->setLogging($baseLogLevel, $baseLogMode,$baseLogFile);
70 70
 		    $this->logSetup=true;
71
+		} else {
72
+				    $this->logSetup=false;
71 73
 		}
72
-		else
73
-		    $this->logSetup=false;
74 74
 		$this->logging->log('Loggin started', INFO);
75 75
 
76 76
 		// Get options from ini files
@@ -83,7 +83,10 @@  discard block
 block discarded – undo
83 83
 		$this->setupDatabase($trapConfig); // Setup database class
84 84
 		
85 85
 		$this->getDatabaseOptions(); // Get options in database
86
-		if ($this->api_use === true) $this->getAPI(); // Setup API
86
+		if ($this->api_use === true) {
87
+			$this->getAPI();
88
+		}
89
+		// Setup API
87 90
 		
88 91
 		$this->mibClass = new Mib($this->logging,$this->trapsDB,$this->snmptranslate,$this->snmptranslate_dirs); // Create Mib class
89 92
 		
@@ -117,8 +120,7 @@  discard block
 block discarded – undo
117 120
 	        }
118 121
 	        $this->logging->log($message,$log_level,'syslog');
119 122
 	        return false;
120
-	    }
121
-	    else
123
+	    } else
122 124
 	    {
123 125
 	        $option_var=$option_array[$option_category][$option_name];
124 126
 	        return true;
@@ -182,7 +184,10 @@  discard block
 block discarded – undo
182 184
 	    
183 185
 	    $this->trapsDB = new Database($this->logging,$dbConfig[$dbTrapName],$this->db_prefix);
184 186
 	    
185
-	    if ($this->api_use === true) return; // In case of API use, no IDO is necessary
187
+	    if ($this->api_use === true) {
188
+	    	return;
189
+	    }
190
+	    // In case of API use, no IDO is necessary
186 191
         
187 192
 	    // IDO Database
188 193
 	    if (!array_key_exists('IDOdatabase',$trapConfig['config']))
@@ -207,9 +212,11 @@  discard block
 block discarded – undo
207 212
 	protected function getDatabaseOptions()
208 213
 	{
209 214
 		// Database options
210
-		if ($this->logSetup === false) // Only if logging was no setup in constructor
215
+		if ($this->logSetup === false) {
216
+			// Only if logging was no setup in constructor
211 217
 		{
212 218
     		$this->getDBConfigIfSet('log_level',$this->logging->debugLevel);
219
+		}
213 220
     		$this->getDBConfigIfSet('log_destination',$this->logging->outputMode);
214 221
     		$this->getDBConfigIfSet('log_file',$this->logging->outputFile);
215 222
 		}
@@ -218,7 +225,9 @@  discard block
 block discarded – undo
218 225
 	protected function getDBConfigIfSet($element,&$variable)
219 226
 	{
220 227
 		$value=$this->getDBConfig($element);
221
-		if ($value != 'null') $variable=$value;
228
+		if ($value != 'null') {
229
+			$variable=$value;
230
+		}
222 231
 	}
223 232
 	
224 233
 	/** 
@@ -306,8 +315,7 @@  discard block
 block discarded – undo
306 315
 		{
307 316
 		    $this->writeTrapErrorToDB("Error parsing trap (code 2/IP)");
308 317
 			$this->logging->log('Error parsing IP : '.$IP,ERROR,'');
309
-		} 
310
-		else 
318
+		} else 
311 319
 		{		
312 320
 			$this->trap_data['source_ip']=$matches[1];
313 321
 			$this->trap_data['destination_ip']=$matches[3];
@@ -322,14 +330,12 @@  discard block
 block discarded – undo
322 330
 			if ($ret_code===0 || $ret_code===false) 
323 331
 			{
324 332
 				$this->logging->log('No match on trap data : '.$vars,WARN,'');
325
-			}
326
-			else 
333
+			} else 
327 334
 			{
328 335
 			    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'))
329 336
 				{
330 337
 					$this->trap_data['trap_oid']=$matches[2];				
331
-				}
332
-				else
338
+				} else
333 339
 				{
334 340
 					$object= new stdClass;
335 341
 					$object->oid =$matches[1];
@@ -500,7 +506,9 @@  discard block
 block discarded – undo
500 506
 	            }
501 507
 	            
502 508
 	            $inserted_id=$ret_code->fetch(PDO::FETCH_ASSOC)['LAST_INSERT_ID()'];
503
-	            if ($inserted_id==false) throw new Exception("Weird SQL error : last_insert_id returned false : open issue");
509
+	            if ($inserted_id==false) {
510
+	            	throw new Exception("Weird SQL error : last_insert_id returned false : open issue");
511
+	            }
504 512
 	            $this->trap_id=$inserted_id;
505 513
 	            break;
506 514
 	        default:
@@ -516,7 +524,9 @@  discard block
 block discarded – undo
516 524
 	{
517 525
 		
518 526
 		// If action is ignore -> don't send t DB
519
-		if ($this->trap_to_db === false) return;
527
+		if ($this->trap_to_db === false) {
528
+			return;
529
+		}
520 530
 		
521 531
 		
522 532
 		$db_conn=$this->trapsDB->db_connect_trap();
@@ -573,7 +583,9 @@  discard block
 block discarded – undo
573 583
 				}
574 584
 
575 585
 				$inserted_id=$ret_code->fetch(PDO::FETCH_ASSOC)['LAST_INSERT_ID()'];
576
-				if ($inserted_id==false) throw new Exception("Weird SQL error : last_insert_id returned false : open issue");
586
+				if ($inserted_id==false) {
587
+					throw new Exception("Weird SQL error : last_insert_id returned false : open issue");
588
+				}
577 589
 				$this->trap_id=$inserted_id;
578 590
 			break;
579 591
 			default: 
@@ -702,8 +714,7 @@  discard block
 block discarded – undo
702 714
     		// TODO : file_put_contents & fopen (,'w' or 'a') does not work. See why. Or not as using API will be by default....
703 715
     		exec('echo "'.$send.'" > ' .$this->icinga2cmd);
704 716
     		return true;
705
-	    }
706
-	    else
717
+	    } else
707 718
 	    {
708 719
 	        $api = $this->getAPI();
709 720
 	        $api->setCredentials($this->api_username, $this->api_password);
@@ -712,8 +723,7 @@  discard block
 block discarded – undo
712 723
 	        {
713 724
 	            $this->logging->log( "Error sending result : " .$retmessage,WARN,'');
714 725
 	            return false;
715
-	        }
716
-	        else 
726
+	        } else 
717 727
 	        {
718 728
 	            $this->logging->log( "Sent result : " .$retmessage,INFO );
719 729
 	            return true;
@@ -773,7 +783,9 @@  discard block
 block discarded – undo
773 783
 	/***************** Eval & tokenizer functions ****************/
774 784
 	protected function eval_getElement($rule,&$item)
775 785
 	{
776
-		while ($rule[$item]==' ') $item++;
786
+		while ($rule[$item]==' ') {
787
+			$item++;
788
+		}
777 789
 		if (preg_match('/[0-9\.]/',$rule[$item]))
778 790
 		{ // number
779 791
 	
@@ -800,14 +812,15 @@  discard block
 block discarded – undo
800 812
 			$start=$item;
801 813
 			$parenthesis_count=0; 
802 814
 			while (($item < strlen($rule)) // Not end of string AND
803
-			      && ( ($rule[$item] != ')' ) || $parenthesis_count > 0) ) // Closing ')' or embeded ()
815
+			      && ( ($rule[$item] != ')' ) || $parenthesis_count > 0) ) {
816
+				// Closing ')' or embeded ()
804 817
 			{ 
805 818
 				if ($rule[$item] == '"' )
806 819
 				{ // pass through string
807 820
 					$item++;
821
+			}
808 822
 					$item=$this->eval_getNext($rule,$item,'"');
809
-				} 
810
-				else{
823
+				} else{
811 824
 				    if ($rule[$item] == '(')
812 825
 				    {
813 826
 				        $parenthesis_count++;
@@ -835,13 +848,17 @@  discard block
 block discarded – undo
835 848
 	protected function eval_getNext($rule,$item,$tok)
836 849
 	{
837 850
 		while (($rule[$item] != $tok ) && ($item < strlen($rule))) { $item++;}
838
-		if ($item==strlen($rule)) throw new Exception("closing '".$tok."' not found in ".$rule ." at " .$item);
851
+		if ($item==strlen($rule)) {
852
+			throw new Exception("closing '".$tok."' not found in ".$rule ." at " .$item);
853
+		}
839 854
 		return $item+1;
840 855
 	}
841 856
 	
842 857
 	protected function eval_getOper($rule,&$item)
843 858
 	{
844
-		while ($rule[$item]==' ') $item++;
859
+		while ($rule[$item]==' ') {
860
+			$item++;
861
+		}
845 862
 		switch ($rule[$item])
846 863
 		{
847 864
 			case '<':
@@ -877,12 +894,13 @@  discard block
 block discarded – undo
877 894
 	public function evaluation($rule,&$item)
878 895
 	{
879 896
 	    //echo "Evaluation of ".substr($rule,$item)."\n";
880
-		if ( $rule[$item] == '!') // If '!' found, negate next expression.
897
+		if ( $rule[$item] == '!') {
898
+			// If '!' found, negate next expression.
881 899
 		{
882 900
 		    $negate=true;
883
-		    $item++;
884 901
 		}
885
-		else
902
+		    $item++;
903
+		} else
886 904
 		{
887 905
 		    $negate=false;
888 906
 		}
@@ -890,10 +908,14 @@  discard block
 block discarded – undo
890 908
 		list($type1,$val1) = $this->eval_getElement($rule,$item);
891 909
 		//echo "Elmt1: ".$val1."/".$type1." : ".substr($rule,$item)."\n";
892 910
 		
893
-		if ($item==strlen($rule)) // If only element, return value, but only boolean
911
+		if ($item==strlen($rule)) {
912
+			// If only element, return value, but only boolean
894 913
 		{
895 914
 		  if ($type1 != 2) throw new Exception("Cannot use num/string as boolean : ".$rule);
896
-		  if ($negate === true) $val1= ! $val1;
915
+		}
916
+		  if ($negate === true) {
917
+		  	$val1= ! $val1;
918
+		  }
897 919
 		  return $val1;
898 920
 		}  
899 921
 		
@@ -902,27 +924,34 @@  discard block
 block discarded – undo
902 924
 		//echo "Comp : ".$comp." : ".substr($rule,$item)."\n";
903 925
         
904 926
 		// Third element : number, string or ()
905
-		if ( $rule[$item] == '!') // starts with a ! so evaluate whats next
927
+		if ( $rule[$item] == '!') {
928
+			// starts with a ! so evaluate whats next
906 929
 		{
907 930
 		    $item++;
908
-		    if ($typec != 1) throw new Exception("Mixing boolean and comparison : ".$rule);
931
+		}
932
+		    if ($typec != 1) {
933
+		    	throw new Exception("Mixing boolean and comparison : ".$rule);
934
+		    }
909 935
 		    $val2= ! $this->evaluation($rule,$item);
910 936
 		    $type2=2; // result is a boolean 
911
-		}
912
-		else 
937
+		} else 
913 938
 		{
914 939
 		    list($type2,$val2) = $this->eval_getElement($rule,$item);
915 940
 		}
916 941
 		//echo "Elmt2: ".$val2."/".$type2." : ".substr($rule,$item)."\n";
917 942
 		
918
-		if ($type1!=$type2)  // cannot compare different types
943
+		if ($type1!=$type2) {
944
+			// cannot compare different types
919 945
 		{ 
920 946
 		    throw new Exception("Cannot compare string & number : ".$rule);
921 947
 		}
922
-		if ($typec==1 && $type1 !=2) // cannot use & or | with string/number
948
+		}
949
+		if ($typec==1 && $type1 !=2) {
950
+			// cannot use & or | with string/number
923 951
 		{
924 952
 		    throw new Exception("Cannot use boolean operators with string & number : ".$rule);
925 953
 		}
954
+		}
926 955
 		
927 956
 		switch ($comp){
928 957
 			case '<':	$retVal= ($val1 < $val2); break;
@@ -936,9 +965,15 @@  discard block
 block discarded – undo
936 965
 			case '&':	$retVal= ($val1 && $val2); break;
937 966
 			default:  throw new Exception("Error in expression - unknown comp : ".$comp);
938 967
 		}
939
-		if ($negate === true) $retVal = ! $retVal; // Inverse result if negate before expression
968
+		if ($negate === true) {
969
+			$retVal = ! $retVal;
970
+		}
971
+		// Inverse result if negate before expression
940 972
 		
941
-		if ($item==strlen($rule)) return $retVal; // End of string : return evaluation
973
+		if ($item==strlen($rule)) {
974
+			return $retVal;
975
+		}
976
+		// End of string : return evaluation
942 977
 		// check for logical operator :
943 978
 		switch ($rule[$item])
944 979
 		{
@@ -965,7 +1000,9 @@  discard block
 block discarded – undo
965 1000
 					$rule2.=$rule[$item];
966 1001
 					$item++;
967 1002
 				}
968
-				if ($item == strlen ($rule)) throw new Exception("closing '\"' not found in ".$rule ." at " .$item);
1003
+				if ($item == strlen ($rule)) {
1004
+					throw new Exception("closing '\"' not found in ".$rule ." at " .$item);
1005
+				}
969 1006
 				$rule2.=$rule[$item];
970 1007
 				$item++;
971 1008
 				continue;
@@ -985,10 +1022,12 @@  discard block
 block discarded – undo
985 1022
 	
986 1023
 	protected function eval_rule($rule)
987 1024
 	{
988
-		if ($rule==null || $rule == '') // Empty rule is always true
1025
+		if ($rule==null || $rule == '') {
1026
+			// Empty rule is always true
989 1027
 		{
990 1028
 			return true;
991 1029
 		}
1030
+		}
992 1031
 		$matches=array();
993 1032
 		while (preg_match('/_OID\(([0-9\.\*]+)\)/',$rule,$matches) == 1)
994 1033
 		{
@@ -1075,20 +1114,17 @@  discard block
 block discarded – undo
1075 1114
 						if ($this->serviceCheckResult($host_name,$service_name,$action,$display) == false)
1076 1115
 						{
1077 1116
 						    $this->trap_action.='Error sending status : check cmd/API';
1078
-						}
1079
-						else
1117
+						} else
1080 1118
 						{
1081 1119
 						    $this->add_rule_match($rule['id'],$rule['num_match']+1);
1082 1120
 						    $this->trap_action.='Status '.$action.' to '.$host_name.'/'.$service_name;
1083 1121
 						}
1084
-					}
1085
-					else
1122
+					} else
1086 1123
 					{
1087 1124
 						$this->add_rule_match($rule['id'],$rule['num_match']+1);
1088 1125
 					}
1089 1126
 					$this->trap_to_db=($action==-2)?false:true;
1090
-				}
1091
-				else
1127
+				} else
1092 1128
 				{
1093 1129
 					//$this->logging->log('rules KOO : '.print_r($rule),INFO );
1094 1130
 					
@@ -1099,14 +1135,12 @@  discard block
 block discarded – undo
1099 1135
 					    if ($this->serviceCheckResult($host_name,$service_name,$action,$display)==false)
1100 1136
 					    {
1101 1137
 					        $this->trap_action.='Error sending status : check cmd/API';
1102
-					    }
1103
-					    else
1138
+					    } else
1104 1139
 					    {
1105 1140
     						$this->add_rule_match($rule['id'],$rule['num_match']+1);
1106 1141
     						$this->trap_action.='Status '.$action.' to '.$host_name.'/'.$service_name;
1107 1142
 					    }
1108
-					}
1109
-					else
1143
+					} else
1110 1144
 					{
1111 1145
 						$this->add_rule_match($rule['id'],$rule['num_match']+1);
1112 1146
 					}
@@ -1116,16 +1150,14 @@  discard block
 block discarded – undo
1116 1150
 				if (!isset($this->trap_data['source_name']))
1117 1151
 				{
1118 1152
 					$this->trap_data['source_name']=$rule['host_name'];
1119
-				}
1120
-				else
1153
+				} else
1121 1154
 				{
1122 1155
 					if (!preg_match('/'.$rule['host_name'].'/',$this->trap_data['source_name']))
1123 1156
 					{ // only add if not present
1124 1157
 						$this->trap_data['source_name'].=','.$rule['host_name'];
1125 1158
 					}
1126 1159
 				}
1127
-			}
1128
-			catch (Exception $e) 
1160
+			} catch (Exception $e) 
1129 1161
 			{ 
1130 1162
 			    $this->logging->log('Error in rule eval : '.$e->getMessage(),WARN,'');
1131 1163
 			    $this->trap_action.=' ERR : '.$e->getMessage();
@@ -1136,8 +1168,7 @@  discard block
 block discarded – undo
1136 1168
 		if ($this->trap_data['status']=='error')
1137 1169
 		{
1138 1170
 		  $this->trap_to_db=true; // Always put errors in DB for the use can see
1139
-		}
1140
-		else
1171
+		} else
1141 1172
 		{
1142 1173
 		  $this->trap_data['status']='done';
1143 1174
 		}
Please login to merge, or discard this patch.
Spacing   +265 added lines, -265 removed lines patch added patch discarded remove patch
@@ -34,8 +34,8 @@  discard block
 block discarded – undo
34 34
 	protected $api_password='';
35 35
 
36 36
 	// Logs 
37
-	protected $logging;    //< Logging class.
38
-	protected $logSetup;   //< bool true if log was setup in constructor
37
+	protected $logging; //< Logging class.
38
+	protected $logSetup; //< bool true if log was setup in constructor
39 39
 	
40 40
 	// Databases
41 41
 	public $trapsDB; //< Database class
@@ -51,7 +51,7 @@  discard block
 block discarded – undo
51 51
 	// Mib update data
52 52
 	public $mibClass; //< Mib class
53 53
 	
54
-	function __construct($etc_dir='/etc/icingaweb2',$baseLogLevel=null,$baseLogMode='syslog',$baseLogFile='')
54
+	function __construct($etc_dir='/etc/icingaweb2', $baseLogLevel=null, $baseLogMode='syslog', $baseLogFile='')
55 55
 	{
56 56
 	    // Paths of ini files
57 57
 		$this->icingaweb2_etc=$etc_dir;
@@ -59,10 +59,10 @@  discard block
 block discarded – undo
59 59
 		$this->icingaweb2_ressources=$this->icingaweb2_etc."/resources.ini";
60 60
 
61 61
 		// Setup logging
62
-		$this->logging = new Logging();
62
+		$this->logging=new Logging();
63 63
 		if ($baseLogLevel != null)
64 64
 		{
65
-		    $this->logging->setLogging($baseLogLevel, $baseLogMode,$baseLogFile);
65
+		    $this->logging->setLogging($baseLogLevel, $baseLogMode, $baseLogFile);
66 66
 		    $this->logSetup=true;
67 67
 		}
68 68
 		else
@@ -70,10 +70,10 @@  discard block
 block discarded – undo
70 70
 		$this->logging->log('Loggin started', INFO);
71 71
 
72 72
 		// Get options from ini files
73
-		$trapConfig=parse_ini_file($this->trap_module_config,true);
73
+		$trapConfig=parse_ini_file($this->trap_module_config, true);
74 74
 		if ($trapConfig == false)
75 75
 		{
76
-		    $this->logging->log("Error reading ini file : ".$this->trap_module_config,ERROR,'syslog');
76
+		    $this->logging->log("Error reading ini file : ".$this->trap_module_config, ERROR, 'syslog');
77 77
 		}
78 78
 		$this->getMainOptions($trapConfig); // Get main options from ini file
79 79
 		$this->setupDatabase($trapConfig); // Setup database class
@@ -81,7 +81,7 @@  discard block
 block discarded – undo
81 81
 		$this->getDatabaseOptions(); // Get options in database
82 82
 		if ($this->api_use === true) $this->getAPI(); // Setup API
83 83
 		
84
-		$this->mibClass = new Mib($this->logging,$this->trapsDB,$this->snmptranslate,$this->snmptranslate_dirs); // Create Mib class
84
+		$this->mibClass=new Mib($this->logging, $this->trapsDB, $this->snmptranslate, $this->snmptranslate_dirs); // Create Mib class
85 85
 		
86 86
 		$this->trap_data=array(
87 87
 			'source_ip'	=> 'unknown',
@@ -103,15 +103,15 @@  discard block
 block discarded – undo
103 103
 	 * @param string $message warning message if not found
104 104
 	 * @return boolean true if found, or false
105 105
 	 */
106
-	protected function getOptionIfSet($option_array,$option_category,$option_name, &$option_var, $log_level = 2, $message = null)
106
+	protected function getOptionIfSet($option_array, $option_category, $option_name, &$option_var, $log_level=2, $message=null)
107 107
 	{
108 108
 	    if (!isset($option_array[$option_category][$option_name]))
109 109
 	    {
110 110
 	        if ($message === null)
111 111
 	        {
112
-	            $message='No ' . $option_name . ' in config file: '. $this->trap_module_config;
112
+	            $message='No '.$option_name.' in config file: '.$this->trap_module_config;
113 113
 	        }
114
-	        $this->logging->log($message,$log_level,'syslog');
114
+	        $this->logging->log($message, $log_level, 'syslog');
115 115
 	        return false;
116 116
 	    }
117 117
 	    else
@@ -129,24 +129,24 @@  discard block
 block discarded – undo
129 129
 	{
130 130
 
131 131
 		// Snmptranslate binary path
132
-		$this->getOptionIfSet($trapConfig,'config','snmptranslate', $this->snmptranslate);
132
+		$this->getOptionIfSet($trapConfig, 'config', 'snmptranslate', $this->snmptranslate);
133 133
 
134 134
 		// mibs path
135
-		$this->getOptionIfSet($trapConfig,'config','snmptranslate_dirs', $this->snmptranslate_dirs);
135
+		$this->getOptionIfSet($trapConfig, 'config', 'snmptranslate_dirs', $this->snmptranslate_dirs);
136 136
 
137 137
 		// icinga2cmd path
138
-		$this->getOptionIfSet($trapConfig,'config','icingacmd', $this->icinga2cmd);
138
+		$this->getOptionIfSet($trapConfig, 'config', 'icingacmd', $this->icinga2cmd);
139 139
 		
140 140
 		// table prefix
141
-		$this->getOptionIfSet($trapConfig,'config','database_prefix', $this->db_prefix);
141
+		$this->getOptionIfSet($trapConfig, 'config', 'database_prefix', $this->db_prefix);
142 142
 
143 143
 		// API options
144
-		if ($this->getOptionIfSet($trapConfig,'config','icingaAPI_host', $this->api_hostname))
144
+		if ($this->getOptionIfSet($trapConfig, 'config', 'icingaAPI_host', $this->api_hostname))
145 145
 		{
146 146
 		    $this->api_use=true;
147
-		    $this->getOptionIfSet($trapConfig,'config','icingaAPI_port', $this->api_port);
148
-		    $this->getOptionIfSet($trapConfig,'config','icingaAPI_user', $this->api_username);
149
-		    $this->getOptionIfSet($trapConfig,'config','icingaAPI_password', $this->api_password);
147
+		    $this->getOptionIfSet($trapConfig, 'config', 'icingaAPI_port', $this->api_port);
148
+		    $this->getOptionIfSet($trapConfig, 'config', 'icingaAPI_user', $this->api_username);
149
+		    $this->getOptionIfSet($trapConfig, 'config', 'icingaAPI_password', $this->api_password);
150 150
 		}
151 151
 	}
152 152
 	
@@ -157,40 +157,40 @@  discard block
 block discarded – undo
157 157
 	protected function setupDatabase($trapConfig)
158 158
 	{
159 159
 	    // Trap database
160
-	    if (!array_key_exists('database',$trapConfig['config']))
160
+	    if (!array_key_exists('database', $trapConfig['config']))
161 161
         {
162
-            $this->logging->log("No database in config file: ".$this->trap_module_config,ERROR,'');
162
+            $this->logging->log("No database in config file: ".$this->trap_module_config, ERROR, '');
163 163
             return;
164 164
         }
165 165
         $dbTrapName=$trapConfig['config']['database'];
166
-        $this->logging->log("Found database in config file: ".$dbTrapName,INFO );
166
+        $this->logging->log("Found database in config file: ".$dbTrapName, INFO);
167 167
 	    
168
-	   if ( ($dbConfig=parse_ini_file($this->icingaweb2_ressources,true)) === false)
168
+	   if (($dbConfig=parse_ini_file($this->icingaweb2_ressources, true)) === false)
169 169
 	    {
170
-	        $this->logging->log("Error reading ini file : ".$this->icingaweb2_ressources,ERROR,'');
170
+	        $this->logging->log("Error reading ini file : ".$this->icingaweb2_ressources, ERROR, '');
171 171
 	        return;
172 172
 	    }
173
-	    if (!array_key_exists($dbTrapName,$dbConfig))
173
+	    if (!array_key_exists($dbTrapName, $dbConfig))
174 174
 	    {
175
-	        $this->logging->log("No database '.$dbTrapName.' in config file: ".$this->icingaweb2_ressources,ERROR,'');
175
+	        $this->logging->log("No database '.$dbTrapName.' in config file: ".$this->icingaweb2_ressources, ERROR, '');
176 176
 	        return;
177 177
 	    }
178 178
 	    
179
-	    $this->trapsDB = new Database($this->logging,$dbConfig[$dbTrapName],$this->db_prefix);
179
+	    $this->trapsDB=new Database($this->logging, $dbConfig[$dbTrapName], $this->db_prefix);
180 180
 	    
181 181
 	    if ($this->api_use === true) return; // In case of API use, no IDO is necessary
182 182
         
183 183
 	    // IDO Database
184
-	    if (!array_key_exists('IDOdatabase',$trapConfig['config']))
184
+	    if (!array_key_exists('IDOdatabase', $trapConfig['config']))
185 185
 	    {
186
-	        $this->logging->log("No IDOdatabase in config file: ".$this->trap_module_config,ERROR,'');
186
+	        $this->logging->log("No IDOdatabase in config file: ".$this->trap_module_config, ERROR, '');
187 187
 	    }
188 188
 	    $dbIdoName=$trapConfig['config']['IDOdatabase'];		
189 189
 
190
-	    $this->logging->log("Found IDO database in config file: ".$dbIdoName,INFO );
191
-        if (!array_key_exists($dbIdoName,$dbConfig))
190
+	    $this->logging->log("Found IDO database in config file: ".$dbIdoName, INFO);
191
+        if (!array_key_exists($dbIdoName, $dbConfig))
192 192
 	    {
193
-	        $this->logging->log("No database '.$dbIdoName.' in config file: ".$this->icingaweb2_ressources,ERROR,'');
193
+	        $this->logging->log("No database '.$dbIdoName.' in config file: ".$this->icingaweb2_ressources, ERROR, '');
194 194
 	        return;
195 195
 	    }
196 196
 	    
@@ -205,13 +205,13 @@  discard block
 block discarded – undo
205 205
 		// Database options
206 206
 		if ($this->logSetup === false) // Only if logging was no setup in constructor
207 207
 		{
208
-    		$this->getDBConfigIfSet('log_level',$this->logging->debugLevel);
209
-    		$this->getDBConfigIfSet('log_destination',$this->logging->outputMode);
210
-    		$this->getDBConfigIfSet('log_file',$this->logging->outputFile);
208
+    		$this->getDBConfigIfSet('log_level', $this->logging->debugLevel);
209
+    		$this->getDBConfigIfSet('log_destination', $this->logging->outputMode);
210
+    		$this->getDBConfigIfSet('log_file', $this->logging->outputFile);
211 211
 		}
212 212
 	}
213 213
 
214
-	protected function getDBConfigIfSet($element,&$variable)
214
+	protected function getDBConfigIfSet($element, &$variable)
215 215
 	{
216 216
 		$value=$this->getDBConfig($element);
217 217
 		if ($value != 'null') $variable=$value;
@@ -227,7 +227,7 @@  discard block
 block discarded – undo
227 227
 		$db_conn=$this->trapsDB->db_connect_trap();
228 228
 		$sql='SELECT value from '.$this->db_prefix.'db_config WHERE ( name=\''.$element.'\' )';
229 229
 		if (($ret_code=$db_conn->query($sql)) === false) {
230
-			$this->logging->log('No result in query : ' . $sql,WARN,'');
230
+			$this->logging->log('No result in query : '.$sql, WARN, '');
231 231
 			return null;
232 232
 		}
233 233
 		$value=$ret_code->fetch();
@@ -244,22 +244,22 @@  discard block
 block discarded – undo
244 244
 	*	@param  string $destination file/syslog/display
245 245
 	*	@return void
246 246
 	**/	
247
-	public function trapLog( $message, $level, $destination ='') // OBSOLETE
247
+	public function trapLog($message, $level, $destination='') // OBSOLETE
248 248
 	{	
249 249
 		// TODO : replace ref with $this->logging->log 
250 250
 	    $this->logging->log($message, $level, $destination);
251 251
 	}
252 252
 	
253
-	public function setLogging($debugLvl,$outputType,$outputOption=null)  // OBSOLETE
253
+	public function setLogging($debugLvl, $outputType, $outputOption=null)  // OBSOLETE
254 254
 	{
255
-		$this->logging->setLogging($debugLvl, $outputType,$outputOption);
255
+		$this->logging->setLogging($debugLvl, $outputType, $outputOption);
256 256
 	}
257 257
 	
258 258
 	protected function getAPI()
259 259
 	{
260 260
 	    if ($this->icinga2api == null)
261 261
 	    {
262
-	        $this->icinga2api = new Icinga2API($this->api_hostname,$this->api_port);
262
+	        $this->icinga2api=new Icinga2API($this->api_hostname, $this->api_port);
263 263
 	    }
264 264
 	    return $this->icinga2api;
265 265
 	}
@@ -278,7 +278,7 @@  discard block
 block discarded – undo
278 278
 		if ($input_stream === false)
279 279
 		{
280 280
 		    $this->writeTrapErrorToDB("Error reading trap (code 1/Stdin)");
281
-			$this->logging->log("Error reading stdin !",ERROR,'');
281
+			$this->logging->log("Error reading stdin !", ERROR, '');
282 282
 			return null; // note : exception thrown by logging
283 283
 		}
284 284
 
@@ -287,21 +287,21 @@  discard block
 block discarded – undo
287 287
 		if ($this->receivingHost === false)
288 288
 		{
289 289
 		    $this->writeTrapErrorToDB("Error reading trap (code 1/Line Host)");
290
-			$this->logging->log("Error reading Host !",ERROR,''); 
290
+			$this->logging->log("Error reading Host !", ERROR, ''); 
291 291
 		}
292 292
 		// line 2 IP:port=>IP:port
293 293
 		$IP=chop(fgets($input_stream));
294 294
 		if ($IP === false)
295 295
 		{
296 296
 		    $this->writeTrapErrorToDB("Error reading trap (code 1/Line IP)");
297
-			$this->logging->log("Error reading IP !",ERROR,''); 
297
+			$this->logging->log("Error reading IP !", ERROR, ''); 
298 298
 		}
299 299
 		$matches=array();
300
-		$ret_code=preg_match('/.DP: \[(.*)\]:(.*)->\[(.*)\]:(.*)/',$IP,$matches);
301
-		if ($ret_code===0 || $ret_code===false) 
300
+		$ret_code=preg_match('/.DP: \[(.*)\]:(.*)->\[(.*)\]:(.*)/', $IP, $matches);
301
+		if ($ret_code === 0 || $ret_code === false) 
302 302
 		{
303 303
 		    $this->writeTrapErrorToDB("Error parsing trap (code 2/IP)");
304
-			$this->logging->log('Error parsing IP : '.$IP,ERROR,'');
304
+			$this->logging->log('Error parsing IP : '.$IP, ERROR, '');
305 305
 		} 
306 306
 		else 
307 307
 		{		
@@ -311,34 +311,34 @@  discard block
 block discarded – undo
311 311
 			$this->trap_data['destination_port']=$matches[4];
312 312
 		}
313 313
 
314
-		while (($vars=fgets($input_stream)) !==false)
314
+		while (($vars=fgets($input_stream)) !== false)
315 315
 		{
316 316
 			$vars=chop($vars);
317
-			$ret_code=preg_match('/^([^ ]+) (.*)$/',$vars,$matches);
318
-			if ($ret_code===0 || $ret_code===false) 
317
+			$ret_code=preg_match('/^([^ ]+) (.*)$/', $vars, $matches);
318
+			if ($ret_code === 0 || $ret_code === false) 
319 319
 			{
320
-				$this->logging->log('No match on trap data : '.$vars,WARN,'');
320
+				$this->logging->log('No match on trap data : '.$vars, WARN, '');
321 321
 			}
322 322
 			else 
323 323
 			{
324
-			    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'))
324
+			    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'))
325 325
 				{
326 326
 					$this->trap_data['trap_oid']=$matches[2];				
327 327
 				}
328 328
 				else
329 329
 				{
330
-					$object= new stdClass;
331
-					$object->oid =$matches[1];
332
-					$object->value = $matches[2];
333
-					array_push($this->trap_data_ext,$object);
330
+					$object=new stdClass;
331
+					$object->oid=$matches[1];
332
+					$object->value=$matches[2];
333
+					array_push($this->trap_data_ext, $object);
334 334
 				}
335 335
 			}
336 336
 		}
337 337
 
338
-		if ($this->trap_data['trap_oid']=='unknown') 
338
+		if ($this->trap_data['trap_oid'] == 'unknown') 
339 339
 		{
340
-		    $this->writeTrapErrorToDB("No trap oid found : check snmptrapd configuration (code 3/OID)",$this->trap_data['source_ip']);
341
-			$this->logging->log('no trap oid found',ERROR,'');
340
+		    $this->writeTrapErrorToDB("No trap oid found : check snmptrapd configuration (code 3/OID)", $this->trap_data['source_ip']);
341
+			$this->logging->log('no trap oid found', ERROR, '');
342 342
 		} 
343 343
 
344 344
 		// Translate oids.
@@ -360,7 +360,7 @@  discard block
 block discarded – undo
360 360
 		}
361 361
 		
362 362
 
363
-		$this->trap_data['status']= 'waiting';
363
+		$this->trap_data['status']='waiting';
364 364
 		
365 365
 		return $this->trap_data;
366 366
 	}
@@ -376,40 +376,40 @@  discard block
 block discarded – undo
376 376
 		$db_conn=$this->trapsDB->db_connect_trap();
377 377
 		
378 378
 		$sql='SELECT mib,name from '.$this->db_prefix.'mib_cache WHERE oid=\''.$oid.'\';';
379
-		$this->logging->log('SQL query : '.$sql,DEBUG );
379
+		$this->logging->log('SQL query : '.$sql, DEBUG);
380 380
 		if (($ret_code=$db_conn->query($sql)) === false) {
381
-			$this->logging->log('No result in query : ' . $sql,ERROR,'');
381
+			$this->logging->log('No result in query : '.$sql, ERROR, '');
382 382
 		}
383 383
 		$name=$ret_code->fetch();
384 384
 		if ($name['name'] != null)
385 385
 		{
386
-			return array('trap_name_mib'=>$name['mib'],'trap_name'=>$name['name']);
386
+			return array('trap_name_mib'=>$name['mib'], 'trap_name'=>$name['name']);
387 387
 		}
388 388
 		
389 389
 		// Also check if it is an instance of OID
390
-		$oid_instance=preg_replace('/\.[0-9]+$/','',$oid);
390
+		$oid_instance=preg_replace('/\.[0-9]+$/', '', $oid);
391 391
 		
392 392
 		$sql='SELECT mib,name from '.$this->db_prefix.'mib_cache WHERE oid=\''.$oid_instance.'\';';
393
-		$this->logging->log('SQL query : '.$sql,DEBUG );
393
+		$this->logging->log('SQL query : '.$sql, DEBUG);
394 394
 		if (($ret_code=$db_conn->query($sql)) === false) {
395
-			$this->logging->log('No result in query : ' . $sql,ERROR,'');
395
+			$this->logging->log('No result in query : '.$sql, ERROR, '');
396 396
 		}
397 397
 		$name=$ret_code->fetch();
398 398
 		if ($name['name'] != null)
399 399
 		{
400
-			return array('trap_name_mib'=>$name['mib'],'trap_name'=>$name['name']);
400
+			return array('trap_name_mib'=>$name['mib'], 'trap_name'=>$name['name']);
401 401
 		}
402 402
 		
403 403
 		// Try to get oid name from snmptranslate
404
-		$translate=exec($this->snmptranslate . ' -m ALL -M +'.$this->snmptranslate_dirs.
404
+		$translate=exec($this->snmptranslate.' -m ALL -M +'.$this->snmptranslate_dirs.
405 405
 		    ' '.$oid);
406 406
 		$matches=array();
407
-		$ret_code=preg_match('/(.*)::(.*)/',$translate,$matches);
408
-		if ($ret_code===0 || $ret_code === false) {
407
+		$ret_code=preg_match('/(.*)::(.*)/', $translate, $matches);
408
+		if ($ret_code === 0 || $ret_code === false) {
409 409
 			return NULL;
410 410
 		} else {
411
-			$this->logging->log('Found name with snmptrapd and not in DB for oid='.$oid,INFO);
412
-			return array('trap_name_mib'=>$matches[1],'trap_name'=>$matches[2]);
411
+			$this->logging->log('Found name with snmptrapd and not in DB for oid='.$oid, INFO);
412
+			return array('trap_name_mib'=>$matches[1], 'trap_name'=>$matches[2]);
413 413
 		}	
414 414
 	}
415 415
 	
@@ -420,90 +420,90 @@  discard block
 block discarded – undo
420 420
 	**/
421 421
 	public function eraseOldTraps($days=0)
422 422
 	{
423
-		if ($days==0)
423
+		if ($days == 0)
424 424
 		{
425 425
 			if (($days=$this->getDBConfig('db_remove_days')) == null)
426 426
 			{
427
-				$this->logging->log('No days specified & no db value : no tap erase' ,WARN,'');
427
+				$this->logging->log('No days specified & no db value : no tap erase', WARN, '');
428 428
 				return;
429 429
 			}
430 430
 		}
431 431
 		$db_conn=$this->trapsDB->db_connect_trap();
432
-		$daysago = strtotime("-".$days." day");
433
-		$sql= 'delete from '.$this->db_prefix.'received where date_received < \''.date("Y-m-d H:i:s",$daysago).'\';';
432
+		$daysago=strtotime("-".$days." day");
433
+		$sql='delete from '.$this->db_prefix.'received where date_received < \''.date("Y-m-d H:i:s", $daysago).'\';';
434 434
 		if ($db_conn->query($sql) === false) {
435
-			$this->logging->log('Error erasing traps : '.$sql,ERROR,'');
435
+			$this->logging->log('Error erasing traps : '.$sql, ERROR, '');
436 436
 		}
437
-		$this->logging->log('Erased traps older than '.$days.' day(s) : '.$sql,INFO);
437
+		$this->logging->log('Erased traps older than '.$days.' day(s) : '.$sql, INFO);
438 438
 	}
439 439
 
440 440
 	/** Write error to received trap database
441 441
 	 */
442
-	public function writeTrapErrorToDB($message,$sourceIP=null,$trapoid=null)
442
+	public function writeTrapErrorToDB($message, $sourceIP=null, $trapoid=null)
443 443
 	{
444 444
 	    
445 445
 	    $db_conn=$this->trapsDB->db_connect_trap();
446 446
 	    
447 447
 	    // add date time
448
-	    $insert_col ='date_received,status';
449
-	    $insert_val = "'" . date("Y-m-d H:i:s")."','error'";
448
+	    $insert_col='date_received,status';
449
+	    $insert_val="'".date("Y-m-d H:i:s")."','error'";
450 450
         
451
-	    if ($sourceIP !=null)
451
+	    if ($sourceIP != null)
452 452
 	    {
453
-	        $insert_col .=',source_ip';
454
-	        $insert_val .=",'". $sourceIP ."'";
453
+	        $insert_col.=',source_ip';
454
+	        $insert_val.=",'".$sourceIP."'";
455 455
 	    }
456
-	    if ($trapoid !=null)
456
+	    if ($trapoid != null)
457 457
 	    {
458
-	        $insert_col .=',trap_oid';
459
-	        $insert_val .=",'". $trapoid ."'";
458
+	        $insert_col.=',trap_oid';
459
+	        $insert_val.=",'".$trapoid."'";
460 460
 	    }
461
-	    $insert_col .=',status_detail';
462
-	    $insert_val .=",'". $message ."'";
461
+	    $insert_col.=',status_detail';
462
+	    $insert_val.=",'".$message."'";
463 463
 	    
464
-	    $sql= 'INSERT INTO '.$this->db_prefix.'received (' . $insert_col . ') VALUES ('.$insert_val.')';
464
+	    $sql='INSERT INTO '.$this->db_prefix.'received ('.$insert_col.') VALUES ('.$insert_val.')';
465 465
 	    
466 466
 	    switch ($this->trapsDB->trapDBType)
467 467
 	    {
468 468
 	        case 'pgsql':
469
-	            $sql .= ' RETURNING id;';
470
-	            $this->logging->log('sql : '.$sql,INFO);
469
+	            $sql.=' RETURNING id;';
470
+	            $this->logging->log('sql : '.$sql, INFO);
471 471
 	            if (($ret_code=$db_conn->query($sql)) === false) {
472
-	                $this->logging->log('Error SQL insert : '.$sql,1,'');
472
+	                $this->logging->log('Error SQL insert : '.$sql, 1, '');
473 473
 	            }
474
-	            $this->logging->log('SQL insertion OK',INFO );
474
+	            $this->logging->log('SQL insertion OK', INFO);
475 475
 	            // Get last id to insert oid/values in secondary table
476 476
 	            if (($inserted_id_ret=$ret_code->fetch(PDO::FETCH_ASSOC)) === false) {
477 477
 	                
478
-	                $this->logging->log('Erreur recuperation id',1,'');
478
+	                $this->logging->log('Erreur recuperation id', 1, '');
479 479
 	            }
480
-	            if (! isset($inserted_id_ret['id'])) {
481
-	                $this->logging->log('Error getting id',1,'');
480
+	            if (!isset($inserted_id_ret['id'])) {
481
+	                $this->logging->log('Error getting id', 1, '');
482 482
 	            }
483 483
 	            $this->trap_id=$inserted_id_ret['id'];
484 484
 	            break;
485 485
 	        case 'mysql':
486
-	            $sql .= ';';
487
-	            $this->logging->log('sql : '.$sql,INFO );
486
+	            $sql.=';';
487
+	            $this->logging->log('sql : '.$sql, INFO);
488 488
 	            if ($db_conn->query($sql) === false) {
489
-	                $this->logging->log('Error SQL insert : '.$sql,1,'');
489
+	                $this->logging->log('Error SQL insert : '.$sql, 1, '');
490 490
 	            }
491
-	            $this->logging->log('SQL insertion OK',INFO );
491
+	            $this->logging->log('SQL insertion OK', INFO);
492 492
 	            // Get last id to insert oid/values in secondary table
493 493
 	            $sql='SELECT LAST_INSERT_ID();';
494 494
 	            if (($ret_code=$db_conn->query($sql)) === false) {
495
-	                $this->logging->log('Erreur recuperation id',1,'');
495
+	                $this->logging->log('Erreur recuperation id', 1, '');
496 496
 	            }
497 497
 	            
498 498
 	            $inserted_id=$ret_code->fetch(PDO::FETCH_ASSOC)['LAST_INSERT_ID()'];
499
-	            if ($inserted_id==false) throw new Exception("Weird SQL error : last_insert_id returned false : open issue");
499
+	            if ($inserted_id == false) throw new Exception("Weird SQL error : last_insert_id returned false : open issue");
500 500
 	            $this->trap_id=$inserted_id;
501 501
 	            break;
502 502
 	        default:
503
-	            $this->logging->log('Error SQL type unknown  : '.$this->trapsDB->trapDBType,1,'');
503
+	            $this->logging->log('Error SQL type unknown  : '.$this->trapsDB->trapDBType, 1, '');
504 504
 	    }
505 505
 	    
506
-	    $this->logging->log('id found: '. $this->trap_id,INFO );    
506
+	    $this->logging->log('id found: '.$this->trap_id, INFO);    
507 507
 	}
508 508
 	
509 509
 	/** Write trap data to trap database
@@ -520,86 +520,86 @@  discard block
 block discarded – undo
520 520
 		$insert_col='';
521 521
 		$insert_val='';
522 522
 		// add date time
523
-		$this->trap_data['date_received'] = date("Y-m-d H:i:s");
523
+		$this->trap_data['date_received']=date("Y-m-d H:i:s");
524 524
 
525 525
 		$firstcol=1;
526 526
 		foreach ($this->trap_data as $col => $val)
527 527
 		{
528
-			if ($firstcol==0) 
528
+			if ($firstcol == 0) 
529 529
 			{
530
-				$insert_col .=',';
531
-				$insert_val .=',';
530
+				$insert_col.=',';
531
+				$insert_val.=',';
532 532
 			}
533
-			$insert_col .= $col ;
534
-			$insert_val .= ($val==null)? 'NULL' : $db_conn->quote($val);
533
+			$insert_col.=$col;
534
+			$insert_val.=($val == null) ? 'NULL' : $db_conn->quote($val);
535 535
 			$firstcol=0;
536 536
 		}
537 537
 		
538
-		$sql= 'INSERT INTO '.$this->db_prefix.'received (' . $insert_col . ') VALUES ('.$insert_val.')';
538
+		$sql='INSERT INTO '.$this->db_prefix.'received ('.$insert_col.') VALUES ('.$insert_val.')';
539 539
 		switch ($this->trapsDB->trapDBType)
540 540
 		{
541 541
 			case 'pgsql': 
542
-				$sql .= ' RETURNING id;';
543
-				$this->logging->log('sql : '.$sql,INFO );
542
+				$sql.=' RETURNING id;';
543
+				$this->logging->log('sql : '.$sql, INFO);
544 544
 				if (($ret_code=$db_conn->query($sql)) === false) {
545
-					$this->logging->log('Error SQL insert : '.$sql,ERROR,'');
545
+					$this->logging->log('Error SQL insert : '.$sql, ERROR, '');
546 546
 				}
547
-				$this->logging->log('SQL insertion OK',INFO );
547
+				$this->logging->log('SQL insertion OK', INFO);
548 548
 				// Get last id to insert oid/values in secondary table
549 549
 				if (($inserted_id_ret=$ret_code->fetch(PDO::FETCH_ASSOC)) === false) {
550 550
 														   
551
-					$this->logging->log('Erreur recuperation id',ERROR,'');
551
+					$this->logging->log('Erreur recuperation id', ERROR, '');
552 552
 				}
553
-				if (! isset($inserted_id_ret['id'])) {
554
-					$this->logging->log('Error getting id',ERROR,'');
553
+				if (!isset($inserted_id_ret['id'])) {
554
+					$this->logging->log('Error getting id', ERROR, '');
555 555
 				}
556 556
 				$this->trap_id=$inserted_id_ret['id'];
557 557
 			break;
558 558
 			case 'mysql': 
559
-				$sql .= ';';
560
-				$this->logging->log('sql : '.$sql,INFO );
559
+				$sql.=';';
560
+				$this->logging->log('sql : '.$sql, INFO);
561 561
 				if ($db_conn->query($sql) === false) {
562
-					$this->logging->log('Error SQL insert : '.$sql,ERROR,'');
562
+					$this->logging->log('Error SQL insert : '.$sql, ERROR, '');
563 563
 				}
564
-				$this->logging->log('SQL insertion OK',INFO );
564
+				$this->logging->log('SQL insertion OK', INFO);
565 565
 				// Get last id to insert oid/values in secondary table
566 566
 				$sql='SELECT LAST_INSERT_ID();';
567 567
 				if (($ret_code=$db_conn->query($sql)) === false) {
568
-					$this->logging->log('Erreur recuperation id',ERROR,'');
568
+					$this->logging->log('Erreur recuperation id', ERROR, '');
569 569
 				}
570 570
 
571 571
 				$inserted_id=$ret_code->fetch(PDO::FETCH_ASSOC)['LAST_INSERT_ID()'];
572
-				if ($inserted_id==false) throw new Exception("Weird SQL error : last_insert_id returned false : open issue");
572
+				if ($inserted_id == false) throw new Exception("Weird SQL error : last_insert_id returned false : open issue");
573 573
 				$this->trap_id=$inserted_id;
574 574
 			break;
575 575
 			default: 
576
-				$this->logging->log('Error SQL type unknown : '.$this->trapsDB->trapDBType,ERROR,'');
576
+				$this->logging->log('Error SQL type unknown : '.$this->trapsDB->trapDBType, ERROR, '');
577 577
 		}
578
-		$this->logging->log('id found: '.$this->trap_id,INFO );
578
+		$this->logging->log('id found: '.$this->trap_id, INFO);
579 579
 		
580 580
 		// Fill trap extended data table
581 581
 		foreach ($this->trap_data_ext as $value) {			
582 582
 			// TODO : detect if trap value is encoded and decode it to UTF-8 for database
583 583
 			$firstcol=1;
584
-			$value->trap_id = $this->trap_id;
584
+			$value->trap_id=$this->trap_id;
585 585
 			$insert_col='';
586 586
 			$insert_val='';
587 587
 			foreach ($value as $col => $val)
588 588
 			{
589
-				if ($firstcol==0) 
589
+				if ($firstcol == 0) 
590 590
 				{
591
-					$insert_col .=',';
592
-					$insert_val .=',';
591
+					$insert_col.=',';
592
+					$insert_val.=',';
593 593
 				}
594
-				$insert_col .= $col;
595
-				$insert_val .= ($val==null)? 'NULL' : $db_conn->quote($val);
594
+				$insert_col.=$col;
595
+				$insert_val.=($val == null) ? 'NULL' : $db_conn->quote($val);
596 596
 				$firstcol=0;
597 597
 			}
598 598
 
599
-			$sql= 'INSERT INTO '.$this->db_prefix.'received_data (' . $insert_col . ') VALUES ('.$insert_val.');';			
599
+			$sql='INSERT INTO '.$this->db_prefix.'received_data ('.$insert_col.') VALUES ('.$insert_val.');';			
600 600
 
601 601
 			if ($db_conn->query($sql) === false) {
602
-				$this->logging->log('Erreur insertion data : ' . $sql,WARN,'');
602
+				$this->logging->log('Erreur insertion data : '.$sql, WARN, '');
603 603
 			}	
604 604
 		}	
605 605
 	}
@@ -609,14 +609,14 @@  discard block
 block discarded – undo
609 609
 	*	@param $oid string oid in numeric
610 610
 	*	@return mixed : PDO object or false
611 611
 	*/	
612
-	protected function getRules($ip,$oid)
612
+	protected function getRules($ip, $oid)
613 613
 	{
614 614
 		$db_conn=$this->trapsDB->db_connect_trap();
615 615
 		// fetch rules based on IP in rule and OID
616 616
 		$sql='SELECT * from '.$this->db_prefix.'rules WHERE trap_oid=\''.$oid.'\' ';
617
-		$this->logging->log('SQL query : '.$sql,DEBUG );
617
+		$this->logging->log('SQL query : '.$sql, DEBUG);
618 618
 		if (($ret_code=$db_conn->query($sql)) === false) {
619
-			$this->logging->log('No result in query : ' . $sql,WARN,'');
619
+			$this->logging->log('No result in query : '.$sql, WARN, '');
620 620
 			return false;
621 621
 		}
622 622
 		$rules_all=$ret_code->fetchAll();
@@ -625,7 +625,7 @@  discard block
 block discarded – undo
625 625
 		$rule_ret_key=0;
626 626
 		foreach ($rules_all as $key => $rule)
627 627
 		{
628
-			if ($rule['ip4']==$ip || $rule['ip6']==$ip)
628
+			if ($rule['ip4'] == $ip || $rule['ip6'] == $ip)
629 629
 			{
630 630
 				$rules_ret[$rule_ret_key]=$rules_all[$key];
631 631
 				//TODO : get host name by API (and check if correct in rule).
@@ -633,7 +633,7 @@  discard block
 block discarded – undo
633 633
 				continue;
634 634
 			}
635 635
 			// TODO : get hosts IP by API
636
-			if (isset($rule['host_group_name']) && $rule['host_group_name']!=null)
636
+			if (isset($rule['host_group_name']) && $rule['host_group_name'] != null)
637 637
 			{ // get ips of group members by oid
638 638
 				$db_conn2=$this->trapsDB->db_connect_ido();
639 639
 				$sql="SELECT m.host_object_id, a.address as ip4, a.address6 as ip6, b.name1 as host_name
@@ -644,15 +644,15 @@  discard block
 block discarded – undo
644 644
 						LEFT JOIN icinga_objects as b ON b.object_id = a.host_object_id
645 645
 						WHERE o.name1='".$rule['host_group_name']."';";
646 646
 				if (($ret_code2=$db_conn2->query($sql)) === false) {
647
-					$this->logging->log('No result in query : ' . $sql,WARN,'');
647
+					$this->logging->log('No result in query : '.$sql, WARN, '');
648 648
 					continue;
649 649
 				}
650 650
 				$grouphosts=$ret_code2->fetchAll();
651 651
 				//echo "rule grp :\n";print_r($grouphosts);echo "\n";
652
-				foreach ( $grouphosts as $host)
652
+				foreach ($grouphosts as $host)
653 653
 				{
654 654
 					//echo $host['ip4']."\n";
655
-					if ($host['ip4']==$ip || $host['ip6']==$ip)
655
+					if ($host['ip4'] == $ip || $host['ip6'] == $ip)
656 656
 					{
657 657
 						//echo "Rule added \n";
658 658
 						$rules_ret[$rule_ret_key]=$rules_all[$key];
@@ -675,7 +675,7 @@  discard block
 block discarded – undo
675 675
 		$db_conn=$this->trapsDB->db_connect_trap();
676 676
 		$sql="UPDATE ".$this->db_prefix."rules SET num_match = '".$set."' WHERE (id = '".$id."');";
677 677
 		if ($db_conn->query($sql) === false) {
678
-			$this->logging->log('Error in update query : ' . $sql,WARN,'');
678
+			$this->logging->log('Error in update query : '.$sql, WARN, '');
679 679
 		}
680 680
 	}
681 681
 	
@@ -687,31 +687,31 @@  discard block
 block discarded – undo
687 687
 	 * @param string $display
688 688
 	 * @returnn bool true is service check was sent without error
689 689
 	*/
690
-	public function serviceCheckResult($host,$service,$state,$display)
690
+	public function serviceCheckResult($host, $service, $state, $display)
691 691
 	{
692 692
 	    if ($this->api_use === false)
693 693
 	    {
694
-    		$send = '[' . date('U') .'] PROCESS_SERVICE_CHECK_RESULT;' .
695
-    			$host.';' .$service .';' . $state . ';'.$display;
696
-    		$this->logging->log( $send." : to : " .$this->icinga2cmd,INFO );
694
+    		$send='['.date('U').'] PROCESS_SERVICE_CHECK_RESULT;'.
695
+    			$host.';'.$service.';'.$state.';'.$display;
696
+    		$this->logging->log($send." : to : ".$this->icinga2cmd, INFO);
697 697
     		
698 698
     		// TODO : file_put_contents & fopen (,'w' or 'a') does not work. See why. Or not as using API will be by default....
699
-    		exec('echo "'.$send.'" > ' .$this->icinga2cmd);
699
+    		exec('echo "'.$send.'" > '.$this->icinga2cmd);
700 700
     		return true;
701 701
 	    }
702 702
 	    else
703 703
 	    {
704
-	        $api = $this->getAPI();
704
+	        $api=$this->getAPI();
705 705
 	        $api->setCredentials($this->api_username, $this->api_password);
706
-	        list($retcode,$retmessage)=$api->serviceCheckResult($host,$service,$state,$display);
706
+	        list($retcode, $retmessage)=$api->serviceCheckResult($host, $service, $state, $display);
707 707
 	        if ($retcode == false)
708 708
 	        {
709
-	            $this->logging->log( "Error sending result : " .$retmessage,WARN,'');
709
+	            $this->logging->log("Error sending result : ".$retmessage, WARN, '');
710 710
 	            return false;
711 711
 	        }
712 712
 	        else 
713 713
 	        {
714
-	            $this->logging->log( "Sent result : " .$retmessage,INFO );
714
+	            $this->logging->log("Sent result : ".$retmessage, INFO);
715 715
 	            return true;
716 716
 	        }
717 717
 	    }
@@ -719,7 +719,7 @@  discard block
 block discarded – undo
719 719
 	
720 720
 	public function getHostByIP($ip)
721 721
 	{
722
-	    $api = $this->getAPI();
722
+	    $api=$this->getAPI();
723 723
 	    $api->setCredentials($this->api_username, $this->api_password);
724 724
 	    return $api->getHostByIP($ip);
725 725
 	}
@@ -732,32 +732,32 @@  discard block
 block discarded – undo
732 732
 	protected function applyDisplay($display)
733 733
 	{
734 734
 	    $matches=array();
735
-	    while (preg_match('/_OID\(([0-9\.]+)\)/',$display,$matches) == 1)
735
+	    while (preg_match('/_OID\(([0-9\.]+)\)/', $display, $matches) == 1)
736 736
 		{
737 737
 			$oid=$matches[1];
738 738
 			$found=0;
739
-			foreach($this->trap_data_ext as $val)
739
+			foreach ($this->trap_data_ext as $val)
740 740
 			{
741 741
 				if ($oid == $val->oid)
742 742
 				{
743
-					$val->value=preg_replace('/"/','',$val->value);
743
+					$val->value=preg_replace('/"/', '', $val->value);
744 744
 					$rep=0;
745
-					$display=preg_replace('/_OID\('.$oid.'\)/',$val->value,$display,-1,$rep);
746
-					if ($rep==0)
745
+					$display=preg_replace('/_OID\('.$oid.'\)/', $val->value, $display, -1, $rep);
746
+					if ($rep == 0)
747 747
 					{
748
-						$this->logging->log("Error in display",WARN,'');
748
+						$this->logging->log("Error in display", WARN, '');
749 749
 						return $display;
750 750
 					}
751 751
 					$found=1;
752 752
 					break;
753 753
 				}
754 754
 			}
755
-			if ($found==0)
755
+			if ($found == 0)
756 756
 			{
757
-				$display=preg_replace('/_OID\('.$oid.'\)/','<not in trap>',$display,-1,$rep);
758
-				if ($rep==0)
757
+				$display=preg_replace('/_OID\('.$oid.'\)/', '<not in trap>', $display, -1, $rep);
758
+				if ($rep == 0)
759 759
 				{
760
-					$this->logging->log("Error in display",WARN,'');
760
+					$this->logging->log("Error in display", WARN, '');
761 761
 					return $display;
762 762
 				}				
763 763
 			}
@@ -767,27 +767,27 @@  discard block
 block discarded – undo
767 767
 
768 768
 	
769 769
 	/***************** Eval & tokenizer functions ****************/
770
-	protected function eval_getElement($rule,&$item)
770
+	protected function eval_getElement($rule, &$item)
771 771
 	{
772
-		while ($rule[$item]==' ') $item++;
773
-		if (preg_match('/[0-9\.]/',$rule[$item]))
772
+		while ($rule[$item] == ' ') $item++;
773
+		if (preg_match('/[0-9\.]/', $rule[$item]))
774 774
 		{ // number
775 775
 	
776
-			$item2=$item+1; 
777
-			while (($item2!=strlen($rule)) && (preg_match('/[0-9\.]/',$rule[$item2]))) { $item2++ ;}
778
-			$val=substr($rule,$item,$item2-$item);
776
+			$item2=$item + 1; 
777
+			while (($item2 != strlen($rule)) && (preg_match('/[0-9\.]/', $rule[$item2]))) { $item2++; }
778
+			$val=substr($rule, $item, $item2 - $item);
779 779
 			$item=$item2;
780 780
 			//echo "number ".$val."\n";
781
-			return array(0,$val);
781
+			return array(0, $val);
782 782
 		}
783 783
 		if ($rule[$item] == '"')
784 784
 		{ // string
785 785
 			$item++;
786
-			$item2=$this->eval_getNext($rule,$item,'"');
787
-			$val=substr($rule,$item,$item2-$item-1);
786
+			$item2=$this->eval_getNext($rule, $item, '"');
787
+			$val=substr($rule, $item, $item2 - $item - 1);
788 788
 			$item=$item2;
789 789
 			//echo "string : ".$val."\n";
790
-			return array(1,$val);
790
+			return array(1, $val);
791 791
 		}
792 792
 		
793 793
 		if ($rule[$item] == '(')
@@ -796,14 +796,14 @@  discard block
 block discarded – undo
796 796
 			$start=$item;
797 797
 			$parenthesis_count=0; 
798 798
 			while (($item < strlen($rule)) // Not end of string AND
799
-			      && ( ($rule[$item] != ')' ) || $parenthesis_count > 0) ) // Closing ')' or embeded ()
799
+			      && (($rule[$item] != ')') || $parenthesis_count > 0)) // Closing ')' or embeded ()
800 800
 			{ 
801
-				if ($rule[$item] == '"' )
801
+				if ($rule[$item] == '"')
802 802
 				{ // pass through string
803 803
 					$item++;
804
-					$item=$this->eval_getNext($rule,$item,'"');
804
+					$item=$this->eval_getNext($rule, $item, '"');
805 805
 				} 
806
-				else{
806
+				else {
807 807
 				    if ($rule[$item] == '(')
808 808
 				    {
809 809
 				        $parenthesis_count++;
@@ -816,49 +816,49 @@  discard block
 block discarded – undo
816 816
 				}
817 817
 			}
818 818
 			
819
-			if ($item==strlen($rule)) {throw new Exception("no closing () in ".$rule ." at " .$item);}
820
-			$val=substr($rule,$start,$item-$start);
819
+			if ($item == strlen($rule)) {throw new Exception("no closing () in ".$rule." at ".$item); }
820
+			$val=substr($rule, $start, $item - $start);
821 821
 			$item++;
822 822
 			$start=0;
823 823
 			//echo "group : ".$val."\n";
824 824
 			// returns evaluation of group as type 2 (boolean)
825
-			return array(2,$this->evaluation($val,$start));		
825
+			return array(2, $this->evaluation($val, $start));		
826 826
 		}
827
-		throw new Exception("number/string not found in ".$rule ." at " .$item . ' : ' .$rule[$item]);
827
+		throw new Exception("number/string not found in ".$rule." at ".$item.' : '.$rule[$item]);
828 828
 		
829 829
 	}
830 830
 	
831
-	protected function eval_getNext($rule,$item,$tok)
831
+	protected function eval_getNext($rule, $item, $tok)
832 832
 	{
833
-		while (($rule[$item] != $tok ) && ($item < strlen($rule))) { $item++;}
834
-		if ($item==strlen($rule)) throw new Exception("closing '".$tok."' not found in ".$rule ." at " .$item);
835
-		return $item+1;
833
+		while (($rule[$item] != $tok) && ($item < strlen($rule))) { $item++; }
834
+		if ($item == strlen($rule)) throw new Exception("closing '".$tok."' not found in ".$rule." at ".$item);
835
+		return $item + 1;
836 836
 	}
837 837
 	
838
-	protected function eval_getOper($rule,&$item)
838
+	protected function eval_getOper($rule, &$item)
839 839
 	{
840
-		while ($rule[$item]==' ') $item++;
840
+		while ($rule[$item] == ' ') $item++;
841 841
 		switch ($rule[$item])
842 842
 		{
843 843
 			case '<':
844
-				if ($rule[$item+1]=='=') { $item+=2; return array(0,"<=");}
845
-				$item++; return array(0,"<");
844
+				if ($rule[$item + 1] == '=') { $item+=2; return array(0, "<="); }
845
+				$item++; return array(0, "<");
846 846
 			case '>':
847
-				if ($rule[$item+1]=='=') { $item+=2; return array(0,">=");}
848
-				$item++; return array(0,">");
847
+				if ($rule[$item + 1] == '=') { $item+=2; return array(0, ">="); }
848
+				$item++; return array(0, ">");
849 849
 			case '=':
850
-				$item++; return array(0,"=");	
850
+				$item++; return array(0, "=");	
851 851
 			case '!':
852
-				if ($rule[$item+1]=='=') { $item+=2; return array(0,"!=");}
853
-				throw new Exception("Erreur in expr - incorrect operator '!'  found in ".$rule ." at " .$item);
852
+				if ($rule[$item + 1] == '=') { $item+=2; return array(0, "!="); }
853
+				throw new Exception("Erreur in expr - incorrect operator '!'  found in ".$rule." at ".$item);
854 854
 			case '~':
855
-				$item++; return array(0,"~");	
855
+				$item++; return array(0, "~");	
856 856
 			case '|':
857
-				$item++; return array(1,"|");	
857
+				$item++; return array(1, "|");	
858 858
 			case '&':
859
-				$item++; return array(1,"&");
859
+				$item++; return array(1, "&");
860 860
 			default	:
861
-				throw new Exception("Erreur in expr - operator not found in ".$rule ." at " .$item);
861
+				throw new Exception("Erreur in expr - operator not found in ".$rule." at ".$item);
862 862
 		}
863 863
 	}
864 864
 	
@@ -870,10 +870,10 @@  discard block
 block discarded – undo
870 870
 	*   comparison int vs strings will return null (error)
871 871
 	*	return : bool or null on error
872 872
 	*/
873
-	public function evaluation($rule,&$item)
873
+	public function evaluation($rule, &$item)
874 874
 	{
875 875
 	    //echo "Evaluation of ".substr($rule,$item)."\n";
876
-		if ( $rule[$item] == '!') // If '!' found, negate next expression.
876
+		if ($rule[$item] == '!') // If '!' found, negate next expression.
877 877
 		{
878 878
 		    $negate=true;
879 879
 		    $item++;
@@ -883,63 +883,63 @@  discard block
 block discarded – undo
883 883
 		    $negate=false;
884 884
 		}
885 885
 		// First element : number, string or ()
886
-		list($type1,$val1) = $this->eval_getElement($rule,$item);
886
+		list($type1, $val1)=$this->eval_getElement($rule, $item);
887 887
 		//echo "Elmt1: ".$val1."/".$type1." : ".substr($rule,$item)."\n";
888 888
 		
889
-		if ($item==strlen($rule)) // If only element, return value, but only boolean
889
+		if ($item == strlen($rule)) // If only element, return value, but only boolean
890 890
 		{
891 891
 		  if ($type1 != 2) throw new Exception("Cannot use num/string as boolean : ".$rule);
892
-		  if ($negate === true) $val1= ! $val1;
892
+		  if ($negate === true) $val1=!$val1;
893 893
 		  return $val1;
894 894
 		}  
895 895
 		
896 896
 		// Second element : operator
897
-		list($typec,$comp) = $this->eval_getOper($rule,$item);
897
+		list($typec, $comp)=$this->eval_getOper($rule, $item);
898 898
 		//echo "Comp : ".$comp." : ".substr($rule,$item)."\n";
899 899
         
900 900
 		// Third element : number, string or ()
901
-		if ( $rule[$item] == '!') // starts with a ! so evaluate whats next
901
+		if ($rule[$item] == '!') // starts with a ! so evaluate whats next
902 902
 		{
903 903
 		    $item++;
904 904
 		    if ($typec != 1) throw new Exception("Mixing boolean and comparison : ".$rule);
905
-		    $val2= ! $this->evaluation($rule,$item);
905
+		    $val2=!$this->evaluation($rule, $item);
906 906
 		    $type2=2; // result is a boolean 
907 907
 		}
908 908
 		else 
909 909
 		{
910
-		    list($type2,$val2) = $this->eval_getElement($rule,$item);
910
+		    list($type2, $val2)=$this->eval_getElement($rule, $item);
911 911
 		}
912 912
 		//echo "Elmt2: ".$val2."/".$type2." : ".substr($rule,$item)."\n";
913 913
 		
914
-		if ($type1!=$type2)  // cannot compare different types
914
+		if ($type1 != $type2)  // cannot compare different types
915 915
 		{ 
916 916
 		    throw new Exception("Cannot compare string & number : ".$rule);
917 917
 		}
918
-		if ($typec==1 && $type1 !=2) // cannot use & or | with string/number
918
+		if ($typec == 1 && $type1 != 2) // cannot use & or | with string/number
919 919
 		{
920 920
 		    throw new Exception("Cannot use boolean operators with string & number : ".$rule);
921 921
 		}
922 922
 		
923
-		switch ($comp){
924
-			case '<':	$retVal= ($val1 < $val2); break;
925
-			case '<=':	$retVal= ($val1 <= $val2); break;
926
-			case '>':	$retVal= ($val1 > $val2); break;
927
-			case '>=':	$retVal= ($val1 >= $val2); break;
928
-			case '=':	$retVal= ($val1 == $val2); break;
929
-			case '!=':	$retVal= ($val1 != $val2); break;
930
-			case '~':	$retVal= (preg_match('/'.preg_replace('/"/','',$val2).'/',$val1)); break;
931
-			case '|':	$retVal= ($val1 || $val2); break;
932
-			case '&':	$retVal= ($val1 && $val2); break;
923
+		switch ($comp) {
924
+			case '<':	$retVal=($val1 < $val2); break;
925
+			case '<=':	$retVal=($val1 <= $val2); break;
926
+			case '>':	$retVal=($val1 > $val2); break;
927
+			case '>=':	$retVal=($val1 >= $val2); break;
928
+			case '=':	$retVal=($val1 == $val2); break;
929
+			case '!=':	$retVal=($val1 != $val2); break;
930
+			case '~':	$retVal=(preg_match('/'.preg_replace('/"/', '', $val2).'/', $val1)); break;
931
+			case '|':	$retVal=($val1 || $val2); break;
932
+			case '&':	$retVal=($val1 && $val2); break;
933 933
 			default:  throw new Exception("Error in expression - unknown comp : ".$comp);
934 934
 		}
935
-		if ($negate === true) $retVal = ! $retVal; // Inverse result if negate before expression
935
+		if ($negate === true) $retVal=!$retVal; // Inverse result if negate before expression
936 936
 		
937
-		if ($item==strlen($rule)) return $retVal; // End of string : return evaluation
937
+		if ($item == strlen($rule)) return $retVal; // End of string : return evaluation
938 938
 		// check for logical operator :
939 939
 		switch ($rule[$item])
940 940
 		{
941
-			case '|':	$item++; return ($retVal || $this->evaluation($rule,$item) );
942
-			case '&':	$item++; return ($retVal && $this->evaluation($rule,$item) );
941
+			case '|':	$item++; return ($retVal || $this->evaluation($rule, $item));
942
+			case '&':	$item++; return ($retVal && $this->evaluation($rule, $item));
943 943
 			
944 944
 			default:  throw new Exception("Erreur in expr - garbadge at end of expression : ".$rule[$item]);
945 945
 		}
@@ -951,17 +951,17 @@  discard block
 block discarded – undo
951 951
 		$rule2='';
952 952
 		while ($item < strlen($rule))
953 953
 		{
954
-			if ($rule[$item]==' ') { $item++; continue; }
955
-			if ($rule[$item]=='"')
954
+			if ($rule[$item] == ' ') { $item++; continue; }
955
+			if ($rule[$item] == '"')
956 956
 			{
957 957
 				$rule2.=$rule[$item];
958 958
 				$item++;
959
-				while (($rule[$item]!='"') && ($item < strlen($rule)))
959
+				while (($rule[$item] != '"') && ($item < strlen($rule)))
960 960
 				{
961 961
 					$rule2.=$rule[$item];
962 962
 					$item++;
963 963
 				}
964
-				if ($item == strlen ($rule)) throw new Exception("closing '\"' not found in ".$rule ." at " .$item);
964
+				if ($item == strlen($rule)) throw new Exception("closing '\"' not found in ".$rule." at ".$item);
965 965
 				$rule2.=$rule[$item];
966 966
 				$item++;
967 967
 				continue;
@@ -981,12 +981,12 @@  discard block
 block discarded – undo
981 981
 	
982 982
 	protected function eval_rule($rule)
983 983
 	{
984
-		if ($rule==null || $rule == '') // Empty rule is always true
984
+		if ($rule == null || $rule == '') // Empty rule is always true
985 985
 		{
986 986
 			return true;
987 987
 		}
988 988
 		$matches=array();
989
-		while (preg_match('/_OID\(([0-9\.\*]+)\)/',$rule,$matches) == 1)
989
+		while (preg_match('/_OID\(([0-9\.\*]+)\)/', $rule, $matches) == 1)
990 990
 		{
991 991
 			$oid=$matches[1];
992 992
 			$found=0;
@@ -998,49 +998,49 @@  discard block
 block discarded – undo
998 998
 			// replace * with \* in oid for preg_replace
999 999
 			$oid=preg_replace('/\*/', '\*', $oid);
1000 1000
 			
1001
-			$this->logging->log('OID in rule : '.$oid.' / '.$oidR,DEBUG );
1001
+			$this->logging->log('OID in rule : '.$oid.' / '.$oidR, DEBUG);
1002 1002
 			
1003
-			foreach($this->trap_data_ext as $val)
1003
+			foreach ($this->trap_data_ext as $val)
1004 1004
 			{
1005
-				if (preg_match("/^$oidR$/",$val->oid) == 1)
1005
+				if (preg_match("/^$oidR$/", $val->oid) == 1)
1006 1006
 				{
1007
-					if (!preg_match('/^[0-9]*\.?[0-9]+$/',$val->value))
1007
+					if (!preg_match('/^[0-9]*\.?[0-9]+$/', $val->value))
1008 1008
 					{ // If not a number, change " to ' and put " around it
1009
-						$val->value=preg_replace('/"/',"'",$val->value);
1009
+						$val->value=preg_replace('/"/', "'", $val->value);
1010 1010
 						$val->value='"'.$val->value.'"';
1011 1011
 					}
1012 1012
 					$rep=0;
1013
-					$rule=preg_replace('/_OID\('.$oid.'\)/',$val->value,$rule,-1,$rep);
1014
-					if ($rep==0)
1013
+					$rule=preg_replace('/_OID\('.$oid.'\)/', $val->value, $rule, -1, $rep);
1014
+					if ($rep == 0)
1015 1015
 					{
1016
-						$this->logging->log("Error in rule_eval",WARN,'');
1016
+						$this->logging->log("Error in rule_eval", WARN, '');
1017 1017
 						return false;
1018 1018
 					}
1019 1019
 					$found=1;
1020 1020
 					break;
1021 1021
 				}
1022 1022
 			}
1023
-			if ($found==0)
1023
+			if ($found == 0)
1024 1024
 			{	// OID not found : throw error
1025 1025
 			    throw new Exception('OID '.$oid.' not found in trap');
1026 1026
 			}
1027 1027
 		}
1028 1028
 		$item=0;
1029 1029
 		$rule=$this->eval_cleanup($rule);
1030
-		$this->logging->log('Rule after clenup: '.$rule,INFO );
1030
+		$this->logging->log('Rule after clenup: '.$rule, INFO);
1031 1031
 		
1032
-		return  $this->evaluation($rule,$item);
1032
+		return  $this->evaluation($rule, $item);
1033 1033
 	}
1034 1034
 	
1035 1035
 	/** Match rules for current trap and do action
1036 1036
 	*/
1037 1037
 	public function applyRules()
1038 1038
 	{
1039
-		$rules = $this->getRules($this->trap_data['source_ip'],$this->trap_data['trap_oid']);
1039
+		$rules=$this->getRules($this->trap_data['source_ip'], $this->trap_data['trap_oid']);
1040 1040
 		
1041
-		if ($rules===false || count($rules)==0)
1041
+		if ($rules === false || count($rules) == 0)
1042 1042
 		{
1043
-			$this->logging->log('No rules found for this trap',INFO );
1043
+			$this->logging->log('No rules found for this trap', INFO);
1044 1044
 			$this->trap_data['status']='unknown';
1045 1045
 			$this->trap_to_db=true;
1046 1046
 			return;
@@ -1055,58 +1055,58 @@  discard block
 block discarded – undo
1055 1055
 			$service_name=$rule['service_name'];
1056 1056
 			
1057 1057
 			$display=$this->applyDisplay($rule['display']);
1058
-			$this->trap_action = ($this->trap_action==null)? '' : $this->trap_action . ', ';
1058
+			$this->trap_action=($this->trap_action == null) ? '' : $this->trap_action.', ';
1059 1059
 			try
1060 1060
 			{
1061
-				$this->logging->log('Rule to eval : '.$rule['rule'],INFO );
1061
+				$this->logging->log('Rule to eval : '.$rule['rule'], INFO);
1062 1062
 				$evalr=$this->eval_rule($rule['rule']);
1063 1063
 				
1064 1064
 				if ($evalr == true)
1065 1065
 				{
1066 1066
 					//$this->logging->log('rules OOK: '.print_r($rule),INFO );
1067 1067
 					$action=$rule['action_match'];
1068
-					$this->logging->log('action OK : '.$action,INFO );
1068
+					$this->logging->log('action OK : '.$action, INFO);
1069 1069
 					if ($action >= 0)
1070 1070
 					{
1071
-						if ($this->serviceCheckResult($host_name,$service_name,$action,$display) == false)
1071
+						if ($this->serviceCheckResult($host_name, $service_name, $action, $display) == false)
1072 1072
 						{
1073 1073
 						    $this->trap_action.='Error sending status : check cmd/API';
1074 1074
 						}
1075 1075
 						else
1076 1076
 						{
1077
-						    $this->add_rule_match($rule['id'],$rule['num_match']+1);
1077
+						    $this->add_rule_match($rule['id'], $rule['num_match'] + 1);
1078 1078
 						    $this->trap_action.='Status '.$action.' to '.$host_name.'/'.$service_name;
1079 1079
 						}
1080 1080
 					}
1081 1081
 					else
1082 1082
 					{
1083
-						$this->add_rule_match($rule['id'],$rule['num_match']+1);
1083
+						$this->add_rule_match($rule['id'], $rule['num_match'] + 1);
1084 1084
 					}
1085
-					$this->trap_to_db=($action==-2)?false:true;
1085
+					$this->trap_to_db=($action == -2) ?false:true;
1086 1086
 				}
1087 1087
 				else
1088 1088
 				{
1089 1089
 					//$this->logging->log('rules KOO : '.print_r($rule),INFO );
1090 1090
 					
1091 1091
 					$action=$rule['action_nomatch'];
1092
-					$this->logging->log('action NOK : '.$action,INFO );
1092
+					$this->logging->log('action NOK : '.$action, INFO);
1093 1093
 					if ($action >= 0)
1094 1094
 					{
1095
-					    if ($this->serviceCheckResult($host_name,$service_name,$action,$display)==false)
1095
+					    if ($this->serviceCheckResult($host_name, $service_name, $action, $display) == false)
1096 1096
 					    {
1097 1097
 					        $this->trap_action.='Error sending status : check cmd/API';
1098 1098
 					    }
1099 1099
 					    else
1100 1100
 					    {
1101
-    						$this->add_rule_match($rule['id'],$rule['num_match']+1);
1101
+    						$this->add_rule_match($rule['id'], $rule['num_match'] + 1);
1102 1102
     						$this->trap_action.='Status '.$action.' to '.$host_name.'/'.$service_name;
1103 1103
 					    }
1104 1104
 					}
1105 1105
 					else
1106 1106
 					{
1107
-						$this->add_rule_match($rule['id'],$rule['num_match']+1);
1107
+						$this->add_rule_match($rule['id'], $rule['num_match'] + 1);
1108 1108
 					}
1109
-					$this->trap_to_db=($action==-2)?false:true;					
1109
+					$this->trap_to_db=($action == -2) ?false:true;					
1110 1110
 				}
1111 1111
 				// Put name in source_name
1112 1112
 				if (!isset($this->trap_data['source_name']))
@@ -1115,7 +1115,7 @@  discard block
 block discarded – undo
1115 1115
 				}
1116 1116
 				else
1117 1117
 				{
1118
-					if (!preg_match('/'.$rule['host_name'].'/',$this->trap_data['source_name']))
1118
+					if (!preg_match('/'.$rule['host_name'].'/', $this->trap_data['source_name']))
1119 1119
 					{ // only add if not present
1120 1120
 						$this->trap_data['source_name'].=','.$rule['host_name'];
1121 1121
 					}
@@ -1123,13 +1123,13 @@  discard block
 block discarded – undo
1123 1123
 			}
1124 1124
 			catch (Exception $e) 
1125 1125
 			{ 
1126
-			    $this->logging->log('Error in rule eval : '.$e->getMessage(),WARN,'');
1126
+			    $this->logging->log('Error in rule eval : '.$e->getMessage(), WARN, '');
1127 1127
 			    $this->trap_action.=' ERR : '.$e->getMessage();
1128 1128
 			    $this->trap_data['status']='error';
1129 1129
 			}
1130 1130
 			
1131 1131
 		}
1132
-		if ($this->trap_data['status']=='error')
1132
+		if ($this->trap_data['status'] == 'error')
1133 1133
 		{
1134 1134
 		  $this->trap_to_db=true; // Always put errors in DB for the use can see
1135 1135
 		}
@@ -1145,13 +1145,13 @@  discard block
 block discarded – undo
1145 1145
 	public function add_rule_final($time)
1146 1146
 	{
1147 1147
 		$db_conn=$this->trapsDB->db_connect_trap();
1148
-		if ($this->trap_action==null) 
1148
+		if ($this->trap_action == null) 
1149 1149
 		{
1150 1150
 			$this->trap_action='No action';
1151 1151
 		}
1152 1152
 		$sql="UPDATE ".$this->db_prefix."received SET process_time = '".$time."' , status_detail='".$this->trap_action."'  WHERE (id = '".$this->trap_id."');";
1153 1153
 		if ($db_conn->query($sql) === false) {
1154
-			$this->logging->log('Error in update query : ' . $sql,WARN,'');
1154
+			$this->logging->log('Error in update query : '.$sql, WARN, '');
1155 1155
 		}
1156 1156
 	}
1157 1157
 	
@@ -1174,7 +1174,7 @@  discard block
 block discarded – undo
1174 1174
     WHERE s.current_state != 0;";
1175 1175
 		$db_conn=$this->trapsDB->db_connect_ido();
1176 1176
 		if (($services_db=$db_conn->query($sql_query)) === false) { // set err to 1 to throw exception.
1177
-			$this->logging->log('No result in query : ' . $sql_query,ERROR,'');
1177
+			$this->logging->log('No result in query : '.$sql_query, ERROR, '');
1178 1178
 			return 0;
1179 1179
 		}
1180 1180
 		$services=$services_db->fetchAll();
@@ -1183,7 +1183,7 @@  discard block
 block discarded – undo
1183 1183
 		$sql_query="SELECT host_name, service_name, revert_ok FROM ".$this->db_prefix."rules where revert_ok != 0;";
1184 1184
 		$db_conn2=$this->trapsDB->db_connect_trap();
1185 1185
 		if (($rules_db=$db_conn2->query($sql_query)) === false) {
1186
-			$this->logging->log('No result in query : ' . $sql_query,ERROR,'');
1186
+			$this->logging->log('No result in query : '.$sql_query, ERROR, '');
1187 1187
 			return 0;
1188 1188
 		}
1189 1189
 		$rules=$rules_db->fetchAll();
@@ -1199,13 +1199,13 @@  discard block
 block discarded – undo
1199 1199
 					$service['host_name'] == $rule['host_name'] &&
1200 1200
 					($service['last_check'] + $rule['revert_ok']) < $now)
1201 1201
 				{
1202
-					$this->serviceCheckResult($service['host_name'],$service['service_name'],0,'Reset service to OK after '.$rule['revert_ok'].' seconds');
1202
+					$this->serviceCheckResult($service['host_name'], $service['service_name'], 0, 'Reset service to OK after '.$rule['revert_ok'].' seconds');
1203 1203
 					$numreset++;
1204 1204
 				}
1205 1205
 			}
1206 1206
 		}
1207 1207
 		echo "\n";
1208
-		echo $numreset . " service(s) reset to OK\n";
1208
+		echo $numreset." service(s) reset to OK\n";
1209 1209
 		return 0;
1210 1210
 		
1211 1211
 	}
Please login to merge, or discard this patch.
application/clicommands/MibCommand.php 3 patches
Indentation   +71 added lines, -71 removed lines patch added patch discarded remove patch
@@ -20,77 +20,77 @@  discard block
 block discarded – undo
20 20
 class MibCommand extends Command
21 21
 {
22 22
 	/**
23
-	*	Update mib database
24
-	*
25
-	*	USAGE 
26
-	*
27
-	*	icingli trapdirector mib update
28
-	*	
29
-	*	OPTIONS
30
-	*	
31
-	*	--pid <file> : run in background with pid in <file>
32
-	*
33
-	*	--verb    : Set output log to verbose
34
-	*
35
-	*   --force-check : force check of all traps & objects for change. (NOT IMPLEMENTED)
36
-	*/
23
+	 *	Update mib database
24
+	 *
25
+	 *	USAGE 
26
+	 *
27
+	 *	icingli trapdirector mib update
28
+	 *	
29
+	 *	OPTIONS
30
+	 *	
31
+	 *	--pid <file> : run in background with pid in <file>
32
+	 *
33
+	 *	--verb    : Set output log to verbose
34
+	 *
35
+	 *   --force-check : force check of all traps & objects for change. (NOT IMPLEMENTED)
36
+	 */
37 37
 	public function updateAction()
38 38
 	{
39
-	    $background = $this->params->get('pid', null);
40
-	    $logLevel= $this->params->has('verb') ? 4 : 2;
41
-	    if ($this->params->has('force-check')) { echo "Not implemented"; return;}
42
-	    $forceCheck=$this->params->has('force-check')?True:False;
43
-	    $pid=1;
44
-	    if ($background != null)
45
-	    {
46
-	        $file=@fopen($background,'w');
47
-	        if ($file == false)
48
-	        {
49
-	            echo 'Error : cannot open pid file '.$background;
50
-	            return 1;
51
-	        }
52
-	        $pid = pcntl_fork();
53
-	        if ($pid == -1) {
54
-	            echo 'Error : Cannot fork process';
55
-	            return 1;
56
-	        }
57
-	    }
58
-	    $module=Icinga::app()->getModuleManager()->getModule($this->getModuleName());
39
+		$background = $this->params->get('pid', null);
40
+		$logLevel= $this->params->has('verb') ? 4 : 2;
41
+		if ($this->params->has('force-check')) { echo "Not implemented"; return;}
42
+		$forceCheck=$this->params->has('force-check')?True:False;
43
+		$pid=1;
44
+		if ($background != null)
45
+		{
46
+			$file=@fopen($background,'w');
47
+			if ($file == false)
48
+			{
49
+				echo 'Error : cannot open pid file '.$background;
50
+				return 1;
51
+			}
52
+			$pid = pcntl_fork();
53
+			if ($pid == -1) {
54
+				echo 'Error : Cannot fork process';
55
+				return 1;
56
+			}
57
+		}
58
+		$module=Icinga::app()->getModuleManager()->getModule($this->getModuleName());
59 59
 		require_once($module->getBaseDir() .'/bin/trap_class.php');
60 60
 		$icingaweb2_etc=$this->Config()->get('config', 'icingaweb2_etc');
61 61
 		$trap = new Trap($icingaweb2_etc);
62 62
 		if ($pid == 1)
63 63
 		{
64
-		    $trap->setLogging($logLevel,'display');
64
+			$trap->setLogging($logLevel,'display');
65 65
 		}
66 66
 		else
67 67
 		{  // use default display TODO : if default is 'display' son process will be killed at first output....
68
-		    if ($pid != 0)
69
-		    {
70
-		        // father process
71
-		        fwrite($file,$pid);
72
-		        fclose($file);
73
-		        echo "OK : process $pid in bckground";
74
-		        return 0;
75
-		    }
76
-		    else
77
-		    {  // son process : close all file descriptors and go to a new session
78
-		        fclose($file);		        
68
+			if ($pid != 0)
69
+			{
70
+				// father process
71
+				fwrite($file,$pid);
72
+				fclose($file);
73
+				echo "OK : process $pid in bckground";
74
+				return 0;
75
+			}
76
+			else
77
+			{  // son process : close all file descriptors and go to a new session
78
+				fclose($file);		        
79 79
 // 		        $sid = posix_setsid();
80
-                fclose(STDIN);
81
-                fclose(STDOUT);
82
-                fclose(STDERR);
83
-                try
84
-                {
85
-                    $trap->mibClass->update_mib_database(false,$forceCheck);
86
-                }
87
-                catch (Exception $e)
88
-                {
89
-                    $trap->trapLog('Error in updating : ' . $e->getMessage(),2);
90
-                }
91
-                unlink($background);
92
-                return 0;
93
-		    }
80
+				fclose(STDIN);
81
+				fclose(STDOUT);
82
+				fclose(STDERR);
83
+				try
84
+				{
85
+					$trap->mibClass->update_mib_database(false,$forceCheck);
86
+				}
87
+				catch (Exception $e)
88
+				{
89
+					$trap->trapLog('Error in updating : ' . $e->getMessage(),2);
90
+				}
91
+				unlink($background);
92
+				return 0;
93
+			}
94 94
 		    
95 95
 		}
96 96
 		
@@ -108,20 +108,20 @@  discard block
 block discarded – undo
108 108
 		}
109 109
 		if ($pid != 1)
110 110
 		{
111
-		    unlink($background);
111
+			unlink($background);
112 112
 		}
113 113
 	}
114 114
 	/**
115
-	*	purge all mib database NOT IMPLEMENTED
116
-	*
117
-	*	USAGE 
118
-	*
119
-	*	icingli trapdirector mib purge --confirm yes
120
-	*	
121
-	*	OPTIONS
122
-	*	
123
-	*	--confirm yes : needed to execute purge
124
-	*/
115
+	 *	purge all mib database NOT IMPLEMENTED
116
+	 *
117
+	 *	USAGE 
118
+	 *
119
+	 *	icingli trapdirector mib purge --confirm yes
120
+	 *	
121
+	 *	OPTIONS
122
+	 *	
123
+	 *	--confirm yes : needed to execute purge
124
+	 */
125 125
 	public function purgeAction()
126 126
 	{
127 127
 		$db_prefix=$this->Config()->get('config', 'database_prefix');
Please login to merge, or discard this patch.
Spacing   +23 added lines, -23 removed lines patch added patch discarded remove patch
@@ -36,39 +36,39 @@  discard block
 block discarded – undo
36 36
 	*/
37 37
 	public function updateAction()
38 38
 	{
39
-	    $background = $this->params->get('pid', null);
40
-	    $logLevel= $this->params->has('verb') ? 4 : 2;
41
-	    if ($this->params->has('force-check')) { echo "Not implemented"; return;}
42
-	    $forceCheck=$this->params->has('force-check')?True:False;
39
+	    $background=$this->params->get('pid', null);
40
+	    $logLevel=$this->params->has('verb') ? 4 : 2;
41
+	    if ($this->params->has('force-check')) { echo "Not implemented"; return; }
42
+	    $forceCheck=$this->params->has('force-check') ?True:False;
43 43
 	    $pid=1;
44 44
 	    if ($background != null)
45 45
 	    {
46
-	        $file=@fopen($background,'w');
46
+	        $file=@fopen($background, 'w');
47 47
 	        if ($file == false)
48 48
 	        {
49 49
 	            echo 'Error : cannot open pid file '.$background;
50 50
 	            return 1;
51 51
 	        }
52
-	        $pid = pcntl_fork();
52
+	        $pid=pcntl_fork();
53 53
 	        if ($pid == -1) {
54 54
 	            echo 'Error : Cannot fork process';
55 55
 	            return 1;
56 56
 	        }
57 57
 	    }
58 58
 	    $module=Icinga::app()->getModuleManager()->getModule($this->getModuleName());
59
-		require_once($module->getBaseDir() .'/bin/trap_class.php');
59
+		require_once($module->getBaseDir().'/bin/trap_class.php');
60 60
 		$icingaweb2_etc=$this->Config()->get('config', 'icingaweb2_etc');
61
-		$trap = new Trap($icingaweb2_etc);
61
+		$trap=new Trap($icingaweb2_etc);
62 62
 		if ($pid == 1)
63 63
 		{
64
-		    $trap->setLogging($logLevel,'display');
64
+		    $trap->setLogging($logLevel, 'display');
65 65
 		}
66 66
 		else
67 67
 		{  // use default display TODO : if default is 'display' son process will be killed at first output....
68 68
 		    if ($pid != 0)
69 69
 		    {
70 70
 		        // father process
71
-		        fwrite($file,$pid);
71
+		        fwrite($file, $pid);
72 72
 		        fclose($file);
73 73
 		        echo "OK : process $pid in bckground";
74 74
 		        return 0;
@@ -82,11 +82,11 @@  discard block
 block discarded – undo
82 82
                 fclose(STDERR);
83 83
                 try
84 84
                 {
85
-                    $trap->mibClass->update_mib_database(false,$forceCheck);
85
+                    $trap->mibClass->update_mib_database(false, $forceCheck);
86 86
                 }
87 87
                 catch (Exception $e)
88 88
                 {
89
-                    $trap->trapLog('Error in updating : ' . $e->getMessage(),2);
89
+                    $trap->trapLog('Error in updating : '.$e->getMessage(), 2);
90 90
                 }
91 91
                 unlink($background);
92 92
                 return 0;
@@ -98,13 +98,13 @@  discard block
 block discarded – undo
98 98
 		{
99 99
 			echo "Update main mib database : \n";
100 100
 			echo "# (trap found) C (trap already processed) . (every 2 seconds) : \n";
101
-			$trap->mibClass->update_mib_database(true,$forceCheck);
101
+			$trap->mibClass->update_mib_database(true, $forceCheck);
102 102
 			echo "Done\n";
103 103
 			
104 104
 		}
105 105
 		catch (Exception $e)
106 106
 		{
107
-			echo 'Error in updating : ' . $e->getMessage();
107
+			echo 'Error in updating : '.$e->getMessage();
108 108
 		}
109 109
 		if ($pid != 1)
110 110
 		{
@@ -128,26 +128,26 @@  discard block
 block discarded – undo
128 128
 		echo "Not implemented";
129 129
 		// TODO : implement
130 130
 		return;
131
-		$Config = new TrapModuleConfig($db_prefix);
131
+		$Config=new TrapModuleConfig($db_prefix);
132 132
 		
133 133
 		try
134 134
 		{
135 135
 			
136 136
 			$dbresource=$this->Config()->get('config', 'database');
137 137
 			echo "DB name : $dbresource\n";
138
-			$db = IcingaDbConnection::fromResourceName($dbresource)->getConnection();
138
+			$db=IcingaDbConnection::fromResourceName($dbresource)->getConnection();
139 139
 			
140
-			$query = $db->select()->from($Config->getTrapTableName(),array('COUNT(*)'));			
141
-			echo "Number of traps : " . $db->fetchOne($query) ."\n";
142
-			$query = $db->select()->from($Config->getTrapDataTableName(),array('COUNT(*)'));			
143
-			echo "Number of trap objects : " . $db->fetchOne($query) ."\n";
144
-			$query = $db->select()->from($Config->getTrapRuleName(),array('COUNT(*)'));			
145
-			echo "Number of rules : " . $db->fetchOne($query) ."\n";		
140
+			$query=$db->select()->from($Config->getTrapTableName(), array('COUNT(*)'));			
141
+			echo "Number of traps : ".$db->fetchOne($query)."\n";
142
+			$query=$db->select()->from($Config->getTrapDataTableName(), array('COUNT(*)'));			
143
+			echo "Number of trap objects : ".$db->fetchOne($query)."\n";
144
+			$query=$db->select()->from($Config->getTrapRuleName(), array('COUNT(*)'));			
145
+			echo "Number of rules : ".$db->fetchOne($query)."\n";		
146 146
 			
147 147
 		}
148 148
 		catch (Exception $e)
149 149
 		{
150
-			echo 'Error in DB : ' . $e->getMessage();
150
+			echo 'Error in DB : '.$e->getMessage();
151 151
 		}	   
152 152
 	}  	 	
153 153
 
Please login to merge, or discard this patch.
Braces   +5 added lines, -10 removed lines patch added patch discarded remove patch
@@ -62,8 +62,7 @@  discard block
 block discarded – undo
62 62
 		if ($pid == 1)
63 63
 		{
64 64
 		    $trap->setLogging($logLevel,'display');
65
-		}
66
-		else
65
+		} else
67 66
 		{  // use default display TODO : if default is 'display' son process will be killed at first output....
68 67
 		    if ($pid != 0)
69 68
 		    {
@@ -72,8 +71,7 @@  discard block
 block discarded – undo
72 71
 		        fclose($file);
73 72
 		        echo "OK : process $pid in bckground";
74 73
 		        return 0;
75
-		    }
76
-		    else
74
+		    } else
77 75
 		    {  // son process : close all file descriptors and go to a new session
78 76
 		        fclose($file);		        
79 77
 // 		        $sid = posix_setsid();
@@ -83,8 +81,7 @@  discard block
 block discarded – undo
83 81
                 try
84 82
                 {
85 83
                     $trap->mibClass->update_mib_database(false,$forceCheck);
86
-                }
87
-                catch (Exception $e)
84
+                } catch (Exception $e)
88 85
                 {
89 86
                     $trap->trapLog('Error in updating : ' . $e->getMessage(),2);
90 87
                 }
@@ -101,8 +98,7 @@  discard block
 block discarded – undo
101 98
 			$trap->mibClass->update_mib_database(true,$forceCheck);
102 99
 			echo "Done\n";
103 100
 			
104
-		}
105
-		catch (Exception $e)
101
+		} catch (Exception $e)
106 102
 		{
107 103
 			echo 'Error in updating : ' . $e->getMessage();
108 104
 		}
@@ -144,8 +140,7 @@  discard block
 block discarded – undo
144 140
 			$query = $db->select()->from($Config->getTrapRuleName(),array('COUNT(*)'));			
145 141
 			echo "Number of rules : " . $db->fetchOne($query) ."\n";		
146 142
 			
147
-		}
148
-		catch (Exception $e)
143
+		} catch (Exception $e)
149 144
 		{
150 145
 			echo 'Error in DB : ' . $e->getMessage();
151 146
 		}	   
Please login to merge, or discard this patch.
library/Trapdirector/TrapsProcess/Mib.php 3 patches
Indentation   +509 added lines, -509 removed lines patch added patch discarded remove patch
@@ -10,581 +10,581 @@
 block discarded – undo
10 10
 class Mib
11 11
 {
12 12
     
13
-    protected $logging; //< logging class
14
-    protected $trapsDB; //< Database class
13
+	protected $logging; //< logging class
14
+	protected $trapsDB; //< Database class
15 15
     
16
-    public $snmptranslate;
17
-    public $snmptranslate_dirs;
16
+	public $snmptranslate;
17
+	public $snmptranslate_dirs;
18 18
     
19
-    private $dbOidAll; //< All oid in database;
20
-    private $dbOidIndex; //< Index of oid in dbOidAll
21
-    private $objectsAll; //< output lines of snmptranslate list
22
-    private $trapObjectsIndex; //< array of traps objects (as OID)
19
+	private $dbOidAll; //< All oid in database;
20
+	private $dbOidIndex; //< Index of oid in dbOidAll
21
+	private $objectsAll; //< output lines of snmptranslate list
22
+	private $trapObjectsIndex; //< array of traps objects (as OID)
23 23
     
24
-    private $oidDesc=array(); //< $oid,$mib,$name,$type,$textConv,$dispHint,$syntax,$type_enum,$description=NULL
24
+	private $oidDesc=array(); //< $oid,$mib,$name,$type,$textConv,$dispHint,$syntax,$type_enum,$description=NULL
25 25
 
26
-    // Timing vars for update
27
-    private $timing=array();
26
+	// Timing vars for update
27
+	private $timing=array();
28 28
     
29
-    /**
30
-     * Setup Mib Class
31
-     * @param Logging $logClass : where to log
32
-     * @param Database $dbClass : Database
33
-     */
34
-    function __construct($logClass,$dbClass,$snmptrans,$snmptransdir)
35
-    {
36
-        $this->logging=$logClass;
37
-        $this->trapsDB=$dbClass;
38
-        $this->snmptranslate=$snmptrans;
39
-        $this->snmptranslate_dirs=$snmptransdir;
29
+	/**
30
+	 * Setup Mib Class
31
+	 * @param Logging $logClass : where to log
32
+	 * @param Database $dbClass : Database
33
+	 */
34
+	function __construct($logClass,$dbClass,$snmptrans,$snmptransdir)
35
+	{
36
+		$this->logging=$logClass;
37
+		$this->trapsDB=$dbClass;
38
+		$this->snmptranslate=$snmptrans;
39
+		$this->snmptranslate_dirs=$snmptransdir;
40 40
 
41
-    }
41
+	}
42 42
     
43 43
     
44
-    /**
45
-     * Update or add an OID to database uses $this->dbOidIndex for mem cache
46
-     * and $this->oidDesc doe data
47
-     * @return number : 0=unchanged, 1 = changed, 2=created
48
-     */
49
-    public function update_oid()
50
-    {
51
-        $db_conn=$this->trapsDB->db_connect_trap();
52
-        $this->oidDesc['description']=$db_conn->quote($this->oidDesc['description']);
53
-        if (isset($this->dbOidIndex[$this->oidDesc['oid']]))
54
-        {
55
-            if ($this->dbOidIndex[$this->oidDesc['oid']]['key'] == -1)
56
-            { // newly created.
57
-                return 0;
58
-            }
59
-            $oidIndex=$this->dbOidIndex[$this->oidDesc['oid']]['key']; // Get index in dbOidAll
60
-            $dbOid=$this->dbOidAll[$oidIndex]; // Get array of element
61
-            if ( $this->oidDesc['name'] != $dbOid['name'] ||
62
-                $this->oidDesc['mib'] != $dbOid['mib'] ||
63
-                $this->oidDesc['type'] !=$dbOid['type']
64
-               )
65
-            { // Do update
66
-                $sql='UPDATE '.$this->trapsDB->dbPrefix.'mib_cache SET '.
67
-                    'name = :name , type = :type , mib = :mib , textual_convention = :tc , display_hint = :display_hint'.
68
-                    ', syntax = :syntax, type_enum = :type_enum, description = :description '.
69
-                    ' WHERE id= :id';
70
-                $sqlQuery=$db_conn->prepare($sql);
44
+	/**
45
+	 * Update or add an OID to database uses $this->dbOidIndex for mem cache
46
+	 * and $this->oidDesc doe data
47
+	 * @return number : 0=unchanged, 1 = changed, 2=created
48
+	 */
49
+	public function update_oid()
50
+	{
51
+		$db_conn=$this->trapsDB->db_connect_trap();
52
+		$this->oidDesc['description']=$db_conn->quote($this->oidDesc['description']);
53
+		if (isset($this->dbOidIndex[$this->oidDesc['oid']]))
54
+		{
55
+			if ($this->dbOidIndex[$this->oidDesc['oid']]['key'] == -1)
56
+			{ // newly created.
57
+				return 0;
58
+			}
59
+			$oidIndex=$this->dbOidIndex[$this->oidDesc['oid']]['key']; // Get index in dbOidAll
60
+			$dbOid=$this->dbOidAll[$oidIndex]; // Get array of element
61
+			if ( $this->oidDesc['name'] != $dbOid['name'] ||
62
+				$this->oidDesc['mib'] != $dbOid['mib'] ||
63
+				$this->oidDesc['type'] !=$dbOid['type']
64
+			   )
65
+			{ // Do update
66
+				$sql='UPDATE '.$this->trapsDB->dbPrefix.'mib_cache SET '.
67
+					'name = :name , type = :type , mib = :mib , textual_convention = :tc , display_hint = :display_hint'.
68
+					', syntax = :syntax, type_enum = :type_enum, description = :description '.
69
+					' WHERE id= :id';
70
+				$sqlQuery=$db_conn->prepare($sql);
71 71
                 
72
-                $sqlParam=array(
73
-                    ':name' => $this->oidDesc['name'],
74
-                    ':type' => $this->oidDesc['type'],
75
-                    ':mib' => $this->oidDesc['mib'],
76
-                    ':tc' =>  $this->oidDesc['textconv']??'null',
77
-                    ':display_hint' => $this->oidDesc['dispHint']??'null' ,
78
-                    ':syntax' => $this->oidDesc['syntax']==null??'null',
79
-                    ':type_enum' => $this->oidDesc['type_enum']??'null',
80
-                    ':description' => $this->oidDesc['description']??'null',
81
-                    ':id' => $this->dbOidAll[$this->dbOidIndex[$this->oidDesc['oid']]['id']]
82
-                );
72
+				$sqlParam=array(
73
+					':name' => $this->oidDesc['name'],
74
+					':type' => $this->oidDesc['type'],
75
+					':mib' => $this->oidDesc['mib'],
76
+					':tc' =>  $this->oidDesc['textconv']??'null',
77
+					':display_hint' => $this->oidDesc['dispHint']??'null' ,
78
+					':syntax' => $this->oidDesc['syntax']==null??'null',
79
+					':type_enum' => $this->oidDesc['type_enum']??'null',
80
+					':description' => $this->oidDesc['description']??'null',
81
+					':id' => $this->dbOidAll[$this->dbOidIndex[$this->oidDesc['oid']]['id']]
82
+				);
83 83
                 
84
-                if ($sqlQuery->execute($sqlParam) === false) {
85
-                    $this->logging->log('Error in query : ' . $sql,ERROR,'');
86
-                }
87
-                $this->logging->log('Trap updated : '.$this->oidDesc['name'] . ' / OID : '.$this->oidDesc['oid'],DEBUG );
88
-                return 1;
89
-            }
90
-            else
91
-            {
92
-                $this->logging->log('Trap unchanged : '.$this->oidDesc['name'] . ' / OID : '.$this->oidDesc['oid'],DEBUG );
93
-                return 0;
94
-            }
95
-        }
96
-        // create new OID.
84
+				if ($sqlQuery->execute($sqlParam) === false) {
85
+					$this->logging->log('Error in query : ' . $sql,ERROR,'');
86
+				}
87
+				$this->logging->log('Trap updated : '.$this->oidDesc['name'] . ' / OID : '.$this->oidDesc['oid'],DEBUG );
88
+				return 1;
89
+			}
90
+			else
91
+			{
92
+				$this->logging->log('Trap unchanged : '.$this->oidDesc['name'] . ' / OID : '.$this->oidDesc['oid'],DEBUG );
93
+				return 0;
94
+			}
95
+		}
96
+		// create new OID.
97 97
         
98
-        // Insert data
98
+		// Insert data
99 99
         
100
-        $sql='INSERT INTO '.$this->trapsDB->dbPrefix.'mib_cache '.
101
-            '(oid, name, type , mib, textual_convention, display_hint '.
102
-            ', syntax, type_enum , description ) ' .
103
-            'values (:oid, :name , :type ,:mib ,:tc , :display_hint'.
104
-            ', :syntax, :type_enum, :description )';
100
+		$sql='INSERT INTO '.$this->trapsDB->dbPrefix.'mib_cache '.
101
+			'(oid, name, type , mib, textual_convention, display_hint '.
102
+			', syntax, type_enum , description ) ' .
103
+			'values (:oid, :name , :type ,:mib ,:tc , :display_hint'.
104
+			', :syntax, :type_enum, :description )';
105 105
         
106
-        if ($this->trapsDB->trapDBType == 'pgsql') $sql .= 'RETURNING id';
106
+		if ($this->trapsDB->trapDBType == 'pgsql') $sql .= 'RETURNING id';
107 107
         
108
-        $sqlQuery=$db_conn->prepare($sql);
108
+		$sqlQuery=$db_conn->prepare($sql);
109 109
         
110
-        $sqlParam=array(
111
-            ':oid' => $this->oidDesc['oid'],
112
-            ':name' => $this->oidDesc['name'],
113
-            ':type' => $this->oidDesc['type'],
114
-            ':mib' => $this->oidDesc['mib'],
115
-            ':tc' =>  ($this->oidDesc['textconv']==null)?'null':$this->oidDesc['textconv'] ,
116
-            ':display_hint' => ($this->oidDesc['dispHint']==null)?'null':$this->oidDesc['dispHint'] ,
117
-            ':syntax' => ($this->oidDesc['syntax']==null)?'null':$this->oidDesc['syntax'],
118
-            ':type_enum' => ($this->oidDesc['type_enum']==null)?'null':$this->oidDesc['type_enum'],
119
-            ':description' => ($this->oidDesc['description']==null)?'null':$this->oidDesc['description']
120
-        );
110
+		$sqlParam=array(
111
+			':oid' => $this->oidDesc['oid'],
112
+			':name' => $this->oidDesc['name'],
113
+			':type' => $this->oidDesc['type'],
114
+			':mib' => $this->oidDesc['mib'],
115
+			':tc' =>  ($this->oidDesc['textconv']==null)?'null':$this->oidDesc['textconv'] ,
116
+			':display_hint' => ($this->oidDesc['dispHint']==null)?'null':$this->oidDesc['dispHint'] ,
117
+			':syntax' => ($this->oidDesc['syntax']==null)?'null':$this->oidDesc['syntax'],
118
+			':type_enum' => ($this->oidDesc['type_enum']==null)?'null':$this->oidDesc['type_enum'],
119
+			':description' => ($this->oidDesc['description']==null)?'null':$this->oidDesc['description']
120
+		);
121 121
         
122
-        if ($sqlQuery->execute($sqlParam) === false) {
123
-            $this->logging->log('Error in query : ' . $sql,1,'');
124
-        }
122
+		if ($sqlQuery->execute($sqlParam) === false) {
123
+			$this->logging->log('Error in query : ' . $sql,1,'');
124
+		}
125 125
         
126
-        switch ($this->trapsDB->trapDBType)
127
-        {
128
-            case 'pgsql':
129
-                // Get last id to insert oid/values in secondary table
130
-                if (($inserted_id_ret=$sqlQuery->fetch(PDO::FETCH_ASSOC)) === false) {
131
-                    $this->logging->log('Error getting id - pgsql - ',1,'');
132
-                }
133
-                if (! isset($inserted_id_ret['id'])) {
134
-                    $this->logging->log('Error getting id - pgsql - empty.',1,'');
135
-                }
136
-                $this->dbOidIndex[$this->oidDesc['oid']]['id']=$inserted_id_ret['id'];
137
-                break;
138
-            case 'mysql':
139
-                // Get last id to insert oid/values in secondary table
140
-                $sql='SELECT LAST_INSERT_ID();';
141
-                if (($ret_code=$db_conn->query($sql)) === false) {
142
-                    $this->logging->log('Erreur getting id - mysql - ',1,'');
143
-                }
126
+		switch ($this->trapsDB->trapDBType)
127
+		{
128
+			case 'pgsql':
129
+				// Get last id to insert oid/values in secondary table
130
+				if (($inserted_id_ret=$sqlQuery->fetch(PDO::FETCH_ASSOC)) === false) {
131
+					$this->logging->log('Error getting id - pgsql - ',1,'');
132
+				}
133
+				if (! isset($inserted_id_ret['id'])) {
134
+					$this->logging->log('Error getting id - pgsql - empty.',1,'');
135
+				}
136
+				$this->dbOidIndex[$this->oidDesc['oid']]['id']=$inserted_id_ret['id'];
137
+				break;
138
+			case 'mysql':
139
+				// Get last id to insert oid/values in secondary table
140
+				$sql='SELECT LAST_INSERT_ID();';
141
+				if (($ret_code=$db_conn->query($sql)) === false) {
142
+					$this->logging->log('Erreur getting id - mysql - ',1,'');
143
+				}
144 144
                 
145
-                $inserted_id=$ret_code->fetch(PDO::FETCH_ASSOC)['LAST_INSERT_ID()'];
146
-                if ($inserted_id==false) throw new Exception("Weird SQL error : last_insert_id returned false : open issue");
147
-                $this->dbOidIndex[$this->oidDesc['oid']]['id']=$inserted_id;
148
-                break;
149
-            default:
150
-                $this->logging->log('Error SQL type Unknown : '.$this->trapsDB->trapDBType,1,'');
151
-        }
145
+				$inserted_id=$ret_code->fetch(PDO::FETCH_ASSOC)['LAST_INSERT_ID()'];
146
+				if ($inserted_id==false) throw new Exception("Weird SQL error : last_insert_id returned false : open issue");
147
+				$this->dbOidIndex[$this->oidDesc['oid']]['id']=$inserted_id;
148
+				break;
149
+			default:
150
+				$this->logging->log('Error SQL type Unknown : '.$this->trapsDB->trapDBType,1,'');
151
+		}
152 152
         
153
-        // Set as newly created.
154
-        $this->dbOidIndex[$this->oidDesc['oid']]['key']=-1;
155
-        return 2;
156
-    }
153
+		// Set as newly created.
154
+		$this->dbOidIndex[$this->oidDesc['oid']]['key']=-1;
155
+		return 2;
156
+	}
157 157
     
158
-    /**
159
-     * create or update (with check_existing = true) objects of trap
160
-     * @param string $trapOID : trap oid
161
-     * @param string $trapmib : mib of trap
162
-     * @param array $objects : array of objects name (without MIB)
163
-     * @param bool $check_existing : check instead of create
164
-     */
165
-    public function trap_objects($trapOID,$trapmib,$objects,$check_existing)
166
-    {
167
-        $dbObjects=null; // cache of objects for trap in db
168
-        $db_conn=$this->trapsDB->db_connect_trap();
158
+	/**
159
+	 * create or update (with check_existing = true) objects of trap
160
+	 * @param string $trapOID : trap oid
161
+	 * @param string $trapmib : mib of trap
162
+	 * @param array $objects : array of objects name (without MIB)
163
+	 * @param bool $check_existing : check instead of create
164
+	 */
165
+	public function trap_objects($trapOID,$trapmib,$objects,$check_existing)
166
+	{
167
+		$dbObjects=null; // cache of objects for trap in db
168
+		$db_conn=$this->trapsDB->db_connect_trap();
169 169
         
170
-        // Get id of trapmib.
170
+		// Get id of trapmib.
171 171
         
172
-        $trapId = $this->dbOidIndex[$trapOID]['id'];
173
-        if ($check_existing === true)
174
-        {
175
-            // Get all objects
176
-            $sql='SELECT * FROM '.$this->trapsDB->dbPrefix.'mib_cache_trap_object where trap_id='.$trapId.';';
177
-            $this->logging->log('SQL query get all traps: '.$sql,DEBUG );
178
-            if (($ret_code=$db_conn->query($sql)) === false) {
179
-                $this->logging->log('No result in query : ' . $sql,1,'');
180
-            }
181
-            $dbObjectsRaw=$ret_code->fetchAll();
172
+		$trapId = $this->dbOidIndex[$trapOID]['id'];
173
+		if ($check_existing === true)
174
+		{
175
+			// Get all objects
176
+			$sql='SELECT * FROM '.$this->trapsDB->dbPrefix.'mib_cache_trap_object where trap_id='.$trapId.';';
177
+			$this->logging->log('SQL query get all traps: '.$sql,DEBUG );
178
+			if (($ret_code=$db_conn->query($sql)) === false) {
179
+				$this->logging->log('No result in query : ' . $sql,1,'');
180
+			}
181
+			$dbObjectsRaw=$ret_code->fetchAll();
182 182
             
183
-            foreach ($dbObjectsRaw as $val)
184
-            {
185
-                $dbObjects[$val['object_id']]=1;
186
-            }
187
-        }
188
-        foreach ($objects as $object)
189
-        {
190
-            $match=$snmptrans=array();
191
-            $retVal=0;
183
+			foreach ($dbObjectsRaw as $val)
184
+			{
185
+				$dbObjects[$val['object_id']]=1;
186
+			}
187
+		}
188
+		foreach ($objects as $object)
189
+		{
190
+			$match=$snmptrans=array();
191
+			$retVal=0;
192 192
             
193
-            $this->reset_oidDesc();
193
+			$this->reset_oidDesc();
194 194
             
195 195
             
196
-            $tmpdesc=''; // For multiline description
197
-            $indesc=false; // true if currently inside multiline description
196
+			$tmpdesc=''; // For multiline description
197
+			$indesc=false; // true if currently inside multiline description
198 198
             
199
-            $this->oidDesc['mib']=$trapmib;
200
-            exec($this->snmptranslate . ' -m ALL -M +'.$this->snmptranslate_dirs.
201
-                ' -On -Td '.$this->oidDesc['mib'].'::'.$object . ' 2>/dev/null',$snmptrans,$retVal);
202
-            if ($retVal!=0)
203
-            {
204
-                // Maybe not trap mib, search with IR
205
-                exec($this->snmptranslate . ' -m ALL -M +'.$this->snmptranslate_dirs.
206
-                    ' -IR '.$object . ' 2>/dev/null',$snmptrans,$retVal);
207
-                if ($retVal != 0 || !preg_match('/(.*)::(.*)/',$snmptrans[0],$match))
208
-                { // Not found -> continue with warning
209
-                    $this->logging->log('Error finding trap object : '.$trapmib.'::'.$object,2,'');
210
-                    continue;
211
-                }
212
-                $this->oidDesc['mib']=$match[1];
199
+			$this->oidDesc['mib']=$trapmib;
200
+			exec($this->snmptranslate . ' -m ALL -M +'.$this->snmptranslate_dirs.
201
+				' -On -Td '.$this->oidDesc['mib'].'::'.$object . ' 2>/dev/null',$snmptrans,$retVal);
202
+			if ($retVal!=0)
203
+			{
204
+				// Maybe not trap mib, search with IR
205
+				exec($this->snmptranslate . ' -m ALL -M +'.$this->snmptranslate_dirs.
206
+					' -IR '.$object . ' 2>/dev/null',$snmptrans,$retVal);
207
+				if ($retVal != 0 || !preg_match('/(.*)::(.*)/',$snmptrans[0],$match))
208
+				{ // Not found -> continue with warning
209
+					$this->logging->log('Error finding trap object : '.$trapmib.'::'.$object,2,'');
210
+					continue;
211
+				}
212
+				$this->oidDesc['mib']=$match[1];
213 213
                 
214
-                // Do the snmptranslate again.
215
-                exec($this->snmptranslate . ' -m ALL -M +'.$this->snmptranslate_dirs.
216
-                    ' -On -Td '.$this->oidDesc['mib'].'::'.$object,$snmptrans,$retVal);
217
-                if ($retVal!=0) {
218
-                    $this->logging->log('Error finding trap object : '.$this->oidDesc['mib'].'::'.$object,2,'');
219
-                }
214
+				// Do the snmptranslate again.
215
+				exec($this->snmptranslate . ' -m ALL -M +'.$this->snmptranslate_dirs.
216
+					' -On -Td '.$this->oidDesc['mib'].'::'.$object,$snmptrans,$retVal);
217
+				if ($retVal!=0) {
218
+					$this->logging->log('Error finding trap object : '.$this->oidDesc['mib'].'::'.$object,2,'');
219
+				}
220 220
                 
221
-            }
222
-            foreach ($snmptrans as $line)
223
-            {
224
-                if ($indesc===true)
225
-                {
226
-                    $line=preg_replace('/[\t ]+/',' ',$line);
227
-                    if (preg_match('/(.*)"$/', $line,$match))
228
-                    {
229
-                        $this->oidDesc['description'] = $tmpdesc . $match[1];
230
-                        $indesc=false;
231
-                    }
232
-                    $tmpdesc.=$line;
233
-                    continue;
234
-                }
235
-                if (preg_match('/^\.[0-9\.]+$/', $line))
236
-                {
237
-                    $this->oidDesc['oid']=$line;
238
-                    continue;
239
-                }
240
-                if (preg_match('/^[\t ]+SYNTAX[\t ]+([^{]*) \{(.*)\}/',$line,$match))
241
-                {
242
-                    $this->oidDesc['syntax']=$match[1];
243
-                    $this->oidDesc['type_enum']=$match[2];
244
-                    continue;
245
-                }
246
-                if (preg_match('/^[\t ]+SYNTAX[\t ]+(.*)/',$line,$match))
247
-                {
248
-                    $this->oidDesc['syntax']=$match[1];
249
-                    continue;
250
-                }
251
-                if (preg_match('/^[\t ]+DISPLAY-HINT[\t ]+"(.*)"/',$line,$match))
252
-                {
253
-                    $this->oidDesc['dispHint']=$match[1];
254
-                    continue;
255
-                }
256
-                if (preg_match('/^[\t ]+DESCRIPTION[\t ]+"(.*)"/',$line,$match))
257
-                {
258
-                    $this->oidDesc['description']=$match[1];
259
-                    continue;
260
-                }
261
-                if (preg_match('/^[\t ]+DESCRIPTION[\t ]+"(.*)/',$line,$match))
262
-                {
263
-                    $tmpdesc=$match[1];
264
-                    $indesc=true;
265
-                    continue;
266
-                }
267
-                if (preg_match('/^[\t ]+-- TEXTUAL CONVENTION[\t ]+(.*)/',$line,$match))
268
-                {
269
-                    $this->oidDesc['textconv']=$match[1];
270
-                    continue;
271
-                }
272
-            }
273
-            $this->oidDesc['name'] = $object;
274
-            $this->logging->log("Adding object ".$this->oidDesc['name']." : ".$this->oidDesc['oid']." / ".$this->oidDesc['syntax']." / ".$this->oidDesc['type_enum']." / ".$this->oidDesc['dispHint']." / ".$this->oidDesc['textconv'],DEBUG );
275
-            //echo "$this->oidDesc['name'] : $this->oidDesc['oid'] / $this->oidDesc['syntax'] / $this->oidDesc['type_enum'] / $this->oidDesc['dispHint'] / $this->oidDesc['textconv'] / $this->oidDesc['description']\n";
276
-            // Update
277
-            $this->update_oid();
221
+			}
222
+			foreach ($snmptrans as $line)
223
+			{
224
+				if ($indesc===true)
225
+				{
226
+					$line=preg_replace('/[\t ]+/',' ',$line);
227
+					if (preg_match('/(.*)"$/', $line,$match))
228
+					{
229
+						$this->oidDesc['description'] = $tmpdesc . $match[1];
230
+						$indesc=false;
231
+					}
232
+					$tmpdesc.=$line;
233
+					continue;
234
+				}
235
+				if (preg_match('/^\.[0-9\.]+$/', $line))
236
+				{
237
+					$this->oidDesc['oid']=$line;
238
+					continue;
239
+				}
240
+				if (preg_match('/^[\t ]+SYNTAX[\t ]+([^{]*) \{(.*)\}/',$line,$match))
241
+				{
242
+					$this->oidDesc['syntax']=$match[1];
243
+					$this->oidDesc['type_enum']=$match[2];
244
+					continue;
245
+				}
246
+				if (preg_match('/^[\t ]+SYNTAX[\t ]+(.*)/',$line,$match))
247
+				{
248
+					$this->oidDesc['syntax']=$match[1];
249
+					continue;
250
+				}
251
+				if (preg_match('/^[\t ]+DISPLAY-HINT[\t ]+"(.*)"/',$line,$match))
252
+				{
253
+					$this->oidDesc['dispHint']=$match[1];
254
+					continue;
255
+				}
256
+				if (preg_match('/^[\t ]+DESCRIPTION[\t ]+"(.*)"/',$line,$match))
257
+				{
258
+					$this->oidDesc['description']=$match[1];
259
+					continue;
260
+				}
261
+				if (preg_match('/^[\t ]+DESCRIPTION[\t ]+"(.*)/',$line,$match))
262
+				{
263
+					$tmpdesc=$match[1];
264
+					$indesc=true;
265
+					continue;
266
+				}
267
+				if (preg_match('/^[\t ]+-- TEXTUAL CONVENTION[\t ]+(.*)/',$line,$match))
268
+				{
269
+					$this->oidDesc['textconv']=$match[1];
270
+					continue;
271
+				}
272
+			}
273
+			$this->oidDesc['name'] = $object;
274
+			$this->logging->log("Adding object ".$this->oidDesc['name']." : ".$this->oidDesc['oid']." / ".$this->oidDesc['syntax']." / ".$this->oidDesc['type_enum']." / ".$this->oidDesc['dispHint']." / ".$this->oidDesc['textconv'],DEBUG );
275
+			//echo "$this->oidDesc['name'] : $this->oidDesc['oid'] / $this->oidDesc['syntax'] / $this->oidDesc['type_enum'] / $this->oidDesc['dispHint'] / $this->oidDesc['textconv'] / $this->oidDesc['description']\n";
276
+			// Update
277
+			$this->update_oid();
278 278
             
279
-            if (isset($dbObjects[$this->dbOidIndex[$this->oidDesc['oid']]['id']]))
280
-            {   // if link exists, continue
281
-                $dbObjects[$this->dbOidIndex[$this->oidDesc['oid']]['id']]=2;
282
-                continue;
283
-            }
284
-            if ($check_existing === true)
285
-            {
286
-                // TODO : check link trap - objects exists, mark them.
287
-            }
288
-            // Associate in object table
289
-            $sql='INSERT INTO '.$this->trapsDB->dbPrefix.'mib_cache_trap_object (trap_id,object_id) '.
290
-                'values (:trap_id, :object_id)';
291
-            $sqlQuery=$db_conn->prepare($sql);
292
-            $sqlParam=array(
293
-                ':trap_id' => $trapId,
294
-                ':object_id' => $this->dbOidIndex[$this->oidDesc['oid']]['id'],
295
-            );
279
+			if (isset($dbObjects[$this->dbOidIndex[$this->oidDesc['oid']]['id']]))
280
+			{   // if link exists, continue
281
+				$dbObjects[$this->dbOidIndex[$this->oidDesc['oid']]['id']]=2;
282
+				continue;
283
+			}
284
+			if ($check_existing === true)
285
+			{
286
+				// TODO : check link trap - objects exists, mark them.
287
+			}
288
+			// Associate in object table
289
+			$sql='INSERT INTO '.$this->trapsDB->dbPrefix.'mib_cache_trap_object (trap_id,object_id) '.
290
+				'values (:trap_id, :object_id)';
291
+			$sqlQuery=$db_conn->prepare($sql);
292
+			$sqlParam=array(
293
+				':trap_id' => $trapId,
294
+				':object_id' => $this->dbOidIndex[$this->oidDesc['oid']]['id'],
295
+			);
296 296
             
297
-            if ($sqlQuery->execute($sqlParam) === false) {
298
-                $this->logging->log('Error adding trap object : ' . $sql . ' / ' . $trapId . '/'. $this->dbOidIndex[$this->oidDesc['oid']]['id'] ,1,'');
299
-            }
300
-        }
301
-        if ($check_existing === true)
302
-        {
303
-            // TODO : remove link trap - objects that wasn't marked.
304
-        }
297
+			if ($sqlQuery->execute($sqlParam) === false) {
298
+				$this->logging->log('Error adding trap object : ' . $sql . ' / ' . $trapId . '/'. $this->dbOidIndex[$this->oidDesc['oid']]['id'] ,1,'');
299
+			}
300
+		}
301
+		if ($check_existing === true)
302
+		{
303
+			// TODO : remove link trap - objects that wasn't marked.
304
+		}
305 305
         
306
-    }
306
+	}
307 307
 
308
-    private function reset_oidDesc()
309
-    {
310
-        $this->oidDesc['oid']=null;
311
-        $this->oidDesc['name']=null;
312
-        $this->oidDesc['type']=null;
313
-        $this->oidDesc['mib']=null;
314
-        $this->oidDesc['textconv']=null;
315
-        $this->oidDesc['dispHint'] =null;
316
-        $this->oidDesc['syntax']=null;
317
-        $this->oidDesc['type_enum']=null;
318
-        $this->oidDesc['description']=null;
319
-    }
308
+	private function reset_oidDesc()
309
+	{
310
+		$this->oidDesc['oid']=null;
311
+		$this->oidDesc['name']=null;
312
+		$this->oidDesc['type']=null;
313
+		$this->oidDesc['mib']=null;
314
+		$this->oidDesc['textconv']=null;
315
+		$this->oidDesc['dispHint'] =null;
316
+		$this->oidDesc['syntax']=null;
317
+		$this->oidDesc['type_enum']=null;
318
+		$this->oidDesc['description']=null;
319
+	}
320 320
     
321
-    /**
322
-     * Fills $this->objectsAll with all mibs from snmptranslate
323
-     * @return integer : number of elements 
324
-     */
325
-    private function load_mibs_snmptranslate()
326
-    {
327
-        $retVal=0;
328
-        // Get all mib objects from all mibs
329
-        $snmpCommand=$this->snmptranslate . ' -m ALL -M +'.$this->snmptranslate_dirs.' -On -Tto 2>/dev/null';
330
-        $this->logging->log('Getting all traps : '.$snmpCommand,DEBUG );
331
-        unset($this->objectsAll);
332
-        exec($snmpCommand,$this->objectsAll,$retVal);
333
-        if ($retVal!=0)
334
-        {
335
-            $this->logging->log('error executing snmptranslate',ERROR,'');
336
-        }
337
-        // Count elements to show progress
338
-        $numElements=count($this->objectsAll);
339
-        $this->logging->log('Total snmp objects returned by snmptranslate : '.$numElements,INFO );
340
-        return $numElements;
341
-    }
321
+	/**
322
+	 * Fills $this->objectsAll with all mibs from snmptranslate
323
+	 * @return integer : number of elements 
324
+	 */
325
+	private function load_mibs_snmptranslate()
326
+	{
327
+		$retVal=0;
328
+		// Get all mib objects from all mibs
329
+		$snmpCommand=$this->snmptranslate . ' -m ALL -M +'.$this->snmptranslate_dirs.' -On -Tto 2>/dev/null';
330
+		$this->logging->log('Getting all traps : '.$snmpCommand,DEBUG );
331
+		unset($this->objectsAll);
332
+		exec($snmpCommand,$this->objectsAll,$retVal);
333
+		if ($retVal!=0)
334
+		{
335
+			$this->logging->log('error executing snmptranslate',ERROR,'');
336
+		}
337
+		// Count elements to show progress
338
+		$numElements=count($this->objectsAll);
339
+		$this->logging->log('Total snmp objects returned by snmptranslate : '.$numElements,INFO );
340
+		return $numElements;
341
+	}
342 342
 
343
-    /**
344
-     * load all mib objects db in dbOidAll (raw) and index in dbOidIndex
345
-     */
346
-    private function load_mibs_from_db()
347
-    {
348
-        // Get all mibs from databse to have a memory index
343
+	/**
344
+	 * load all mib objects db in dbOidAll (raw) and index in dbOidIndex
345
+	 */
346
+	private function load_mibs_from_db()
347
+	{
348
+		// Get all mibs from databse to have a memory index
349 349
         
350
-        $db_conn=$this->trapsDB->db_connect_trap();
350
+		$db_conn=$this->trapsDB->db_connect_trap();
351 351
         
352
-        $sql='SELECT * from '.$this->trapsDB->dbPrefix.'mib_cache;';
353
-        $this->logging->log('SQL query : '.$sql,DEBUG );
354
-        if (($ret_code=$db_conn->query($sql)) === false) {
355
-            $this->logging->log('No result in query : ' . $sql,ERROR,'');
356
-        }
357
-        $this->dbOidAll=$ret_code->fetchAll();
358
-        $this->dbOidIndex=array();
359
-        // Create the index for db;
360
-        foreach($this->dbOidAll as $key=>$val)
361
-        {
362
-            $this->dbOidIndex[$val['oid']]['key']=$key;
363
-            $this->dbOidIndex[$val['oid']]['id']=$val['id'];
364
-        }
365
-    }
352
+		$sql='SELECT * from '.$this->trapsDB->dbPrefix.'mib_cache;';
353
+		$this->logging->log('SQL query : '.$sql,DEBUG );
354
+		if (($ret_code=$db_conn->query($sql)) === false) {
355
+			$this->logging->log('No result in query : ' . $sql,ERROR,'');
356
+		}
357
+		$this->dbOidAll=$ret_code->fetchAll();
358
+		$this->dbOidIndex=array();
359
+		// Create the index for db;
360
+		foreach($this->dbOidAll as $key=>$val)
361
+		{
362
+			$this->dbOidIndex[$val['oid']]['key']=$key;
363
+			$this->dbOidIndex[$val['oid']]['id']=$val['id'];
364
+		}
365
+	}
366 366
 
367
-    /**
368
-     * Reset all update timers & count to zero
369
-     */
370
-    private function reset_update_timers()
371
-    {
372
-        $this->timing['base_parse_time']=0;
373
-        $this->timing['base_check_time']=0;
374
-        $this->timing['type0_check_time']=0;
375
-        $this->timing['nottrap_time']=0;
376
-        $this->timing['update_time']=0;
377
-        $this->timing['objects_time']=0;
378
-        $this->timing['base_parse_num']=0;
379
-        $this->timing['base_check_num']=0;
380
-        $this->timing['type0_check_num']=0;
381
-        $this->timing['nottrap_num']=0;
382
-        $this->timing['update_num']=0;
383
-        $this->timing['objects_num']=0;
384
-        $this->timing['num_traps']=0;
385
-    }
367
+	/**
368
+	 * Reset all update timers & count to zero
369
+	 */
370
+	private function reset_update_timers()
371
+	{
372
+		$this->timing['base_parse_time']=0;
373
+		$this->timing['base_check_time']=0;
374
+		$this->timing['type0_check_time']=0;
375
+		$this->timing['nottrap_time']=0;
376
+		$this->timing['update_time']=0;
377
+		$this->timing['objects_time']=0;
378
+		$this->timing['base_parse_num']=0;
379
+		$this->timing['base_check_num']=0;
380
+		$this->timing['type0_check_num']=0;
381
+		$this->timing['nottrap_num']=0;
382
+		$this->timing['update_num']=0;
383
+		$this->timing['objects_num']=0;
384
+		$this->timing['num_traps']=0;
385
+	}
386 386
 
387
-    private function detect_trap($curElement,$onlyTraps)
388
-    {
389
-        // Get oid or pass if not found
390
-        if (!preg_match('/^\.[0-9\.]+$/',$this->objectsAll[$curElement]))
391
-        {
392
-            $this->timing['base_parse_time'] += microtime(true) - $this->timing['base_time'];
393
-            $this->timing['base_parse_num'] ++;
394
-            return true;
395
-        }
396
-        $this->oidDesc['oid']=$this->objectsAll[$curElement];
387
+	private function detect_trap($curElement,$onlyTraps)
388
+	{
389
+		// Get oid or pass if not found
390
+		if (!preg_match('/^\.[0-9\.]+$/',$this->objectsAll[$curElement]))
391
+		{
392
+			$this->timing['base_parse_time'] += microtime(true) - $this->timing['base_time'];
393
+			$this->timing['base_parse_num'] ++;
394
+			return true;
395
+		}
396
+		$this->oidDesc['oid']=$this->objectsAll[$curElement];
397 397
         
398
-        // get next line
399
-        $curElement++;
400
-        $match=$snmptrans=array();
401
-        if (!preg_match('/ +([^\(]+)\(.+\) type=([0-9]+)( tc=([0-9]+))?( hint=(.+))?/',
402
-            $this->objectsAll[$curElement],$match))
403
-        {
404
-            $this->timing['base_check_time'] += microtime(true) - $this->timing['base_time'];
405
-            $this->timing['base_check_num']++;
406
-            return true;
407
-        }
398
+		// get next line
399
+		$curElement++;
400
+		$match=$snmptrans=array();
401
+		if (!preg_match('/ +([^\(]+)\(.+\) type=([0-9]+)( tc=([0-9]+))?( hint=(.+))?/',
402
+			$this->objectsAll[$curElement],$match))
403
+		{
404
+			$this->timing['base_check_time'] += microtime(true) - $this->timing['base_time'];
405
+			$this->timing['base_check_num']++;
406
+			return true;
407
+		}
408 408
         
409
-        $this->oidDesc['name']=$match[1]; // Name
410
-        $this->oidDesc['type']=$match[2]; // type (21=trap, 0: may be trap, else : not trap
409
+		$this->oidDesc['name']=$match[1]; // Name
410
+		$this->oidDesc['type']=$match[2]; // type (21=trap, 0: may be trap, else : not trap
411 411
         
412
-        if ($this->oidDesc['type']==0) // object type=0 : check if v1 trap
413
-        {
414
-            // Check if next is suboid -> in that case is cannot be a trap
415
-            if (preg_match("/^".$this->oidDesc['oid']."/",$this->objectsAll[$curElement+1]))
416
-            {
417
-                $this->timing['type0_check_time'] += microtime(true) - $this->timing['base_time'];
418
-                $this->timing['type0_check_num']++;
419
-                return true;
420
-            }
421
-            unset($snmptrans);
422
-            $retVal=0;
423
-            exec($this->snmptranslate . ' -m ALL -M +'.$this->snmptranslate_dirs.
424
-                ' -Td '.$this->oidDesc['oid'] . ' | grep OBJECTS ',$snmptrans,$retVal);
425
-            if ($retVal!=0)
426
-            {
427
-                $this->timing['type0_check_time'] += microtime(true) - $this->timing['base_time'];
428
-                $this->timing['type0_check_num']++;
429
-                return true;
430
-            }
431
-            //echo "\n v1 trap found : $this->oidDesc['oid'] \n";
432
-            // Force as trap.
433
-            $this->oidDesc['type']=21;
434
-        }
435
-        if ($onlyTraps===true && $this->oidDesc['type']!=21) // if only traps and not a trap, continue
436
-        {
437
-            $this->timing['nottrap_time'] += microtime(true) - $this->timing['base_time'];
438
-            $this->timing['nottrap_num']++;
439
-            return true;
440
-        }
441
-        return false;
442
-    }
412
+		if ($this->oidDesc['type']==0) // object type=0 : check if v1 trap
413
+		{
414
+			// Check if next is suboid -> in that case is cannot be a trap
415
+			if (preg_match("/^".$this->oidDesc['oid']."/",$this->objectsAll[$curElement+1]))
416
+			{
417
+				$this->timing['type0_check_time'] += microtime(true) - $this->timing['base_time'];
418
+				$this->timing['type0_check_num']++;
419
+				return true;
420
+			}
421
+			unset($snmptrans);
422
+			$retVal=0;
423
+			exec($this->snmptranslate . ' -m ALL -M +'.$this->snmptranslate_dirs.
424
+				' -Td '.$this->oidDesc['oid'] . ' | grep OBJECTS ',$snmptrans,$retVal);
425
+			if ($retVal!=0)
426
+			{
427
+				$this->timing['type0_check_time'] += microtime(true) - $this->timing['base_time'];
428
+				$this->timing['type0_check_num']++;
429
+				return true;
430
+			}
431
+			//echo "\n v1 trap found : $this->oidDesc['oid'] \n";
432
+			// Force as trap.
433
+			$this->oidDesc['type']=21;
434
+		}
435
+		if ($onlyTraps===true && $this->oidDesc['type']!=21) // if only traps and not a trap, continue
436
+		{
437
+			$this->timing['nottrap_time'] += microtime(true) - $this->timing['base_time'];
438
+			$this->timing['nottrap_num']++;
439
+			return true;
440
+		}
441
+		return false;
442
+	}
443 443
     
444
-    /**
445
-     * Cache mib in database
446
-     * @param boolean $display_progress : Display progress on standard output
447
-     * @param boolean $check_change : Force check of trap params & objects
448
-     * @param boolean $onlyTraps : only cache traps and objects (true) or all (false)
449
-     * @param string $startOID : only cache under startOID (NOT IMPLEMENTED)
450
-     */
451
-    public function update_mib_database($display_progress=false,$check_change=false,$onlyTraps=true,$startOID='.1')
452
-    {
453
-        // Global Timing
454
-        $timeTaken = microtime(true);
444
+	/**
445
+	 * Cache mib in database
446
+	 * @param boolean $display_progress : Display progress on standard output
447
+	 * @param boolean $check_change : Force check of trap params & objects
448
+	 * @param boolean $onlyTraps : only cache traps and objects (true) or all (false)
449
+	 * @param string $startOID : only cache under startOID (NOT IMPLEMENTED)
450
+	 */
451
+	public function update_mib_database($display_progress=false,$check_change=false,$onlyTraps=true,$startOID='.1')
452
+	{
453
+		// Global Timing
454
+		$timeTaken = microtime(true);
455 455
         
456
-        $numElements=$this->load_mibs_snmptranslate(); // Load objectsAll
456
+		$numElements=$this->load_mibs_snmptranslate(); // Load objectsAll
457 457
         
458
-        $this->load_mibs_from_db(); // Load from db dbOidAll & dbOidIndex
458
+		$this->load_mibs_from_db(); // Load from db dbOidAll & dbOidIndex
459 459
         
460
-        $step=$basestep=$numElements/10; // output display of % done
461
-        $num_step=0;
462
-        $timeFiveSec = microtime(true); // Used for display a '.' every <n> seconds
460
+		$step=$basestep=$numElements/10; // output display of % done
461
+		$num_step=0;
462
+		$timeFiveSec = microtime(true); // Used for display a '.' every <n> seconds
463 463
         
464
-        // Create index for trap objects
465
-        $this->trapObjectsIndex=array();
464
+		// Create index for trap objects
465
+		$this->trapObjectsIndex=array();
466 466
         
467
-        // detailed timing (time_* vars)
468
-        $this->reset_update_timers();
467
+		// detailed timing (time_* vars)
468
+		$this->reset_update_timers();
469 469
         
470
-        for ($curElement=0;$curElement < $numElements;$curElement++)
471
-        {
472
-            $this->timing['base_time']= microtime(true);
473
-            if ($display_progress)
474
-            {
475
-                if ((microtime(true)-$timeFiveSec) > 2)
476
-                { // echo a . every 2 sec
477
-                    echo '.';
478
-                    $timeFiveSec = microtime(true);
479
-                }
480
-                if ($curElement>$step)
481
-                { // display progress
482
-                    $num_step++;
483
-                    $step+=$basestep;   
484
-                    echo "\n" . ($num_step*10). '% : ';
485
-                }
486
-            }
470
+		for ($curElement=0;$curElement < $numElements;$curElement++)
471
+		{
472
+			$this->timing['base_time']= microtime(true);
473
+			if ($display_progress)
474
+			{
475
+				if ((microtime(true)-$timeFiveSec) > 2)
476
+				{ // echo a . every 2 sec
477
+					echo '.';
478
+					$timeFiveSec = microtime(true);
479
+				}
480
+				if ($curElement>$step)
481
+				{ // display progress
482
+					$num_step++;
483
+					$step+=$basestep;   
484
+					echo "\n" . ($num_step*10). '% : ';
485
+				}
486
+			}
487 487
             
488
-            $this->reset_oidDesc();
489
-            if ($this->detect_trap($curElement,$onlyTraps)===true)
490
-            {
491
-                continue;
492
-            }
488
+			$this->reset_oidDesc();
489
+			if ($this->detect_trap($curElement,$onlyTraps)===true)
490
+			{
491
+				continue;
492
+			}
493 493
             
494
-            $this->timing['num_traps']++;
494
+			$this->timing['num_traps']++;
495 495
             
496
-            $this->logging->log('Found trap : '.$this->oidDesc['name'] . ' / OID : '.$this->oidDesc['oid'],INFO );
497
-            if ($display_progress) echo '#'; // echo a # when trap found
496
+			$this->logging->log('Found trap : '.$this->oidDesc['name'] . ' / OID : '.$this->oidDesc['oid'],INFO );
497
+			if ($display_progress) echo '#'; // echo a # when trap found
498 498
             
499
-            //################################
500
-            // get trap objects & source MIB
501
-            $retVal=0;
502
-            $match=$snmptrans=array();
503
-            exec($this->snmptranslate . ' -m ALL -M +'.$this->snmptranslate_dirs.
504
-                ' -Td '.$this->oidDesc['oid'],$snmptrans,$retVal);
505
-            if ($retVal!=0)
506
-            {
507
-                $this->logging->log('error executing snmptranslate',ERROR);
508
-            }
499
+			//################################
500
+			// get trap objects & source MIB
501
+			$retVal=0;
502
+			$match=$snmptrans=array();
503
+			exec($this->snmptranslate . ' -m ALL -M +'.$this->snmptranslate_dirs.
504
+				' -Td '.$this->oidDesc['oid'],$snmptrans,$retVal);
505
+			if ($retVal!=0)
506
+			{
507
+				$this->logging->log('error executing snmptranslate',ERROR);
508
+			}
509 509
             
510
-            if (!preg_match('/^(.*)::/',$snmptrans[0],$match))
511
-            {
512
-                $this->logging->log('Error getting mib from trap '.$this->oidDesc['oid'].' : ' . $snmptrans[0],ERROR);
513
-            }
514
-            $this->oidDesc['mib']=$match[1];
510
+			if (!preg_match('/^(.*)::/',$snmptrans[0],$match))
511
+			{
512
+				$this->logging->log('Error getting mib from trap '.$this->oidDesc['oid'].' : ' . $snmptrans[0],ERROR);
513
+			}
514
+			$this->oidDesc['mib']=$match[1];
515 515
             
516
-            $numLine=1;
517
-            while (isset($snmptrans[$numLine]) && !preg_match('/^[\t ]+DESCRIPTION[\t ]+"(.*)/',$snmptrans[$numLine],$match)) $numLine++;
518
-            if (isset($snmptrans[$numLine]))
519
-            {
520
-                $snmptrans[$numLine] = preg_replace('/^[\t ]+DESCRIPTION[\t ]+"/','',$snmptrans[$numLine]);
516
+			$numLine=1;
517
+			while (isset($snmptrans[$numLine]) && !preg_match('/^[\t ]+DESCRIPTION[\t ]+"(.*)/',$snmptrans[$numLine],$match)) $numLine++;
518
+			if (isset($snmptrans[$numLine]))
519
+			{
520
+				$snmptrans[$numLine] = preg_replace('/^[\t ]+DESCRIPTION[\t ]+"/','',$snmptrans[$numLine]);
521 521
                 
522
-                while (isset($snmptrans[$numLine]) && !preg_match('/"/',$snmptrans[$numLine]))
523
-                {
524
-                    $this->oidDesc['description'].=preg_replace('/[\t ]+/',' ',$snmptrans[$numLine]);
525
-                    $numLine++;
526
-                }
527
-                if (isset($snmptrans[$numLine])) {
528
-                    $this->oidDesc['description'].=preg_replace('/".*/','',$snmptrans[$numLine]);
529
-                    $this->oidDesc['description']=preg_replace('/[\t ]+/',' ',$this->oidDesc['description']);
530
-                }
522
+				while (isset($snmptrans[$numLine]) && !preg_match('/"/',$snmptrans[$numLine]))
523
+				{
524
+					$this->oidDesc['description'].=preg_replace('/[\t ]+/',' ',$snmptrans[$numLine]);
525
+					$numLine++;
526
+				}
527
+				if (isset($snmptrans[$numLine])) {
528
+					$this->oidDesc['description'].=preg_replace('/".*/','',$snmptrans[$numLine]);
529
+					$this->oidDesc['description']=preg_replace('/[\t ]+/',' ',$this->oidDesc['description']);
530
+				}
531 531
                 
532
-            }
532
+			}
533 533
             
534
-            $update=$this->update_oid(); // Do update of trap.
534
+			$update=$this->update_oid(); // Do update of trap.
535 535
             
536
-            $this->timing['update_time'] += microtime(true) - $this->timing['base_time'];
537
-            $this->timing['update_num']++;
536
+			$this->timing['update_time'] += microtime(true) - $this->timing['base_time'];
537
+			$this->timing['update_num']++;
538 538
             
539
-            $this->timing['base_time']= microtime(true); // Reset to check object time
539
+			$this->timing['base_time']= microtime(true); // Reset to check object time
540 540
             
541
-            if (($update==0) && ($check_change===false))
542
-            { // Trapd didn't change & force check disabled
543
-                $this->timing['objects_time'] += microtime(true) - $this->timing['base_time'];
544
-                if ($display_progress) echo "C";
545
-                continue;
546
-            }
541
+			if (($update==0) && ($check_change===false))
542
+			{ // Trapd didn't change & force check disabled
543
+				$this->timing['objects_time'] += microtime(true) - $this->timing['base_time'];
544
+				if ($display_progress) echo "C";
545
+				continue;
546
+			}
547 547
             
548
-            $synt=null;
549
-            foreach ($snmptrans as $line)
550
-            {
551
-                if (preg_match('/OBJECTS.*\{([^\}]+)\}/',$line,$match))
552
-                {
553
-                    $synt=$match[1];
554
-                }
555
-            }
556
-            if ($synt == null)
557
-            {
558
-                //echo "No objects for $trapOID\n";
559
-                $this->timing['objects_time'] += microtime(true) - $this->timing['base_time'];
560
-                continue;
561
-            }
562
-            //echo "$synt \n";
563
-            $trapObjects=array();
564
-            while (preg_match('/ *([^ ,]+) *,* */',$synt,$match))
565
-            {
566
-                array_push($trapObjects,$match[1]);
567
-                $synt=preg_replace('/'.$match[0].'/','',$synt);
568
-            }
548
+			$synt=null;
549
+			foreach ($snmptrans as $line)
550
+			{
551
+				if (preg_match('/OBJECTS.*\{([^\}]+)\}/',$line,$match))
552
+				{
553
+					$synt=$match[1];
554
+				}
555
+			}
556
+			if ($synt == null)
557
+			{
558
+				//echo "No objects for $trapOID\n";
559
+				$this->timing['objects_time'] += microtime(true) - $this->timing['base_time'];
560
+				continue;
561
+			}
562
+			//echo "$synt \n";
563
+			$trapObjects=array();
564
+			while (preg_match('/ *([^ ,]+) *,* */',$synt,$match))
565
+			{
566
+				array_push($trapObjects,$match[1]);
567
+				$synt=preg_replace('/'.$match[0].'/','',$synt);
568
+			}
569 569
             
570
-            $this->trap_objects($this->oidDesc['oid'], $this->oidDesc['mib'], $trapObjects, false);
570
+			$this->trap_objects($this->oidDesc['oid'], $this->oidDesc['mib'], $trapObjects, false);
571 571
             
572
-            $this->timing['objects_time'] += microtime(true) - $this->timing['base_time'];
573
-            $this->timing['objects_num']++;
574
-        }
572
+			$this->timing['objects_time'] += microtime(true) - $this->timing['base_time'];
573
+			$this->timing['objects_num']++;
574
+		}
575 575
         
576
-        if ($display_progress)
577
-        {
578
-            echo "\nNumber of processed traps :  ". $this->timing['num_traps'] ."\n";
579
-            echo "\nParsing : " . number_format($this->timing['base_parse_time']+$this->timing['base_check_time'],1) ." sec / " . ($this->timing['base_parse_num']+ $this->timing['base_check_num'])  . " occurences\n";
580
-            echo "Detecting traps : " . number_format($this->timing['type0_check_time']+$this->timing['nottrap_time'],1) . " sec / " . ($this->timing['type0_check_num']+$this->timing['nottrap_num']) ." occurences\n";
581
-            echo "Trap processing (".$this->timing['update_num']."): ".number_format($this->timing['update_time'],1)." sec , ";
582
-            echo "Objects processing (".$this->timing['objects_num'].") : ".number_format($this->timing['objects_time'],1)." sec \n";
576
+		if ($display_progress)
577
+		{
578
+			echo "\nNumber of processed traps :  ". $this->timing['num_traps'] ."\n";
579
+			echo "\nParsing : " . number_format($this->timing['base_parse_time']+$this->timing['base_check_time'],1) ." sec / " . ($this->timing['base_parse_num']+ $this->timing['base_check_num'])  . " occurences\n";
580
+			echo "Detecting traps : " . number_format($this->timing['type0_check_time']+$this->timing['nottrap_time'],1) . " sec / " . ($this->timing['type0_check_num']+$this->timing['nottrap_num']) ." occurences\n";
581
+			echo "Trap processing (".$this->timing['update_num']."): ".number_format($this->timing['update_time'],1)." sec , ";
582
+			echo "Objects processing (".$this->timing['objects_num'].") : ".number_format($this->timing['objects_time'],1)." sec \n";
583 583
             
584
-            $timeTaken=microtime(true) - $timeTaken;
585
-            echo "Global time : ".round($timeTaken)." seconds\n";
586
-        }
587
-    }
584
+			$timeTaken=microtime(true) - $timeTaken;
585
+			echo "Global time : ".round($timeTaken)." seconds\n";
586
+		}
587
+	}
588 588
     
589 589
     
590 590
 }
591 591
\ No newline at end of file
Please login to merge, or discard this patch.
Spacing   +114 added lines, -114 removed lines patch added patch discarded remove patch
@@ -31,7 +31,7 @@  discard block
 block discarded – undo
31 31
      * @param Logging $logClass : where to log
32 32
      * @param Database $dbClass : Database
33 33
      */
34
-    function __construct($logClass,$dbClass,$snmptrans,$snmptransdir)
34
+    function __construct($logClass, $dbClass, $snmptrans, $snmptransdir)
35 35
     {
36 36
         $this->logging=$logClass;
37 37
         $this->trapsDB=$dbClass;
@@ -58,9 +58,9 @@  discard block
 block discarded – undo
58 58
             }
59 59
             $oidIndex=$this->dbOidIndex[$this->oidDesc['oid']]['key']; // Get index in dbOidAll
60 60
             $dbOid=$this->dbOidAll[$oidIndex]; // Get array of element
61
-            if ( $this->oidDesc['name'] != $dbOid['name'] ||
61
+            if ($this->oidDesc['name'] != $dbOid['name'] ||
62 62
                 $this->oidDesc['mib'] != $dbOid['mib'] ||
63
-                $this->oidDesc['type'] !=$dbOid['type']
63
+                $this->oidDesc['type'] != $dbOid['type']
64 64
                )
65 65
             { // Do update
66 66
                 $sql='UPDATE '.$this->trapsDB->dbPrefix.'mib_cache SET '.
@@ -74,22 +74,22 @@  discard block
 block discarded – undo
74 74
                     ':type' => $this->oidDesc['type'],
75 75
                     ':mib' => $this->oidDesc['mib'],
76 76
                     ':tc' =>  $this->oidDesc['textconv']??'null',
77
-                    ':display_hint' => $this->oidDesc['dispHint']??'null' ,
78
-                    ':syntax' => $this->oidDesc['syntax']==null??'null',
77
+                    ':display_hint' => $this->oidDesc['dispHint']??'null',
78
+                    ':syntax' => $this->oidDesc['syntax'] == null??'null',
79 79
                     ':type_enum' => $this->oidDesc['type_enum']??'null',
80 80
                     ':description' => $this->oidDesc['description']??'null',
81 81
                     ':id' => $this->dbOidAll[$this->dbOidIndex[$this->oidDesc['oid']]['id']]
82 82
                 );
83 83
                 
84 84
                 if ($sqlQuery->execute($sqlParam) === false) {
85
-                    $this->logging->log('Error in query : ' . $sql,ERROR,'');
85
+                    $this->logging->log('Error in query : '.$sql, ERROR, '');
86 86
                 }
87
-                $this->logging->log('Trap updated : '.$this->oidDesc['name'] . ' / OID : '.$this->oidDesc['oid'],DEBUG );
87
+                $this->logging->log('Trap updated : '.$this->oidDesc['name'].' / OID : '.$this->oidDesc['oid'], DEBUG);
88 88
                 return 1;
89 89
             }
90 90
             else
91 91
             {
92
-                $this->logging->log('Trap unchanged : '.$this->oidDesc['name'] . ' / OID : '.$this->oidDesc['oid'],DEBUG );
92
+                $this->logging->log('Trap unchanged : '.$this->oidDesc['name'].' / OID : '.$this->oidDesc['oid'], DEBUG);
93 93
                 return 0;
94 94
             }
95 95
         }
@@ -99,11 +99,11 @@  discard block
 block discarded – undo
99 99
         
100 100
         $sql='INSERT INTO '.$this->trapsDB->dbPrefix.'mib_cache '.
101 101
             '(oid, name, type , mib, textual_convention, display_hint '.
102
-            ', syntax, type_enum , description ) ' .
102
+            ', syntax, type_enum , description ) '.
103 103
             'values (:oid, :name , :type ,:mib ,:tc , :display_hint'.
104 104
             ', :syntax, :type_enum, :description )';
105 105
         
106
-        if ($this->trapsDB->trapDBType == 'pgsql') $sql .= 'RETURNING id';
106
+        if ($this->trapsDB->trapDBType == 'pgsql') $sql.='RETURNING id';
107 107
         
108 108
         $sqlQuery=$db_conn->prepare($sql);
109 109
         
@@ -112,15 +112,15 @@  discard block
 block discarded – undo
112 112
             ':name' => $this->oidDesc['name'],
113 113
             ':type' => $this->oidDesc['type'],
114 114
             ':mib' => $this->oidDesc['mib'],
115
-            ':tc' =>  ($this->oidDesc['textconv']==null)?'null':$this->oidDesc['textconv'] ,
116
-            ':display_hint' => ($this->oidDesc['dispHint']==null)?'null':$this->oidDesc['dispHint'] ,
117
-            ':syntax' => ($this->oidDesc['syntax']==null)?'null':$this->oidDesc['syntax'],
118
-            ':type_enum' => ($this->oidDesc['type_enum']==null)?'null':$this->oidDesc['type_enum'],
119
-            ':description' => ($this->oidDesc['description']==null)?'null':$this->oidDesc['description']
115
+            ':tc' =>  ($this->oidDesc['textconv'] == null) ? 'null' : $this->oidDesc['textconv'],
116
+            ':display_hint' => ($this->oidDesc['dispHint'] == null) ? 'null' : $this->oidDesc['dispHint'],
117
+            ':syntax' => ($this->oidDesc['syntax'] == null) ? 'null' : $this->oidDesc['syntax'],
118
+            ':type_enum' => ($this->oidDesc['type_enum'] == null) ? 'null' : $this->oidDesc['type_enum'],
119
+            ':description' => ($this->oidDesc['description'] == null) ? 'null' : $this->oidDesc['description']
120 120
         );
121 121
         
122 122
         if ($sqlQuery->execute($sqlParam) === false) {
123
-            $this->logging->log('Error in query : ' . $sql,1,'');
123
+            $this->logging->log('Error in query : '.$sql, 1, '');
124 124
         }
125 125
         
126 126
         switch ($this->trapsDB->trapDBType)
@@ -128,10 +128,10 @@  discard block
 block discarded – undo
128 128
             case 'pgsql':
129 129
                 // Get last id to insert oid/values in secondary table
130 130
                 if (($inserted_id_ret=$sqlQuery->fetch(PDO::FETCH_ASSOC)) === false) {
131
-                    $this->logging->log('Error getting id - pgsql - ',1,'');
131
+                    $this->logging->log('Error getting id - pgsql - ', 1, '');
132 132
                 }
133
-                if (! isset($inserted_id_ret['id'])) {
134
-                    $this->logging->log('Error getting id - pgsql - empty.',1,'');
133
+                if (!isset($inserted_id_ret['id'])) {
134
+                    $this->logging->log('Error getting id - pgsql - empty.', 1, '');
135 135
                 }
136 136
                 $this->dbOidIndex[$this->oidDesc['oid']]['id']=$inserted_id_ret['id'];
137 137
                 break;
@@ -139,15 +139,15 @@  discard block
 block discarded – undo
139 139
                 // Get last id to insert oid/values in secondary table
140 140
                 $sql='SELECT LAST_INSERT_ID();';
141 141
                 if (($ret_code=$db_conn->query($sql)) === false) {
142
-                    $this->logging->log('Erreur getting id - mysql - ',1,'');
142
+                    $this->logging->log('Erreur getting id - mysql - ', 1, '');
143 143
                 }
144 144
                 
145 145
                 $inserted_id=$ret_code->fetch(PDO::FETCH_ASSOC)['LAST_INSERT_ID()'];
146
-                if ($inserted_id==false) throw new Exception("Weird SQL error : last_insert_id returned false : open issue");
146
+                if ($inserted_id == false) throw new Exception("Weird SQL error : last_insert_id returned false : open issue");
147 147
                 $this->dbOidIndex[$this->oidDesc['oid']]['id']=$inserted_id;
148 148
                 break;
149 149
             default:
150
-                $this->logging->log('Error SQL type Unknown : '.$this->trapsDB->trapDBType,1,'');
150
+                $this->logging->log('Error SQL type Unknown : '.$this->trapsDB->trapDBType, 1, '');
151 151
         }
152 152
         
153 153
         // Set as newly created.
@@ -162,21 +162,21 @@  discard block
 block discarded – undo
162 162
      * @param array $objects : array of objects name (without MIB)
163 163
      * @param bool $check_existing : check instead of create
164 164
      */
165
-    public function trap_objects($trapOID,$trapmib,$objects,$check_existing)
165
+    public function trap_objects($trapOID, $trapmib, $objects, $check_existing)
166 166
     {
167 167
         $dbObjects=null; // cache of objects for trap in db
168 168
         $db_conn=$this->trapsDB->db_connect_trap();
169 169
         
170 170
         // Get id of trapmib.
171 171
         
172
-        $trapId = $this->dbOidIndex[$trapOID]['id'];
172
+        $trapId=$this->dbOidIndex[$trapOID]['id'];
173 173
         if ($check_existing === true)
174 174
         {
175 175
             // Get all objects
176 176
             $sql='SELECT * FROM '.$this->trapsDB->dbPrefix.'mib_cache_trap_object where trap_id='.$trapId.';';
177
-            $this->logging->log('SQL query get all traps: '.$sql,DEBUG );
177
+            $this->logging->log('SQL query get all traps: '.$sql, DEBUG);
178 178
             if (($ret_code=$db_conn->query($sql)) === false) {
179
-                $this->logging->log('No result in query : ' . $sql,1,'');
179
+                $this->logging->log('No result in query : '.$sql, 1, '');
180 180
             }
181 181
             $dbObjectsRaw=$ret_code->fetchAll();
182 182
             
@@ -197,36 +197,36 @@  discard block
 block discarded – undo
197 197
             $indesc=false; // true if currently inside multiline description
198 198
             
199 199
             $this->oidDesc['mib']=$trapmib;
200
-            exec($this->snmptranslate . ' -m ALL -M +'.$this->snmptranslate_dirs.
201
-                ' -On -Td '.$this->oidDesc['mib'].'::'.$object . ' 2>/dev/null',$snmptrans,$retVal);
202
-            if ($retVal!=0)
200
+            exec($this->snmptranslate.' -m ALL -M +'.$this->snmptranslate_dirs.
201
+                ' -On -Td '.$this->oidDesc['mib'].'::'.$object.' 2>/dev/null', $snmptrans, $retVal);
202
+            if ($retVal != 0)
203 203
             {
204 204
                 // Maybe not trap mib, search with IR
205
-                exec($this->snmptranslate . ' -m ALL -M +'.$this->snmptranslate_dirs.
206
-                    ' -IR '.$object . ' 2>/dev/null',$snmptrans,$retVal);
207
-                if ($retVal != 0 || !preg_match('/(.*)::(.*)/',$snmptrans[0],$match))
205
+                exec($this->snmptranslate.' -m ALL -M +'.$this->snmptranslate_dirs.
206
+                    ' -IR '.$object.' 2>/dev/null', $snmptrans, $retVal);
207
+                if ($retVal != 0 || !preg_match('/(.*)::(.*)/', $snmptrans[0], $match))
208 208
                 { // Not found -> continue with warning
209
-                    $this->logging->log('Error finding trap object : '.$trapmib.'::'.$object,2,'');
209
+                    $this->logging->log('Error finding trap object : '.$trapmib.'::'.$object, 2, '');
210 210
                     continue;
211 211
                 }
212 212
                 $this->oidDesc['mib']=$match[1];
213 213
                 
214 214
                 // Do the snmptranslate again.
215
-                exec($this->snmptranslate . ' -m ALL -M +'.$this->snmptranslate_dirs.
216
-                    ' -On -Td '.$this->oidDesc['mib'].'::'.$object,$snmptrans,$retVal);
217
-                if ($retVal!=0) {
218
-                    $this->logging->log('Error finding trap object : '.$this->oidDesc['mib'].'::'.$object,2,'');
215
+                exec($this->snmptranslate.' -m ALL -M +'.$this->snmptranslate_dirs.
216
+                    ' -On -Td '.$this->oidDesc['mib'].'::'.$object, $snmptrans, $retVal);
217
+                if ($retVal != 0) {
218
+                    $this->logging->log('Error finding trap object : '.$this->oidDesc['mib'].'::'.$object, 2, '');
219 219
                 }
220 220
                 
221 221
             }
222 222
             foreach ($snmptrans as $line)
223 223
             {
224
-                if ($indesc===true)
224
+                if ($indesc === true)
225 225
                 {
226
-                    $line=preg_replace('/[\t ]+/',' ',$line);
227
-                    if (preg_match('/(.*)"$/', $line,$match))
226
+                    $line=preg_replace('/[\t ]+/', ' ', $line);
227
+                    if (preg_match('/(.*)"$/', $line, $match))
228 228
                     {
229
-                        $this->oidDesc['description'] = $tmpdesc . $match[1];
229
+                        $this->oidDesc['description']=$tmpdesc.$match[1];
230 230
                         $indesc=false;
231 231
                     }
232 232
                     $tmpdesc.=$line;
@@ -237,41 +237,41 @@  discard block
 block discarded – undo
237 237
                     $this->oidDesc['oid']=$line;
238 238
                     continue;
239 239
                 }
240
-                if (preg_match('/^[\t ]+SYNTAX[\t ]+([^{]*) \{(.*)\}/',$line,$match))
240
+                if (preg_match('/^[\t ]+SYNTAX[\t ]+([^{]*) \{(.*)\}/', $line, $match))
241 241
                 {
242 242
                     $this->oidDesc['syntax']=$match[1];
243 243
                     $this->oidDesc['type_enum']=$match[2];
244 244
                     continue;
245 245
                 }
246
-                if (preg_match('/^[\t ]+SYNTAX[\t ]+(.*)/',$line,$match))
246
+                if (preg_match('/^[\t ]+SYNTAX[\t ]+(.*)/', $line, $match))
247 247
                 {
248 248
                     $this->oidDesc['syntax']=$match[1];
249 249
                     continue;
250 250
                 }
251
-                if (preg_match('/^[\t ]+DISPLAY-HINT[\t ]+"(.*)"/',$line,$match))
251
+                if (preg_match('/^[\t ]+DISPLAY-HINT[\t ]+"(.*)"/', $line, $match))
252 252
                 {
253 253
                     $this->oidDesc['dispHint']=$match[1];
254 254
                     continue;
255 255
                 }
256
-                if (preg_match('/^[\t ]+DESCRIPTION[\t ]+"(.*)"/',$line,$match))
256
+                if (preg_match('/^[\t ]+DESCRIPTION[\t ]+"(.*)"/', $line, $match))
257 257
                 {
258 258
                     $this->oidDesc['description']=$match[1];
259 259
                     continue;
260 260
                 }
261
-                if (preg_match('/^[\t ]+DESCRIPTION[\t ]+"(.*)/',$line,$match))
261
+                if (preg_match('/^[\t ]+DESCRIPTION[\t ]+"(.*)/', $line, $match))
262 262
                 {
263 263
                     $tmpdesc=$match[1];
264 264
                     $indesc=true;
265 265
                     continue;
266 266
                 }
267
-                if (preg_match('/^[\t ]+-- TEXTUAL CONVENTION[\t ]+(.*)/',$line,$match))
267
+                if (preg_match('/^[\t ]+-- TEXTUAL CONVENTION[\t ]+(.*)/', $line, $match))
268 268
                 {
269 269
                     $this->oidDesc['textconv']=$match[1];
270 270
                     continue;
271 271
                 }
272 272
             }
273
-            $this->oidDesc['name'] = $object;
274
-            $this->logging->log("Adding object ".$this->oidDesc['name']." : ".$this->oidDesc['oid']." / ".$this->oidDesc['syntax']." / ".$this->oidDesc['type_enum']." / ".$this->oidDesc['dispHint']." / ".$this->oidDesc['textconv'],DEBUG );
273
+            $this->oidDesc['name']=$object;
274
+            $this->logging->log("Adding object ".$this->oidDesc['name']." : ".$this->oidDesc['oid']." / ".$this->oidDesc['syntax']." / ".$this->oidDesc['type_enum']." / ".$this->oidDesc['dispHint']." / ".$this->oidDesc['textconv'], DEBUG);
275 275
             //echo "$this->oidDesc['name'] : $this->oidDesc['oid'] / $this->oidDesc['syntax'] / $this->oidDesc['type_enum'] / $this->oidDesc['dispHint'] / $this->oidDesc['textconv'] / $this->oidDesc['description']\n";
276 276
             // Update
277 277
             $this->update_oid();
@@ -295,7 +295,7 @@  discard block
 block discarded – undo
295 295
             );
296 296
             
297 297
             if ($sqlQuery->execute($sqlParam) === false) {
298
-                $this->logging->log('Error adding trap object : ' . $sql . ' / ' . $trapId . '/'. $this->dbOidIndex[$this->oidDesc['oid']]['id'] ,1,'');
298
+                $this->logging->log('Error adding trap object : '.$sql.' / '.$trapId.'/'.$this->dbOidIndex[$this->oidDesc['oid']]['id'], 1, '');
299 299
             }
300 300
         }
301 301
         if ($check_existing === true)
@@ -312,7 +312,7 @@  discard block
 block discarded – undo
312 312
         $this->oidDesc['type']=null;
313 313
         $this->oidDesc['mib']=null;
314 314
         $this->oidDesc['textconv']=null;
315
-        $this->oidDesc['dispHint'] =null;
315
+        $this->oidDesc['dispHint']=null;
316 316
         $this->oidDesc['syntax']=null;
317 317
         $this->oidDesc['type_enum']=null;
318 318
         $this->oidDesc['description']=null;
@@ -326,17 +326,17 @@  discard block
 block discarded – undo
326 326
     {
327 327
         $retVal=0;
328 328
         // Get all mib objects from all mibs
329
-        $snmpCommand=$this->snmptranslate . ' -m ALL -M +'.$this->snmptranslate_dirs.' -On -Tto 2>/dev/null';
330
-        $this->logging->log('Getting all traps : '.$snmpCommand,DEBUG );
329
+        $snmpCommand=$this->snmptranslate.' -m ALL -M +'.$this->snmptranslate_dirs.' -On -Tto 2>/dev/null';
330
+        $this->logging->log('Getting all traps : '.$snmpCommand, DEBUG);
331 331
         unset($this->objectsAll);
332
-        exec($snmpCommand,$this->objectsAll,$retVal);
333
-        if ($retVal!=0)
332
+        exec($snmpCommand, $this->objectsAll, $retVal);
333
+        if ($retVal != 0)
334 334
         {
335
-            $this->logging->log('error executing snmptranslate',ERROR,'');
335
+            $this->logging->log('error executing snmptranslate', ERROR, '');
336 336
         }
337 337
         // Count elements to show progress
338 338
         $numElements=count($this->objectsAll);
339
-        $this->logging->log('Total snmp objects returned by snmptranslate : '.$numElements,INFO );
339
+        $this->logging->log('Total snmp objects returned by snmptranslate : '.$numElements, INFO);
340 340
         return $numElements;
341 341
     }
342 342
 
@@ -350,14 +350,14 @@  discard block
 block discarded – undo
350 350
         $db_conn=$this->trapsDB->db_connect_trap();
351 351
         
352 352
         $sql='SELECT * from '.$this->trapsDB->dbPrefix.'mib_cache;';
353
-        $this->logging->log('SQL query : '.$sql,DEBUG );
353
+        $this->logging->log('SQL query : '.$sql, DEBUG);
354 354
         if (($ret_code=$db_conn->query($sql)) === false) {
355
-            $this->logging->log('No result in query : ' . $sql,ERROR,'');
355
+            $this->logging->log('No result in query : '.$sql, ERROR, '');
356 356
         }
357 357
         $this->dbOidAll=$ret_code->fetchAll();
358 358
         $this->dbOidIndex=array();
359 359
         // Create the index for db;
360
-        foreach($this->dbOidAll as $key=>$val)
360
+        foreach ($this->dbOidAll as $key=>$val)
361 361
         {
362 362
             $this->dbOidIndex[$val['oid']]['key']=$key;
363 363
             $this->dbOidIndex[$val['oid']]['id']=$val['id'];
@@ -384,13 +384,13 @@  discard block
 block discarded – undo
384 384
         $this->timing['num_traps']=0;
385 385
     }
386 386
 
387
-    private function detect_trap($curElement,$onlyTraps)
387
+    private function detect_trap($curElement, $onlyTraps)
388 388
     {
389 389
         // Get oid or pass if not found
390
-        if (!preg_match('/^\.[0-9\.]+$/',$this->objectsAll[$curElement]))
390
+        if (!preg_match('/^\.[0-9\.]+$/', $this->objectsAll[$curElement]))
391 391
         {
392
-            $this->timing['base_parse_time'] += microtime(true) - $this->timing['base_time'];
393
-            $this->timing['base_parse_num'] ++;
392
+            $this->timing['base_parse_time']+=microtime(true) - $this->timing['base_time'];
393
+            $this->timing['base_parse_num']++;
394 394
             return true;
395 395
         }
396 396
         $this->oidDesc['oid']=$this->objectsAll[$curElement];
@@ -399,9 +399,9 @@  discard block
 block discarded – undo
399 399
         $curElement++;
400 400
         $match=$snmptrans=array();
401 401
         if (!preg_match('/ +([^\(]+)\(.+\) type=([0-9]+)( tc=([0-9]+))?( hint=(.+))?/',
402
-            $this->objectsAll[$curElement],$match))
402
+            $this->objectsAll[$curElement], $match))
403 403
         {
404
-            $this->timing['base_check_time'] += microtime(true) - $this->timing['base_time'];
404
+            $this->timing['base_check_time']+=microtime(true) - $this->timing['base_time'];
405 405
             $this->timing['base_check_num']++;
406 406
             return true;
407 407
         }
@@ -409,22 +409,22 @@  discard block
 block discarded – undo
409 409
         $this->oidDesc['name']=$match[1]; // Name
410 410
         $this->oidDesc['type']=$match[2]; // type (21=trap, 0: may be trap, else : not trap
411 411
         
412
-        if ($this->oidDesc['type']==0) // object type=0 : check if v1 trap
412
+        if ($this->oidDesc['type'] == 0) // object type=0 : check if v1 trap
413 413
         {
414 414
             // Check if next is suboid -> in that case is cannot be a trap
415
-            if (preg_match("/^".$this->oidDesc['oid']."/",$this->objectsAll[$curElement+1]))
415
+            if (preg_match("/^".$this->oidDesc['oid']."/", $this->objectsAll[$curElement + 1]))
416 416
             {
417
-                $this->timing['type0_check_time'] += microtime(true) - $this->timing['base_time'];
417
+                $this->timing['type0_check_time']+=microtime(true) - $this->timing['base_time'];
418 418
                 $this->timing['type0_check_num']++;
419 419
                 return true;
420 420
             }
421 421
             unset($snmptrans);
422 422
             $retVal=0;
423
-            exec($this->snmptranslate . ' -m ALL -M +'.$this->snmptranslate_dirs.
424
-                ' -Td '.$this->oidDesc['oid'] . ' | grep OBJECTS ',$snmptrans,$retVal);
425
-            if ($retVal!=0)
423
+            exec($this->snmptranslate.' -m ALL -M +'.$this->snmptranslate_dirs.
424
+                ' -Td '.$this->oidDesc['oid'].' | grep OBJECTS ', $snmptrans, $retVal);
425
+            if ($retVal != 0)
426 426
             {
427
-                $this->timing['type0_check_time'] += microtime(true) - $this->timing['base_time'];
427
+                $this->timing['type0_check_time']+=microtime(true) - $this->timing['base_time'];
428 428
                 $this->timing['type0_check_num']++;
429 429
                 return true;
430 430
             }
@@ -432,9 +432,9 @@  discard block
 block discarded – undo
432 432
             // Force as trap.
433 433
             $this->oidDesc['type']=21;
434 434
         }
435
-        if ($onlyTraps===true && $this->oidDesc['type']!=21) // if only traps and not a trap, continue
435
+        if ($onlyTraps === true && $this->oidDesc['type'] != 21) // if only traps and not a trap, continue
436 436
         {
437
-            $this->timing['nottrap_time'] += microtime(true) - $this->timing['base_time'];
437
+            $this->timing['nottrap_time']+=microtime(true) - $this->timing['base_time'];
438 438
             $this->timing['nottrap_num']++;
439 439
             return true;
440 440
         }
@@ -448,18 +448,18 @@  discard block
 block discarded – undo
448 448
      * @param boolean $onlyTraps : only cache traps and objects (true) or all (false)
449 449
      * @param string $startOID : only cache under startOID (NOT IMPLEMENTED)
450 450
      */
451
-    public function update_mib_database($display_progress=false,$check_change=false,$onlyTraps=true,$startOID='.1')
451
+    public function update_mib_database($display_progress=false, $check_change=false, $onlyTraps=true, $startOID='.1')
452 452
     {
453 453
         // Global Timing
454
-        $timeTaken = microtime(true);
454
+        $timeTaken=microtime(true);
455 455
         
456 456
         $numElements=$this->load_mibs_snmptranslate(); // Load objectsAll
457 457
         
458 458
         $this->load_mibs_from_db(); // Load from db dbOidAll & dbOidIndex
459 459
         
460
-        $step=$basestep=$numElements/10; // output display of % done
460
+        $step=$basestep=$numElements / 10; // output display of % done
461 461
         $num_step=0;
462
-        $timeFiveSec = microtime(true); // Used for display a '.' every <n> seconds
462
+        $timeFiveSec=microtime(true); // Used for display a '.' every <n> seconds
463 463
         
464 464
         // Create index for trap objects
465 465
         $this->trapObjectsIndex=array();
@@ -467,80 +467,80 @@  discard block
 block discarded – undo
467 467
         // detailed timing (time_* vars)
468 468
         $this->reset_update_timers();
469 469
         
470
-        for ($curElement=0;$curElement < $numElements;$curElement++)
470
+        for ($curElement=0; $curElement < $numElements; $curElement++)
471 471
         {
472
-            $this->timing['base_time']= microtime(true);
472
+            $this->timing['base_time']=microtime(true);
473 473
             if ($display_progress)
474 474
             {
475
-                if ((microtime(true)-$timeFiveSec) > 2)
475
+                if ((microtime(true) - $timeFiveSec) > 2)
476 476
                 { // echo a . every 2 sec
477 477
                     echo '.';
478
-                    $timeFiveSec = microtime(true);
478
+                    $timeFiveSec=microtime(true);
479 479
                 }
480
-                if ($curElement>$step)
480
+                if ($curElement > $step)
481 481
                 { // display progress
482 482
                     $num_step++;
483 483
                     $step+=$basestep;   
484
-                    echo "\n" . ($num_step*10). '% : ';
484
+                    echo "\n".($num_step * 10).'% : ';
485 485
                 }
486 486
             }
487 487
             
488 488
             $this->reset_oidDesc();
489
-            if ($this->detect_trap($curElement,$onlyTraps)===true)
489
+            if ($this->detect_trap($curElement, $onlyTraps) === true)
490 490
             {
491 491
                 continue;
492 492
             }
493 493
             
494 494
             $this->timing['num_traps']++;
495 495
             
496
-            $this->logging->log('Found trap : '.$this->oidDesc['name'] . ' / OID : '.$this->oidDesc['oid'],INFO );
496
+            $this->logging->log('Found trap : '.$this->oidDesc['name'].' / OID : '.$this->oidDesc['oid'], INFO);
497 497
             if ($display_progress) echo '#'; // echo a # when trap found
498 498
             
499 499
             //################################
500 500
             // get trap objects & source MIB
501 501
             $retVal=0;
502 502
             $match=$snmptrans=array();
503
-            exec($this->snmptranslate . ' -m ALL -M +'.$this->snmptranslate_dirs.
504
-                ' -Td '.$this->oidDesc['oid'],$snmptrans,$retVal);
505
-            if ($retVal!=0)
503
+            exec($this->snmptranslate.' -m ALL -M +'.$this->snmptranslate_dirs.
504
+                ' -Td '.$this->oidDesc['oid'], $snmptrans, $retVal);
505
+            if ($retVal != 0)
506 506
             {
507
-                $this->logging->log('error executing snmptranslate',ERROR);
507
+                $this->logging->log('error executing snmptranslate', ERROR);
508 508
             }
509 509
             
510
-            if (!preg_match('/^(.*)::/',$snmptrans[0],$match))
510
+            if (!preg_match('/^(.*)::/', $snmptrans[0], $match))
511 511
             {
512
-                $this->logging->log('Error getting mib from trap '.$this->oidDesc['oid'].' : ' . $snmptrans[0],ERROR);
512
+                $this->logging->log('Error getting mib from trap '.$this->oidDesc['oid'].' : '.$snmptrans[0], ERROR);
513 513
             }
514 514
             $this->oidDesc['mib']=$match[1];
515 515
             
516 516
             $numLine=1;
517
-            while (isset($snmptrans[$numLine]) && !preg_match('/^[\t ]+DESCRIPTION[\t ]+"(.*)/',$snmptrans[$numLine],$match)) $numLine++;
517
+            while (isset($snmptrans[$numLine]) && !preg_match('/^[\t ]+DESCRIPTION[\t ]+"(.*)/', $snmptrans[$numLine], $match)) $numLine++;
518 518
             if (isset($snmptrans[$numLine]))
519 519
             {
520
-                $snmptrans[$numLine] = preg_replace('/^[\t ]+DESCRIPTION[\t ]+"/','',$snmptrans[$numLine]);
520
+                $snmptrans[$numLine]=preg_replace('/^[\t ]+DESCRIPTION[\t ]+"/', '', $snmptrans[$numLine]);
521 521
                 
522
-                while (isset($snmptrans[$numLine]) && !preg_match('/"/',$snmptrans[$numLine]))
522
+                while (isset($snmptrans[$numLine]) && !preg_match('/"/', $snmptrans[$numLine]))
523 523
                 {
524
-                    $this->oidDesc['description'].=preg_replace('/[\t ]+/',' ',$snmptrans[$numLine]);
524
+                    $this->oidDesc['description'].=preg_replace('/[\t ]+/', ' ', $snmptrans[$numLine]);
525 525
                     $numLine++;
526 526
                 }
527 527
                 if (isset($snmptrans[$numLine])) {
528
-                    $this->oidDesc['description'].=preg_replace('/".*/','',$snmptrans[$numLine]);
529
-                    $this->oidDesc['description']=preg_replace('/[\t ]+/',' ',$this->oidDesc['description']);
528
+                    $this->oidDesc['description'].=preg_replace('/".*/', '', $snmptrans[$numLine]);
529
+                    $this->oidDesc['description']=preg_replace('/[\t ]+/', ' ', $this->oidDesc['description']);
530 530
                 }
531 531
                 
532 532
             }
533 533
             
534 534
             $update=$this->update_oid(); // Do update of trap.
535 535
             
536
-            $this->timing['update_time'] += microtime(true) - $this->timing['base_time'];
536
+            $this->timing['update_time']+=microtime(true) - $this->timing['base_time'];
537 537
             $this->timing['update_num']++;
538 538
             
539
-            $this->timing['base_time']= microtime(true); // Reset to check object time
539
+            $this->timing['base_time']=microtime(true); // Reset to check object time
540 540
             
541
-            if (($update==0) && ($check_change===false))
541
+            if (($update == 0) && ($check_change === false))
542 542
             { // Trapd didn't change & force check disabled
543
-                $this->timing['objects_time'] += microtime(true) - $this->timing['base_time'];
543
+                $this->timing['objects_time']+=microtime(true) - $this->timing['base_time'];
544 544
                 if ($display_progress) echo "C";
545 545
                 continue;
546 546
             }
@@ -548,7 +548,7 @@  discard block
 block discarded – undo
548 548
             $synt=null;
549 549
             foreach ($snmptrans as $line)
550 550
             {
551
-                if (preg_match('/OBJECTS.*\{([^\}]+)\}/',$line,$match))
551
+                if (preg_match('/OBJECTS.*\{([^\}]+)\}/', $line, $match))
552 552
                 {
553 553
                     $synt=$match[1];
554 554
                 }
@@ -556,30 +556,30 @@  discard block
 block discarded – undo
556 556
             if ($synt == null)
557 557
             {
558 558
                 //echo "No objects for $trapOID\n";
559
-                $this->timing['objects_time'] += microtime(true) - $this->timing['base_time'];
559
+                $this->timing['objects_time']+=microtime(true) - $this->timing['base_time'];
560 560
                 continue;
561 561
             }
562 562
             //echo "$synt \n";
563 563
             $trapObjects=array();
564
-            while (preg_match('/ *([^ ,]+) *,* */',$synt,$match))
564
+            while (preg_match('/ *([^ ,]+) *,* */', $synt, $match))
565 565
             {
566
-                array_push($trapObjects,$match[1]);
567
-                $synt=preg_replace('/'.$match[0].'/','',$synt);
566
+                array_push($trapObjects, $match[1]);
567
+                $synt=preg_replace('/'.$match[0].'/', '', $synt);
568 568
             }
569 569
             
570 570
             $this->trap_objects($this->oidDesc['oid'], $this->oidDesc['mib'], $trapObjects, false);
571 571
             
572
-            $this->timing['objects_time'] += microtime(true) - $this->timing['base_time'];
572
+            $this->timing['objects_time']+=microtime(true) - $this->timing['base_time'];
573 573
             $this->timing['objects_num']++;
574 574
         }
575 575
         
576 576
         if ($display_progress)
577 577
         {
578
-            echo "\nNumber of processed traps :  ". $this->timing['num_traps'] ."\n";
579
-            echo "\nParsing : " . number_format($this->timing['base_parse_time']+$this->timing['base_check_time'],1) ." sec / " . ($this->timing['base_parse_num']+ $this->timing['base_check_num'])  . " occurences\n";
580
-            echo "Detecting traps : " . number_format($this->timing['type0_check_time']+$this->timing['nottrap_time'],1) . " sec / " . ($this->timing['type0_check_num']+$this->timing['nottrap_num']) ." occurences\n";
581
-            echo "Trap processing (".$this->timing['update_num']."): ".number_format($this->timing['update_time'],1)." sec , ";
582
-            echo "Objects processing (".$this->timing['objects_num'].") : ".number_format($this->timing['objects_time'],1)." sec \n";
578
+            echo "\nNumber of processed traps :  ".$this->timing['num_traps']."\n";
579
+            echo "\nParsing : ".number_format($this->timing['base_parse_time'] + $this->timing['base_check_time'], 1)." sec / ".($this->timing['base_parse_num'] + $this->timing['base_check_num'])." occurences\n";
580
+            echo "Detecting traps : ".number_format($this->timing['type0_check_time'] + $this->timing['nottrap_time'], 1)." sec / ".($this->timing['type0_check_num'] + $this->timing['nottrap_num'])." occurences\n";
581
+            echo "Trap processing (".$this->timing['update_num']."): ".number_format($this->timing['update_time'], 1)." sec , ";
582
+            echo "Objects processing (".$this->timing['objects_num'].") : ".number_format($this->timing['objects_time'], 1)." sec \n";
583 583
             
584 584
             $timeTaken=microtime(true) - $timeTaken;
585 585
             echo "Global time : ".round($timeTaken)." seconds\n";
Please login to merge, or discard this patch.
Braces   +23 added lines, -9 removed lines patch added patch discarded remove patch
@@ -86,8 +86,7 @@  discard block
 block discarded – undo
86 86
                 }
87 87
                 $this->logging->log('Trap updated : '.$this->oidDesc['name'] . ' / OID : '.$this->oidDesc['oid'],DEBUG );
88 88
                 return 1;
89
-            }
90
-            else
89
+            } else
91 90
             {
92 91
                 $this->logging->log('Trap unchanged : '.$this->oidDesc['name'] . ' / OID : '.$this->oidDesc['oid'],DEBUG );
93 92
                 return 0;
@@ -103,7 +102,9 @@  discard block
 block discarded – undo
103 102
             'values (:oid, :name , :type ,:mib ,:tc , :display_hint'.
104 103
             ', :syntax, :type_enum, :description )';
105 104
         
106
-        if ($this->trapsDB->trapDBType == 'pgsql') $sql .= 'RETURNING id';
105
+        if ($this->trapsDB->trapDBType == 'pgsql') {
106
+        	$sql .= 'RETURNING id';
107
+        }
107 108
         
108 109
         $sqlQuery=$db_conn->prepare($sql);
109 110
         
@@ -143,7 +144,9 @@  discard block
 block discarded – undo
143 144
                 }
144 145
                 
145 146
                 $inserted_id=$ret_code->fetch(PDO::FETCH_ASSOC)['LAST_INSERT_ID()'];
146
-                if ($inserted_id==false) throw new Exception("Weird SQL error : last_insert_id returned false : open issue");
147
+                if ($inserted_id==false) {
148
+                	throw new Exception("Weird SQL error : last_insert_id returned false : open issue");
149
+                }
147 150
                 $this->dbOidIndex[$this->oidDesc['oid']]['id']=$inserted_id;
148 151
                 break;
149 152
             default:
@@ -409,12 +412,14 @@  discard block
 block discarded – undo
409 412
         $this->oidDesc['name']=$match[1]; // Name
410 413
         $this->oidDesc['type']=$match[2]; // type (21=trap, 0: may be trap, else : not trap
411 414
         
412
-        if ($this->oidDesc['type']==0) // object type=0 : check if v1 trap
415
+        if ($this->oidDesc['type']==0) {
416
+        	// object type=0 : check if v1 trap
413 417
         {
414 418
             // Check if next is suboid -> in that case is cannot be a trap
415 419
             if (preg_match("/^".$this->oidDesc['oid']."/",$this->objectsAll[$curElement+1]))
416 420
             {
417 421
                 $this->timing['type0_check_time'] += microtime(true) - $this->timing['base_time'];
422
+        }
418 423
                 $this->timing['type0_check_num']++;
419 424
                 return true;
420 425
             }
@@ -432,9 +437,11 @@  discard block
 block discarded – undo
432 437
             // Force as trap.
433 438
             $this->oidDesc['type']=21;
434 439
         }
435
-        if ($onlyTraps===true && $this->oidDesc['type']!=21) // if only traps and not a trap, continue
440
+        if ($onlyTraps===true && $this->oidDesc['type']!=21) {
441
+        	// if only traps and not a trap, continue
436 442
         {
437 443
             $this->timing['nottrap_time'] += microtime(true) - $this->timing['base_time'];
444
+        }
438 445
             $this->timing['nottrap_num']++;
439 446
             return true;
440 447
         }
@@ -494,7 +501,10 @@  discard block
 block discarded – undo
494 501
             $this->timing['num_traps']++;
495 502
             
496 503
             $this->logging->log('Found trap : '.$this->oidDesc['name'] . ' / OID : '.$this->oidDesc['oid'],INFO );
497
-            if ($display_progress) echo '#'; // echo a # when trap found
504
+            if ($display_progress) {
505
+            	echo '#';
506
+            }
507
+            // echo a # when trap found
498 508
             
499 509
             //################################
500 510
             // get trap objects & source MIB
@@ -514,7 +524,9 @@  discard block
 block discarded – undo
514 524
             $this->oidDesc['mib']=$match[1];
515 525
             
516 526
             $numLine=1;
517
-            while (isset($snmptrans[$numLine]) && !preg_match('/^[\t ]+DESCRIPTION[\t ]+"(.*)/',$snmptrans[$numLine],$match)) $numLine++;
527
+            while (isset($snmptrans[$numLine]) && !preg_match('/^[\t ]+DESCRIPTION[\t ]+"(.*)/',$snmptrans[$numLine],$match)) {
528
+            	$numLine++;
529
+            }
518 530
             if (isset($snmptrans[$numLine]))
519 531
             {
520 532
                 $snmptrans[$numLine] = preg_replace('/^[\t ]+DESCRIPTION[\t ]+"/','',$snmptrans[$numLine]);
@@ -541,7 +553,9 @@  discard block
 block discarded – undo
541 553
             if (($update==0) && ($check_change===false))
542 554
             { // Trapd didn't change & force check disabled
543 555
                 $this->timing['objects_time'] += microtime(true) - $this->timing['base_time'];
544
-                if ($display_progress) echo "C";
556
+                if ($display_progress) {
557
+                	echo "C";
558
+                }
545 559
                 continue;
546 560
             }
547 561
             
Please login to merge, or discard this patch.