Passed
Push — master ( 278791...f4c14e )
by Patrick
01:54
created
application/clicommands/MibCommand.php 3 patches
Indentation   +76 added lines, -76 removed lines patch added patch discarded remove patch
@@ -22,77 +22,77 @@  discard block
 block discarded – undo
22 22
 class MibCommand extends Command
23 23
 {
24 24
 	/**
25
-	*	Update mib database
26
-	*
27
-	*	USAGE 
28
-	*
29
-	*	icingli trapdirector mib update
30
-	*	
31
-	*	OPTIONS
32
-	*	
33
-	*	--pid <file> : run in background with pid in <file>
34
-	*
35
-	*	--verb    : Set output log to verbose
36
-	*
37
-	*   --force-check : force check of all traps & objects for change. (NOT IMPLEMENTED)
38
-	*/
25
+	 *	Update mib database
26
+	 *
27
+	 *	USAGE 
28
+	 *
29
+	 *	icingli trapdirector mib update
30
+	 *	
31
+	 *	OPTIONS
32
+	 *	
33
+	 *	--pid <file> : run in background with pid in <file>
34
+	 *
35
+	 *	--verb    : Set output log to verbose
36
+	 *
37
+	 *   --force-check : force check of all traps & objects for change. (NOT IMPLEMENTED)
38
+	 */
39 39
 	public function updateAction()
40 40
 	{
41
-	    $background = $this->params->get('pid', null);
42
-	    $logLevel= $this->params->has('verb') ? 4 : 2;
43
-	    if ($this->params->has('force-check')) { echo "Not implemented"; return;}
44
-	    $forceCheck=$this->params->has('force-check')?True:False;
45
-	    $pid=1;
46
-	    if ($background != null)
47
-	    {
48
-	        $file=@fopen($background,'w');
49
-	        if ($file == false)
50
-	        {
51
-	            echo 'Error : cannot open pid file '.$background;
52
-	            return 1;
53
-	        }
54
-	        $pid = pcntl_fork();
55
-	        if ($pid == -1) {
56
-	            echo 'Error : Cannot fork process';
57
-	            return 1;
58
-	        }
59
-	    }
60
-	    $module=Icinga::app()->getModuleManager()->getModule($this->getModuleName());
41
+		$background = $this->params->get('pid', null);
42
+		$logLevel= $this->params->has('verb') ? 4 : 2;
43
+		if ($this->params->has('force-check')) { echo "Not implemented"; return;}
44
+		$forceCheck=$this->params->has('force-check')?True:False;
45
+		$pid=1;
46
+		if ($background != null)
47
+		{
48
+			$file=@fopen($background,'w');
49
+			if ($file == false)
50
+			{
51
+				echo 'Error : cannot open pid file '.$background;
52
+				return 1;
53
+			}
54
+			$pid = pcntl_fork();
55
+			if ($pid == -1) {
56
+				echo 'Error : Cannot fork process';
57
+				return 1;
58
+			}
59
+		}
60
+		$module=Icinga::app()->getModuleManager()->getModule($this->getModuleName());
61 61
 		require_once($module->getBaseDir() .'/bin/trap_class.php');
62 62
 		$icingaweb2_etc=$this->Config()->get('config', 'icingaweb2_etc');
63 63
 		$trap = new Trap($icingaweb2_etc);
64 64
 		if ($pid == 1)
65 65
 		{
66
-		    $trap->setLogging($logLevel,'display');
66
+			$trap->setLogging($logLevel,'display');
67 67
 		}
68 68
 		else
69 69
 		{  // use default display TODO : if default is 'display' son process will be killed at first output....
70
-		    if ($pid != 0)
71
-		    {
72
-		        // father process
73
-		        fwrite($file,$pid);
74
-		        fclose($file);
75
-		        echo "OK : process $pid in bckground";
76
-		        return 0;
77
-		    }
78
-		    else
79
-		    {  // son process : close all file descriptors and go to a new session
80
-		        fclose($file);		        
70
+			if ($pid != 0)
71
+			{
72
+				// father process
73
+				fwrite($file,$pid);
74
+				fclose($file);
75
+				echo "OK : process $pid in bckground";
76
+				return 0;
77
+			}
78
+			else
79
+			{  // son process : close all file descriptors and go to a new session
80
+				fclose($file);		        
81 81
 // 		        $sid = posix_setsid();
82
-                fclose(STDIN);
83
-                fclose(STDOUT);
84
-                fclose(STDERR);
85
-                try
86
-                {
87
-                    $trap->mibClass->update_mib_database(false,$forceCheck);
88
-                }
89
-                catch (Exception $e)
90
-                {
91
-                    $trap->trapLog('Error in updating : ' . $e->getMessage(),2);
92
-                }
93
-                unlink($background);
94
-                return 0;
95
-		    }
82
+				fclose(STDIN);
83
+				fclose(STDOUT);
84
+				fclose(STDERR);
85
+				try
86
+				{
87
+					$trap->mibClass->update_mib_database(false,$forceCheck);
88
+				}
89
+				catch (Exception $e)
90
+				{
91
+					$trap->trapLog('Error in updating : ' . $e->getMessage(),2);
92
+				}
93
+				unlink($background);
94
+				return 0;
95
+			}
96 96
 		    
97 97
 		}
98 98
 		
@@ -110,28 +110,28 @@  discard block
 block discarded – undo
110 110
 		}
111 111
 		if ($pid != 1)
112 112
 		{
113
-		    unlink($background);
113
+			unlink($background);
114 114
 		}
115 115
 	}
116 116
 	/**
117
-	*	purge all mib database NOT IMPLEMENTED
118
-	*
119
-	*	USAGE 
120
-	*
121
-	*	icingli trapdirector mib purge --confirm
122
-	*	
123
-	*	OPTIONS
124
-	*	
125
-	*	--confirm : needed to execute purge
126
-	*/
117
+	 *	purge all mib database NOT IMPLEMENTED
118
+	 *
119
+	 *	USAGE 
120
+	 *
121
+	 *	icingli trapdirector mib purge --confirm
122
+	 *	
123
+	 *	OPTIONS
124
+	 *	
125
+	 *	--confirm : needed to execute purge
126
+	 */
127 127
 	public function purgeAction()
128 128
 	{
129 129
 		$db_prefix=$this->Config()->get('config', 'database_prefix');
130 130
 		
131 131
 		if (!$this->params->has('confirm'))
132 132
 		{
133
-		    echo "This needs confirmation with '--confirm'\n";
134
-		    return;
133
+			echo "This needs confirmation with '--confirm'\n";
134
+			return;
135 135
 		}
136 136
 		
137 137
 		$Config = new TrapModuleConfig($db_prefix);
@@ -144,9 +144,9 @@  discard block
 block discarded – undo
144 144
 			$db = IcingaDbConnection::fromResourceName($dbresource)->getConnection();
145 145
 			
146 146
 			$query = $db->delete(
147
-			    $Config->getMIBCacheTableName(),
148
-			    'id>0');
149
-            echo 'Deleted '. $query . " traps and objects\n";
147
+				$Config->getMIBCacheTableName(),
148
+				'id>0');
149
+			echo 'Deleted '. $query . " traps and objects\n";
150 150
 		}
151 151
 		catch (Exception $e)
152 152
 		{
Please login to merge, or discard this patch.
Spacing   +19 added lines, -19 removed lines patch added patch discarded remove patch
@@ -38,39 +38,39 @@  discard block
 block discarded – undo
38 38
 	*/
39 39
 	public function updateAction()
40 40
 	{
41
-	    $background = $this->params->get('pid', null);
42
-	    $logLevel= $this->params->has('verb') ? 4 : 2;
43
-	    if ($this->params->has('force-check')) { echo "Not implemented"; return;}
44
-	    $forceCheck=$this->params->has('force-check')?True:False;
41
+	    $background=$this->params->get('pid', null);
42
+	    $logLevel=$this->params->has('verb') ? 4 : 2;
43
+	    if ($this->params->has('force-check')) { echo "Not implemented"; return; }
44
+	    $forceCheck=$this->params->has('force-check') ?True:False;
45 45
 	    $pid=1;
46 46
 	    if ($background != null)
47 47
 	    {
48
-	        $file=@fopen($background,'w');
48
+	        $file=@fopen($background, 'w');
49 49
 	        if ($file == false)
50 50
 	        {
51 51
 	            echo 'Error : cannot open pid file '.$background;
52 52
 	            return 1;
53 53
 	        }
54
-	        $pid = pcntl_fork();
54
+	        $pid=pcntl_fork();
55 55
 	        if ($pid == -1) {
56 56
 	            echo 'Error : Cannot fork process';
57 57
 	            return 1;
58 58
 	        }
59 59
 	    }
60 60
 	    $module=Icinga::app()->getModuleManager()->getModule($this->getModuleName());
61
-		require_once($module->getBaseDir() .'/bin/trap_class.php');
61
+		require_once($module->getBaseDir().'/bin/trap_class.php');
62 62
 		$icingaweb2_etc=$this->Config()->get('config', 'icingaweb2_etc');
63
-		$trap = new Trap($icingaweb2_etc);
63
+		$trap=new Trap($icingaweb2_etc);
64 64
 		if ($pid == 1)
65 65
 		{
66
-		    $trap->setLogging($logLevel,'display');
66
+		    $trap->setLogging($logLevel, 'display');
67 67
 		}
68 68
 		else
69 69
 		{  // use default display TODO : if default is 'display' son process will be killed at first output....
70 70
 		    if ($pid != 0)
71 71
 		    {
72 72
 		        // father process
73
-		        fwrite($file,$pid);
73
+		        fwrite($file, $pid);
74 74
 		        fclose($file);
75 75
 		        echo "OK : process $pid in bckground";
76 76
 		        return 0;
@@ -84,11 +84,11 @@  discard block
 block discarded – undo
84 84
                 fclose(STDERR);
85 85
                 try
86 86
                 {
87
-                    $trap->mibClass->update_mib_database(false,$forceCheck);
87
+                    $trap->mibClass->update_mib_database(false, $forceCheck);
88 88
                 }
89 89
                 catch (Exception $e)
90 90
                 {
91
-                    $trap->trapLog('Error in updating : ' . $e->getMessage(),2);
91
+                    $trap->trapLog('Error in updating : '.$e->getMessage(), 2);
92 92
                 }
93 93
                 unlink($background);
94 94
                 return 0;
@@ -100,13 +100,13 @@  discard block
 block discarded – undo
100 100
 		{
101 101
 			echo "Update main mib database : \n";
102 102
 			echo "# (trap found) C (trap already processed) . (every 2 seconds) : \n";
103
-			$trap->mibClass->update_mib_database(true,$forceCheck);
103
+			$trap->mibClass->update_mib_database(true, $forceCheck);
104 104
 			echo "Done\n";
105 105
 			
106 106
 		}
107 107
 		catch (Exception $e)
108 108
 		{
109
-			echo 'Error in updating : ' . $e->getMessage();
109
+			echo 'Error in updating : '.$e->getMessage();
110 110
 		}
111 111
 		if ($pid != 1)
112 112
 		{
@@ -134,23 +134,23 @@  discard block
 block discarded – undo
134 134
 		    return;
135 135
 		}
136 136
 		
137
-		$Config = new TrapModuleConfig($db_prefix);
137
+		$Config=new TrapModuleConfig($db_prefix);
138 138
 		
139 139
 		try
140 140
 		{
141 141
 			
142 142
 			$dbresource=$this->Config()->get('config', 'database');
143 143
 			echo "DB name : $dbresource\n";
144
-			$db = IcingaDbConnection::fromResourceName($dbresource)->getConnection();
144
+			$db=IcingaDbConnection::fromResourceName($dbresource)->getConnection();
145 145
 			
146
-			$query = $db->delete(
146
+			$query=$db->delete(
147 147
 			    $Config->getMIBCacheTableName(),
148 148
 			    'id>0');
149
-            echo 'Deleted '. $query . " traps and objects\n";
149
+            echo 'Deleted '.$query." traps and objects\n";
150 150
 		}
151 151
 		catch (Exception $e)
152 152
 		{
153
-			echo 'Error in DB : ' . $e->getMessage();
153
+			echo 'Error in DB : '.$e->getMessage();
154 154
 		}	   
155 155
 	}  	 	
156 156
 
Please login to merge, or discard this patch.
Braces   +5 added lines, -10 removed lines patch added patch discarded remove patch
@@ -64,8 +64,7 @@  discard block
 block discarded – undo
64 64
 		if ($pid == 1)
65 65
 		{
66 66
 		    $trap->setLogging($logLevel,'display');
67
-		}
68
-		else
67
+		} else
69 68
 		{  // use default display TODO : if default is 'display' son process will be killed at first output....
70 69
 		    if ($pid != 0)
71 70
 		    {
@@ -74,8 +73,7 @@  discard block
 block discarded – undo
74 73
 		        fclose($file);
75 74
 		        echo "OK : process $pid in bckground";
76 75
 		        return 0;
77
-		    }
78
-		    else
76
+		    } else
79 77
 		    {  // son process : close all file descriptors and go to a new session
80 78
 		        fclose($file);		        
81 79
 // 		        $sid = posix_setsid();
@@ -85,8 +83,7 @@  discard block
 block discarded – undo
85 83
                 try
86 84
                 {
87 85
                     $trap->mibClass->update_mib_database(false,$forceCheck);
88
-                }
89
-                catch (Exception $e)
86
+                } catch (Exception $e)
90 87
                 {
91 88
                     $trap->trapLog('Error in updating : ' . $e->getMessage(),2);
92 89
                 }
@@ -103,8 +100,7 @@  discard block
 block discarded – undo
103 100
 			$trap->mibClass->update_mib_database(true,$forceCheck);
104 101
 			echo "Done\n";
105 102
 			
106
-		}
107
-		catch (Exception $e)
103
+		} catch (Exception $e)
108 104
 		{
109 105
 			echo 'Error in updating : ' . $e->getMessage();
110 106
 		}
@@ -147,8 +143,7 @@  discard block
 block discarded – undo
147 143
 			    $Config->getMIBCacheTableName(),
148 144
 			    'id>0');
149 145
             echo 'Deleted '. $query . " traps and objects\n";
150
-		}
151
-		catch (Exception $e)
146
+		} catch (Exception $e)
152 147
 		{
153 148
 			echo 'Error in DB : ' . $e->getMessage();
154 149
 		}	   
Please login to merge, or discard this patch.
library/Trapdirector/TrapsProcess/Mib.php 3 patches
Braces   +27 added lines, -10 removed lines patch added patch discarded remove patch
@@ -84,8 +84,7 @@  discard block
 block discarded – undo
84 84
             }
85 85
             $this->logging->log('Trap updated : '.$this->oidDesc['name'] . ' / OID : '.$this->oidDesc['oid'],DEBUG );
86 86
             return 1;
87
-        }
88
-        else
87
+        } else
89 88
         {
90 89
             $this->logging->log('Trap unchanged : '.$this->oidDesc['name'] . ' / OID : '.$this->oidDesc['oid'],DEBUG );
91 90
             return 0;
@@ -107,7 +106,9 @@  discard block
 block discarded – undo
107 106
             'values (:oid, :name , :type ,:mib ,:tc , :display_hint'.
108 107
             ', :syntax, :type_enum, :description )';
109 108
         
110
-        if ($this->trapsDB->trapDBType == 'pgsql') $sql .= 'RETURNING id';
109
+        if ($this->trapsDB->trapDBType == 'pgsql') {
110
+        	$sql .= 'RETURNING id';
111
+        }
111 112
         
112 113
         $sqlQuery=$db_conn->prepare($sql);
113 114
         
@@ -147,7 +148,9 @@  discard block
 block discarded – undo
147 148
                 }
148 149
                 
149 150
                 $inserted_id=$ret_code->fetch(PDO::FETCH_ASSOC)['LAST_INSERT_ID()'];
150
-                if ($inserted_id==false) throw new Exception("Weird SQL error : last_insert_id returned false : open issue");
151
+                if ($inserted_id==false) {
152
+                	throw new Exception("Weird SQL error : last_insert_id returned false : open issue");
153
+                }
151 154
                 $this->dbOidIndex[$this->oidDesc['oid']]['id']=$inserted_id;
152 155
                 break;
153 156
             default:
@@ -325,7 +328,10 @@  discard block
 block discarded – undo
325 328
             $this->reset_oidDesc();
326 329
             
327 330
             $snmptrans=$this->get_object_details($object, $trapmib); // Get object mib & details
328
-            if ($snmptrans === null) continue; // object not found
331
+            if ($snmptrans === null) {
332
+            	continue;
333
+            }
334
+            // object not found
329 335
             
330 336
             $this->parse_object($snmptrans);
331 337
 
@@ -476,12 +482,14 @@  discard block
 block discarded – undo
476 482
         $this->oidDesc['name']=$match[1]; // Name
477 483
         $this->oidDesc['type']=$match[2]; // type (21=trap, 0: may be trap, else : not trap
478 484
         
479
-        if ($this->oidDesc['type']==0) // object type=0 : check if v1 trap
485
+        if ($this->oidDesc['type']==0) {
486
+        	// object type=0 : check if v1 trap
480 487
         {
481 488
             // Check if next is suboid -> in that case is cannot be a trap
482 489
             if (preg_match("/^".$this->oidDesc['oid']."/",$this->objectsAll[$curElement+1]))
483 490
             {
484 491
                 $this->timing['type0_check_time'] += microtime(true) - $this->timing['base_time'];
492
+        }
485 493
                 $this->timing['type0_check_num']++;
486 494
                 return true;
487 495
             }
@@ -499,9 +507,11 @@  discard block
 block discarded – undo
499 507
             // Force as trap.
500 508
             $this->oidDesc['type']=21;
501 509
         }
502
-        if ($onlyTraps===true && $this->oidDesc['type']!=21) // if only traps and not a trap, continue
510
+        if ($onlyTraps===true && $this->oidDesc['type']!=21) {
511
+        	// if only traps and not a trap, continue
503 512
         {
504 513
             $this->timing['nottrap_time'] += microtime(true) - $this->timing['base_time'];
514
+        }
505 515
             $this->timing['nottrap_num']++;
506 516
             return true;
507 517
         }
@@ -532,7 +542,9 @@  discard block
 block discarded – undo
532 542
         $this->oidDesc['mib']=$match[1];
533 543
         
534 544
         $numLine=1;
535
-        while (isset($snmptrans[$numLine]) && !preg_match('/^[\t ]+DESCRIPTION[\t ]+"(.*)/',$snmptrans[$numLine],$match)) $numLine++;
545
+        while (isset($snmptrans[$numLine]) && !preg_match('/^[\t ]+DESCRIPTION[\t ]+"(.*)/',$snmptrans[$numLine],$match)) {
546
+        	$numLine++;
547
+        }
536 548
         if (isset($snmptrans[$numLine]))
537 549
         {
538 550
             $snmptrans[$numLine] = preg_replace('/^[\t ]+DESCRIPTION[\t ]+"/','',$snmptrans[$numLine]);
@@ -636,7 +648,10 @@  discard block
 block discarded – undo
636 648
             $this->timing['num_traps']++;
637 649
             
638 650
             $this->logging->log('Found trap : '.$this->oidDesc['name'] . ' / OID : '.$this->oidDesc['oid'],INFO );
639
-            if ($display_progress) echo '#'; // echo a # when trap found
651
+            if ($display_progress) {
652
+            	echo '#';
653
+            }
654
+            // echo a # when trap found
640 655
 
641 656
             // get trap objects & source MIB
642 657
             
@@ -653,7 +668,9 @@  discard block
 block discarded – undo
653 668
             if (($update==0) && ($check_change===false))
654 669
             { // Trapd didn't change & force check disabled
655 670
                 $this->timing['objects_time'] += microtime(true) - $this->timing['base_time'];
656
-                if ($display_progress) echo "C";
671
+                if ($display_progress) {
672
+                	echo "C";
673
+                }
657 674
                 continue;
658 675
             }
659 676
             
Please login to merge, or discard this patch.
Indentation   +577 added lines, -577 removed lines patch added patch discarded remove patch
@@ -11,200 +11,200 @@  discard block
 block discarded – undo
11 11
 class Mib
12 12
 {
13 13
     
14
-    protected $logging; //< logging class
15
-    protected $trapsDB; //< Database class
14
+	protected $logging; //< logging class
15
+	protected $trapsDB; //< Database class
16 16
     
17
-    public $snmptranslate;
18
-    public $snmptranslateDirs;
17
+	public $snmptranslate;
18
+	public $snmptranslateDirs;
19 19
     
20
-    private $dbOidAll; //< All oid in database;
21
-    private $dbOidIndex; //< Index of oid in dbOidAll
22
-    private $objectsAll; //< output lines of snmptranslate list
23
-    private $trapObjectsIndex; //< array of traps objects (as OID)
20
+	private $dbOidAll; //< All oid in database;
21
+	private $dbOidIndex; //< Index of oid in dbOidAll
22
+	private $objectsAll; //< output lines of snmptranslate list
23
+	private $trapObjectsIndex; //< array of traps objects (as OID)
24 24
     
25
-    private $oidDesc=array(); //< $oid,$mib,$name,$type,$textConv,$dispHint,$syntax,$type_enum,$description=NULL
25
+	private $oidDesc=array(); //< $oid,$mib,$name,$type,$textConv,$dispHint,$syntax,$type_enum,$description=NULL
26 26
 
27
-    // Timing vars for update
28
-    private $timing=array();
27
+	// Timing vars for update
28
+	private $timing=array();
29 29
     
30
-    /**
31
-     * Setup Mib Class
32
-     * @param Logging $logClass : where to log
33
-     * @param Database $dbClass : Database
34
-     */
35
-    function __construct($logClass,$dbClass,$snmptrans,$snmptransdir)
36
-    {
37
-        $this->logging=$logClass;
38
-        $this->trapsDB=$dbClass;
39
-        $this->snmptranslate=$snmptrans;
40
-        $this->snmptranslateDirs=$snmptransdir;
30
+	/**
31
+	 * Setup Mib Class
32
+	 * @param Logging $logClass : where to log
33
+	 * @param Database $dbClass : Database
34
+	 */
35
+	function __construct($logClass,$dbClass,$snmptrans,$snmptransdir)
36
+	{
37
+		$this->logging=$logClass;
38
+		$this->trapsDB=$dbClass;
39
+		$this->snmptranslate=$snmptrans;
40
+		$this->snmptranslateDirs=$snmptransdir;
41 41
 
42
-    }
42
+	}
43 43
     
44
-    /**
45
-     * Update object in DB with object in dbOidIndex if name/mib/type has changed.
46
-     * @return number : 0=unchanged, 1 = changed, 2=created
47
-     */
48
-    private function update_oid_update()
49
-    {
44
+	/**
45
+	 * Update object in DB with object in dbOidIndex if name/mib/type has changed.
46
+	 * @return number : 0=unchanged, 1 = changed, 2=created
47
+	 */
48
+	private function update_oid_update()
49
+	{
50 50
         
51
-        $db_conn=$this->trapsDB->db_connect_trap();
51
+		$db_conn=$this->trapsDB->db_connect_trap();
52 52
         
53
-        if ($this->dbOidIndex[$this->oidDesc['oid']]['key'] == -1)
54
-        { // newly created.
55
-            return 0;
56
-        }
57
-        $oidIndex=$this->dbOidIndex[$this->oidDesc['oid']]['key']; // Get index in dbOidAll
58
-        $dbOid=$this->dbOidAll[$oidIndex]; // Get array of element
59
-        if ( $this->oidDesc['name'] != $dbOid['name'] ||
60
-            $this->oidDesc['mib'] != $dbOid['mib'] ||
61
-            $this->oidDesc['type'] !=$dbOid['type']
62
-            )
63
-        { // Do update
64
-            $sql='UPDATE '.$this->trapsDB->dbPrefix.'mib_cache SET '.
65
-                'name = :name , type = :type , mib = :mib , textual_convention = :tc , display_hint = :display_hint'.
66
-                ', syntax = :syntax, type_enum = :type_enum, description = :description '.
67
-                ' WHERE id= :id';
68
-            $sqlQuery=$db_conn->prepare($sql);
53
+		if ($this->dbOidIndex[$this->oidDesc['oid']]['key'] == -1)
54
+		{ // newly created.
55
+			return 0;
56
+		}
57
+		$oidIndex=$this->dbOidIndex[$this->oidDesc['oid']]['key']; // Get index in dbOidAll
58
+		$dbOid=$this->dbOidAll[$oidIndex]; // Get array of element
59
+		if ( $this->oidDesc['name'] != $dbOid['name'] ||
60
+			$this->oidDesc['mib'] != $dbOid['mib'] ||
61
+			$this->oidDesc['type'] !=$dbOid['type']
62
+			)
63
+		{ // Do update
64
+			$sql='UPDATE '.$this->trapsDB->dbPrefix.'mib_cache SET '.
65
+				'name = :name , type = :type , mib = :mib , textual_convention = :tc , display_hint = :display_hint'.
66
+				', syntax = :syntax, type_enum = :type_enum, description = :description '.
67
+				' WHERE id= :id';
68
+			$sqlQuery=$db_conn->prepare($sql);
69 69
             
70
-            $sqlParam=array(
71
-                ':name' => $this->oidDesc['name'],
72
-                ':type' => $this->oidDesc['type'],
73
-                ':mib' => $this->oidDesc['mib'],
74
-                ':tc' =>  $this->oidDesc['textconv']??'null',
75
-                ':display_hint' => $this->oidDesc['dispHint']??'null' ,
76
-                ':syntax' => $this->oidDesc['syntax']==null??'null',
77
-                ':type_enum' => $this->oidDesc['type_enum']??'null',
78
-                ':description' => $this->oidDesc['description']??'null',
79
-                ':id' => $this->dbOidAll[$this->dbOidIndex[$this->oidDesc['oid']]['id']]
80
-            );
70
+			$sqlParam=array(
71
+				':name' => $this->oidDesc['name'],
72
+				':type' => $this->oidDesc['type'],
73
+				':mib' => $this->oidDesc['mib'],
74
+				':tc' =>  $this->oidDesc['textconv']??'null',
75
+				':display_hint' => $this->oidDesc['dispHint']??'null' ,
76
+				':syntax' => $this->oidDesc['syntax']==null??'null',
77
+				':type_enum' => $this->oidDesc['type_enum']??'null',
78
+				':description' => $this->oidDesc['description']??'null',
79
+				':id' => $this->dbOidAll[$this->dbOidIndex[$this->oidDesc['oid']]['id']]
80
+			);
81 81
             
82
-            if ($sqlQuery->execute($sqlParam) === false) {
83
-                $this->logging->log('Error in query : ' . $sql,ERROR,'');
84
-            }
85
-            $this->logging->log('Trap updated : '.$this->oidDesc['name'] . ' / OID : '.$this->oidDesc['oid'],DEBUG );
86
-            return 1;
87
-        }
88
-        else
89
-        {
90
-            $this->logging->log('Trap unchanged : '.$this->oidDesc['name'] . ' / OID : '.$this->oidDesc['oid'],DEBUG );
91
-            return 0;
92
-        }
93
-    }
82
+			if ($sqlQuery->execute($sqlParam) === false) {
83
+				$this->logging->log('Error in query : ' . $sql,ERROR,'');
84
+			}
85
+			$this->logging->log('Trap updated : '.$this->oidDesc['name'] . ' / OID : '.$this->oidDesc['oid'],DEBUG );
86
+			return 1;
87
+		}
88
+		else
89
+		{
90
+			$this->logging->log('Trap unchanged : '.$this->oidDesc['name'] . ' / OID : '.$this->oidDesc['oid'],DEBUG );
91
+			return 0;
92
+		}
93
+	}
94 94
 
95
-    /**
96
-     * Create object in DB with object in dbOidIndex
97
-     * @return number : 0=unchanged, 1 = changed, 2=created
98
-     */
99
-    private function update_oid_create()
100
-    {
101
-        // Insert data
95
+	/**
96
+	 * Create object in DB with object in dbOidIndex
97
+	 * @return number : 0=unchanged, 1 = changed, 2=created
98
+	 */
99
+	private function update_oid_create()
100
+	{
101
+		// Insert data
102 102
         
103
-        $db_conn=$this->trapsDB->db_connect_trap();
104
-        $sql='INSERT INTO '.$this->trapsDB->dbPrefix.'mib_cache '.
105
-            '(oid, name, type , mib, textual_convention, display_hint '.
106
-            ', syntax, type_enum , description ) ' .
107
-            'values (:oid, :name , :type ,:mib ,:tc , :display_hint'.
108
-            ', :syntax, :type_enum, :description )';
103
+		$db_conn=$this->trapsDB->db_connect_trap();
104
+		$sql='INSERT INTO '.$this->trapsDB->dbPrefix.'mib_cache '.
105
+			'(oid, name, type , mib, textual_convention, display_hint '.
106
+			', syntax, type_enum , description ) ' .
107
+			'values (:oid, :name , :type ,:mib ,:tc , :display_hint'.
108
+			', :syntax, :type_enum, :description )';
109 109
         
110
-        if ($this->trapsDB->trapDBType == 'pgsql') $sql .= 'RETURNING id';
110
+		if ($this->trapsDB->trapDBType == 'pgsql') $sql .= 'RETURNING id';
111 111
         
112
-        $sqlQuery=$db_conn->prepare($sql);
112
+		$sqlQuery=$db_conn->prepare($sql);
113 113
         
114
-        $sqlParam=array(
115
-            ':oid' => $this->oidDesc['oid'],
116
-            ':name' => $this->oidDesc['name'],
117
-            ':type' => $this->oidDesc['type'],
118
-            ':mib' => $this->oidDesc['mib'],
119
-            ':tc' =>  $this->oidDesc['textconv']??'null',
120
-            ':display_hint' => $this->oidDesc['dispHint']??'null',
121
-            ':syntax' => $this->oidDesc['syntax']??'null',
122
-            ':type_enum' => $this->oidDesc['type_enum']??'null',
123
-            ':description' => $this->oidDesc['description']??'null'
124
-        );
114
+		$sqlParam=array(
115
+			':oid' => $this->oidDesc['oid'],
116
+			':name' => $this->oidDesc['name'],
117
+			':type' => $this->oidDesc['type'],
118
+			':mib' => $this->oidDesc['mib'],
119
+			':tc' =>  $this->oidDesc['textconv']??'null',
120
+			':display_hint' => $this->oidDesc['dispHint']??'null',
121
+			':syntax' => $this->oidDesc['syntax']??'null',
122
+			':type_enum' => $this->oidDesc['type_enum']??'null',
123
+			':description' => $this->oidDesc['description']??'null'
124
+		);
125 125
         
126
-        if ($sqlQuery->execute($sqlParam) === false) {
127
-            $this->logging->log('Error in query : ' . $sql,1,'');
128
-        }
126
+		if ($sqlQuery->execute($sqlParam) === false) {
127
+			$this->logging->log('Error in query : ' . $sql,1,'');
128
+		}
129 129
         
130
-        switch ($this->trapsDB->trapDBType)
131
-        {
132
-            case 'pgsql':
133
-                // Get last id to insert oid/values in secondary table
134
-                if (($inserted_id_ret=$sqlQuery->fetch(PDO::FETCH_ASSOC)) === false) {
135
-                    $this->logging->log('Error getting id - pgsql - ',1,'');
136
-                }
137
-                if (! isset($inserted_id_ret['id'])) {
138
-                    $this->logging->log('Error getting id - pgsql - empty.',ERROR);
139
-                    return 0;
140
-                }
141
-                $this->dbOidIndex[$this->oidDesc['oid']]['id']=$inserted_id_ret['id'];
142
-                break;
143
-            case 'mysql':
144
-                // Get last id to insert oid/values in secondary table
145
-                $sql='SELECT LAST_INSERT_ID();';
146
-                if (($ret_code=$db_conn->query($sql)) === false) {
147
-                    $this->logging->log('Erreur getting id - mysql - ',ERROR);
148
-                    return 0;
149
-                }
130
+		switch ($this->trapsDB->trapDBType)
131
+		{
132
+			case 'pgsql':
133
+				// Get last id to insert oid/values in secondary table
134
+				if (($inserted_id_ret=$sqlQuery->fetch(PDO::FETCH_ASSOC)) === false) {
135
+					$this->logging->log('Error getting id - pgsql - ',1,'');
136
+				}
137
+				if (! isset($inserted_id_ret['id'])) {
138
+					$this->logging->log('Error getting id - pgsql - empty.',ERROR);
139
+					return 0;
140
+				}
141
+				$this->dbOidIndex[$this->oidDesc['oid']]['id']=$inserted_id_ret['id'];
142
+				break;
143
+			case 'mysql':
144
+				// Get last id to insert oid/values in secondary table
145
+				$sql='SELECT LAST_INSERT_ID();';
146
+				if (($ret_code=$db_conn->query($sql)) === false) {
147
+					$this->logging->log('Erreur getting id - mysql - ',ERROR);
148
+					return 0;
149
+				}
150 150
                 
151
-                $inserted_id=$ret_code->fetch(PDO::FETCH_ASSOC)['LAST_INSERT_ID()'];
152
-                if ($inserted_id==false) throw new Exception("Weird SQL error : last_insert_id returned false : open issue");
153
-                $this->dbOidIndex[$this->oidDesc['oid']]['id']=$inserted_id;
154
-                break;
155
-            default:
156
-                $this->logging->log('Error SQL type Unknown : '.$this->trapsDB->trapDBType,ERROR);
157
-                return 0;
158
-        }
151
+				$inserted_id=$ret_code->fetch(PDO::FETCH_ASSOC)['LAST_INSERT_ID()'];
152
+				if ($inserted_id==false) throw new Exception("Weird SQL error : last_insert_id returned false : open issue");
153
+				$this->dbOidIndex[$this->oidDesc['oid']]['id']=$inserted_id;
154
+				break;
155
+			default:
156
+				$this->logging->log('Error SQL type Unknown : '.$this->trapsDB->trapDBType,ERROR);
157
+				return 0;
158
+		}
159 159
         
160
-        // Set as newly created.
161
-        $this->dbOidIndex[$this->oidDesc['oid']]['key']=-1;
162
-        return 2;
163
-    }
160
+		// Set as newly created.
161
+		$this->dbOidIndex[$this->oidDesc['oid']]['key']=-1;
162
+		return 2;
163
+	}
164 164
     
165
-    /**
166
-     * Update or add an OID to database uses $this->dbOidIndex for mem cache
167
-     * and $this->oidDesc doe data
168
-     * @return number : 0=unchanged, 1 = changed, 2=created
169
-     */
170
-    public function update_oid()
171
-    {
172
-        $db_conn=$this->trapsDB->db_connect_trap();
173
-        // Quote description.
174
-        $this->oidDesc['description']=$db_conn->quote($this->oidDesc['description']);
165
+	/**
166
+	 * Update or add an OID to database uses $this->dbOidIndex for mem cache
167
+	 * and $this->oidDesc doe data
168
+	 * @return number : 0=unchanged, 1 = changed, 2=created
169
+	 */
170
+	public function update_oid()
171
+	{
172
+		$db_conn=$this->trapsDB->db_connect_trap();
173
+		// Quote description.
174
+		$this->oidDesc['description']=$db_conn->quote($this->oidDesc['description']);
175 175
         
176
-        if (isset($this->dbOidIndex[$this->oidDesc['oid']]))
177
-        { // oid exists in db, so update
178
-            return $this->update_oid_update();
179
-        }
180
-        // create new OID.
181
-        return $this->update_oid_create();
176
+		if (isset($this->dbOidIndex[$this->oidDesc['oid']]))
177
+		{ // oid exists in db, so update
178
+			return $this->update_oid_update();
179
+		}
180
+		// create new OID.
181
+		return $this->update_oid_create();
182 182
 
183
-    }
183
+	}
184 184
     
185 185
 /**
186 186
  * get all objects for a trap.
187 187
  * @param integer $trapId
188 188
  * @return array : array of cached objects
189 189
  */    
190
-    private function cache_db_objects($trapId)
191
-    {
192
-        $dbObjects=array(); // cache of objects for trap in db
193
-        $db_conn=$this->trapsDB->db_connect_trap();
194
-        // Get all objects
195
-        $sql='SELECT * FROM '.$this->trapsDB->dbPrefix.'mib_cache_trap_object where trap_id='.$trapId.';';
196
-        $this->logging->log('SQL query get all traps: '.$sql,DEBUG );
197
-        if (($ret_code=$db_conn->query($sql)) === false) {
198
-            $this->logging->log('No result in query : ' . $sql,1,'');
199
-        }
200
-        $dbObjectsRaw=$ret_code->fetchAll();
190
+	private function cache_db_objects($trapId)
191
+	{
192
+		$dbObjects=array(); // cache of objects for trap in db
193
+		$db_conn=$this->trapsDB->db_connect_trap();
194
+		// Get all objects
195
+		$sql='SELECT * FROM '.$this->trapsDB->dbPrefix.'mib_cache_trap_object where trap_id='.$trapId.';';
196
+		$this->logging->log('SQL query get all traps: '.$sql,DEBUG );
197
+		if (($ret_code=$db_conn->query($sql)) === false) {
198
+			$this->logging->log('No result in query : ' . $sql,1,'');
199
+		}
200
+		$dbObjectsRaw=$ret_code->fetchAll();
201 201
         
202
-        foreach ($dbObjectsRaw as $val)
203
-        {
204
-            $dbObjects[$val['object_id']]=1;
205
-        }
206
-        return $dbObjects;
207
-    }
202
+		foreach ($dbObjectsRaw as $val)
203
+		{
204
+			$dbObjects[$val['object_id']]=1;
205
+		}
206
+		return $dbObjects;
207
+	}
208 208
 
209 209
 /**
210 210
  * Get object details & mib , returns snmptranslate output
@@ -212,478 +212,478 @@  discard block
 block discarded – undo
212 212
  * @param string $trapmib : mib of trap
213 213
  * @return NULL|array : null if not found, or output of snmptranslate
214 214
  */
215
-    private function get_object_details($object,$trapmib)
216
-    {
217
-        $match=$snmptrans=array();
218
-        $retVal=0;
219
-        $this->oidDesc['mib']=$trapmib;
220
-        exec($this->snmptranslate . ' -m ALL -M +'.$this->snmptranslateDirs.
221
-            ' -On -Td '.$this->oidDesc['mib'].'::'.$object . ' 2>/dev/null',$snmptrans,$retVal);
222
-        if ($retVal!=0)
223
-        {
224
-            // Maybe not trap mib, search with IR
225
-            exec($this->snmptranslate . ' -m ALL -M +'.$this->snmptranslateDirs.
226
-                ' -IR '.$object . ' 2>/dev/null',$snmptrans,$retVal);
227
-            if ($retVal != 0 || !preg_match('/(.*)::(.*)/',$snmptrans[0],$match))
228
-            { // Not found -> continue with warning
229
-                $this->logging->log('Error finding trap object : '.$trapmib.'::'.$object,2,'');
230
-                return null;
231
-            }
232
-            $this->oidDesc['mib']=$match[1];
215
+	private function get_object_details($object,$trapmib)
216
+	{
217
+		$match=$snmptrans=array();
218
+		$retVal=0;
219
+		$this->oidDesc['mib']=$trapmib;
220
+		exec($this->snmptranslate . ' -m ALL -M +'.$this->snmptranslateDirs.
221
+			' -On -Td '.$this->oidDesc['mib'].'::'.$object . ' 2>/dev/null',$snmptrans,$retVal);
222
+		if ($retVal!=0)
223
+		{
224
+			// Maybe not trap mib, search with IR
225
+			exec($this->snmptranslate . ' -m ALL -M +'.$this->snmptranslateDirs.
226
+				' -IR '.$object . ' 2>/dev/null',$snmptrans,$retVal);
227
+			if ($retVal != 0 || !preg_match('/(.*)::(.*)/',$snmptrans[0],$match))
228
+			{ // Not found -> continue with warning
229
+				$this->logging->log('Error finding trap object : '.$trapmib.'::'.$object,2,'');
230
+				return null;
231
+			}
232
+			$this->oidDesc['mib']=$match[1];
233 233
             
234
-            // Do the snmptranslate again.
235
-            exec($this->snmptranslate . ' -m ALL -M +'.$this->snmptranslateDirs.
236
-                ' -On -Td '.$this->oidDesc['mib'].'::'.$object,$snmptrans,$retVal);
237
-            if ($retVal!=0) {
238
-                $this->logging->log('Error finding trap object : '.$this->oidDesc['mib'].'::'.$object,2,'');
239
-                return null;
240
-            }
234
+			// Do the snmptranslate again.
235
+			exec($this->snmptranslate . ' -m ALL -M +'.$this->snmptranslateDirs.
236
+				' -On -Td '.$this->oidDesc['mib'].'::'.$object,$snmptrans,$retVal);
237
+			if ($retVal!=0) {
238
+				$this->logging->log('Error finding trap object : '.$this->oidDesc['mib'].'::'.$object,2,'');
239
+				return null;
240
+			}
241 241
             
242
-        }
243
-        return $snmptrans;
244
-    }
242
+		}
243
+		return $snmptrans;
244
+	}
245 245
 
246 246
 /**
247 247
  * Parse snmptranslate output and set  $this->oidDesc with elements 
248 248
  * @param array $snmptrans : multi line output of snmptrans
249 249
  */
250
-    private function parse_object($snmptrans)
251
-    {
252
-        $tmpdesc=''; // For multiline description
253
-        $indesc=false; // true if currently inside multiline description
254
-        $match=array();
250
+	private function parse_object($snmptrans)
251
+	{
252
+		$tmpdesc=''; // For multiline description
253
+		$indesc=false; // true if currently inside multiline description
254
+		$match=array();
255 255
         
256
-        foreach ($snmptrans as $line)
257
-        {
258
-            if ($indesc===true)
259
-            {
260
-                $line=preg_replace('/[\t ]+/',' ',$line);
261
-                if (preg_match('/(.*)"$/', $line,$match))
262
-                {
263
-                    $this->oidDesc['description'] = $tmpdesc . $match[1];
264
-                    $indesc=false;
265
-                }
266
-                $tmpdesc.=$line;
267
-                continue;
268
-            }
269
-            if (preg_match('/^\.[0-9\.]+$/', $line))
270
-            {
271
-                $this->oidDesc['oid']=$line;
272
-                continue;
273
-            }
274
-            if (preg_match('/^[\t ]+SYNTAX[\t ]+([^{]*) \{(.*)\}/',$line,$match))
275
-            {
276
-                $this->oidDesc['syntax']=$match[1];
277
-                $this->oidDesc['type_enum']=$match[2];
278
-                continue;
279
-            }
280
-            if (preg_match('/^[\t ]+SYNTAX[\t ]+(.*)/',$line,$match))
281
-            {
282
-                $this->oidDesc['syntax']=$match[1];
283
-                continue;
284
-            }
285
-            if (preg_match('/^[\t ]+DISPLAY-HINT[\t ]+"(.*)"/',$line,$match))
286
-            {
287
-                $this->oidDesc['dispHint']=$match[1];
288
-                continue;
289
-            }
290
-            if (preg_match('/^[\t ]+DESCRIPTION[\t ]+"(.*)"/',$line,$match))
291
-            {
292
-                $this->oidDesc['description']=$match[1];
293
-                continue;
294
-            }
295
-            if (preg_match('/^[\t ]+DESCRIPTION[\t ]+"(.*)/',$line,$match))
296
-            {
297
-                $tmpdesc=$match[1];
298
-                $indesc=true;
299
-                continue;
300
-            }
301
-            if (preg_match('/^[\t ]+-- TEXTUAL CONVENTION[\t ]+(.*)/',$line,$match))
302
-            {
303
-                $this->oidDesc['textconv']=$match[1];
304
-                continue;
305
-            }
306
-        }
307
-    }
256
+		foreach ($snmptrans as $line)
257
+		{
258
+			if ($indesc===true)
259
+			{
260
+				$line=preg_replace('/[\t ]+/',' ',$line);
261
+				if (preg_match('/(.*)"$/', $line,$match))
262
+				{
263
+					$this->oidDesc['description'] = $tmpdesc . $match[1];
264
+					$indesc=false;
265
+				}
266
+				$tmpdesc.=$line;
267
+				continue;
268
+			}
269
+			if (preg_match('/^\.[0-9\.]+$/', $line))
270
+			{
271
+				$this->oidDesc['oid']=$line;
272
+				continue;
273
+			}
274
+			if (preg_match('/^[\t ]+SYNTAX[\t ]+([^{]*) \{(.*)\}/',$line,$match))
275
+			{
276
+				$this->oidDesc['syntax']=$match[1];
277
+				$this->oidDesc['type_enum']=$match[2];
278
+				continue;
279
+			}
280
+			if (preg_match('/^[\t ]+SYNTAX[\t ]+(.*)/',$line,$match))
281
+			{
282
+				$this->oidDesc['syntax']=$match[1];
283
+				continue;
284
+			}
285
+			if (preg_match('/^[\t ]+DISPLAY-HINT[\t ]+"(.*)"/',$line,$match))
286
+			{
287
+				$this->oidDesc['dispHint']=$match[1];
288
+				continue;
289
+			}
290
+			if (preg_match('/^[\t ]+DESCRIPTION[\t ]+"(.*)"/',$line,$match))
291
+			{
292
+				$this->oidDesc['description']=$match[1];
293
+				continue;
294
+			}
295
+			if (preg_match('/^[\t ]+DESCRIPTION[\t ]+"(.*)/',$line,$match))
296
+			{
297
+				$tmpdesc=$match[1];
298
+				$indesc=true;
299
+				continue;
300
+			}
301
+			if (preg_match('/^[\t ]+-- TEXTUAL CONVENTION[\t ]+(.*)/',$line,$match))
302
+			{
303
+				$this->oidDesc['textconv']=$match[1];
304
+				continue;
305
+			}
306
+		}
307
+	}
308 308
 
309
-    /**
310
-     * create or update (with check_existing = true) objects of trap
311
-     * @param string $trapOID : trap oid
312
-     * @param string $trapmib : mib of trap
313
-     * @param array $objects : array of objects name (without MIB)
314
-     * @param bool $check_existing : check instead of create
315
-     */
316
-    public function trap_objects($trapOID,$trapmib,$objects,$check_existing)
317
-    {              
318
-        $trapId = $this->dbOidIndex[$trapOID]['id']; // Get id of trap
309
+	/**
310
+	 * create or update (with check_existing = true) objects of trap
311
+	 * @param string $trapOID : trap oid
312
+	 * @param string $trapmib : mib of trap
313
+	 * @param array $objects : array of objects name (without MIB)
314
+	 * @param bool $check_existing : check instead of create
315
+	 */
316
+	public function trap_objects($trapOID,$trapmib,$objects,$check_existing)
317
+	{              
318
+		$trapId = $this->dbOidIndex[$trapOID]['id']; // Get id of trap
319 319
         
320
-        if ($check_existing === true)
321
-        {
322
-            $dbObjects=$this->cache_db_objects($trapId);
323
-        }
320
+		if ($check_existing === true)
321
+		{
322
+			$dbObjects=$this->cache_db_objects($trapId);
323
+		}
324 324
         
325
-        foreach ($objects as $object)
326
-        {
325
+		foreach ($objects as $object)
326
+		{
327 327
             
328
-            $this->reset_oidDesc();
328
+			$this->reset_oidDesc();
329 329
             
330
-            $snmptrans=$this->get_object_details($object, $trapmib); // Get object mib & details
331
-            if ($snmptrans === null) continue; // object not found
330
+			$snmptrans=$this->get_object_details($object, $trapmib); // Get object mib & details
331
+			if ($snmptrans === null) continue; // object not found
332 332
             
333
-            $this->parse_object($snmptrans);
333
+			$this->parse_object($snmptrans);
334 334
 
335
-            $this->oidDesc['name'] = $object;
335
+			$this->oidDesc['name'] = $object;
336 336
             
337
-            $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 );
337
+			$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 );
338 338
 
339
-            // Update
340
-            $this->update_oid();
339
+			// Update
340
+			$this->update_oid();
341 341
             
342
-            if (isset($dbObjects[$this->dbOidIndex[$this->oidDesc['oid']]['id']]))
343
-            {   // if link exists, continue
344
-                $dbObjects[$this->dbOidIndex[$this->oidDesc['oid']]['id']]=2;
345
-                continue;
346
-            }
347
-            if ($check_existing === true)
348
-            {
349
-                // TODO : check link trap - objects exists, mark them.
350
-            }
351
-            // Associate in object table
352
-            $db_conn=$this->trapsDB->db_connect_trap();
353
-            $sql='INSERT INTO '.$this->trapsDB->dbPrefix.'mib_cache_trap_object (trap_id,object_id) '.
354
-                'values (:trap_id, :object_id)';
355
-            $sqlQuery=$db_conn->prepare($sql);
356
-            $sqlParam=array(
357
-                ':trap_id' => $trapId,
358
-                ':object_id' => $this->dbOidIndex[$this->oidDesc['oid']]['id'],
359
-            );
342
+			if (isset($dbObjects[$this->dbOidIndex[$this->oidDesc['oid']]['id']]))
343
+			{   // if link exists, continue
344
+				$dbObjects[$this->dbOidIndex[$this->oidDesc['oid']]['id']]=2;
345
+				continue;
346
+			}
347
+			if ($check_existing === true)
348
+			{
349
+				// TODO : check link trap - objects exists, mark them.
350
+			}
351
+			// Associate in object table
352
+			$db_conn=$this->trapsDB->db_connect_trap();
353
+			$sql='INSERT INTO '.$this->trapsDB->dbPrefix.'mib_cache_trap_object (trap_id,object_id) '.
354
+				'values (:trap_id, :object_id)';
355
+			$sqlQuery=$db_conn->prepare($sql);
356
+			$sqlParam=array(
357
+				':trap_id' => $trapId,
358
+				':object_id' => $this->dbOidIndex[$this->oidDesc['oid']]['id'],
359
+			);
360 360
             
361
-            if ($sqlQuery->execute($sqlParam) === false) {
362
-                $this->logging->log('Error adding trap object : ' . $sql . ' / ' . $trapId . '/'. $this->dbOidIndex[$this->oidDesc['oid']]['id'] ,1,'');
363
-            }
364
-        }
365
-        if ($check_existing === true)
366
-        {
367
-            // TODO : remove link trap - objects that wasn't marked.
368
-        }
361
+			if ($sqlQuery->execute($sqlParam) === false) {
362
+				$this->logging->log('Error adding trap object : ' . $sql . ' / ' . $trapId . '/'. $this->dbOidIndex[$this->oidDesc['oid']]['id'] ,1,'');
363
+			}
364
+		}
365
+		if ($check_existing === true)
366
+		{
367
+			// TODO : remove link trap - objects that wasn't marked.
368
+		}
369 369
         
370
-    }
370
+	}
371 371
 
372
-    private function reset_oidDesc()
373
-    {
374
-        $this->oidDesc['oid']=null;
375
-        $this->oidDesc['name']=null;
376
-        $this->oidDesc['type']=null;
377
-        $this->oidDesc['mib']=null;
378
-        $this->oidDesc['textconv']=null;
379
-        $this->oidDesc['dispHint'] =null;
380
-        $this->oidDesc['syntax']=null;
381
-        $this->oidDesc['type_enum']=null;
382
-        $this->oidDesc['description']=null;
383
-    }
372
+	private function reset_oidDesc()
373
+	{
374
+		$this->oidDesc['oid']=null;
375
+		$this->oidDesc['name']=null;
376
+		$this->oidDesc['type']=null;
377
+		$this->oidDesc['mib']=null;
378
+		$this->oidDesc['textconv']=null;
379
+		$this->oidDesc['dispHint'] =null;
380
+		$this->oidDesc['syntax']=null;
381
+		$this->oidDesc['type_enum']=null;
382
+		$this->oidDesc['description']=null;
383
+	}
384 384
     
385
-    /**
386
-     * Fills $this->objectsAll with all mibs from snmptranslate
387
-     * @return integer : number of elements 
388
-     */
389
-    private function load_mibs_snmptranslate()
390
-    {
391
-        $retVal=0;
392
-        // Get all mib objects from all mibs
393
-        $snmpCommand=$this->snmptranslate . ' -m ALL -M +'.$this->snmptranslateDirs.' -On -Tto 2>/dev/null';
394
-        $this->logging->log('Getting all traps : '.$snmpCommand,DEBUG );
395
-        unset($this->objectsAll);
396
-        exec($snmpCommand,$this->objectsAll,$retVal);
397
-        if ($retVal!=0)
398
-        {
399
-            $this->logging->log('error executing snmptranslate',ERROR,'');
400
-        }
401
-        // Count elements to show progress
402
-        $numElements=count($this->objectsAll);
403
-        $this->logging->log('Total snmp objects returned by snmptranslate : '.$numElements,INFO );
404
-        return $numElements;
405
-    }
385
+	/**
386
+	 * Fills $this->objectsAll with all mibs from snmptranslate
387
+	 * @return integer : number of elements 
388
+	 */
389
+	private function load_mibs_snmptranslate()
390
+	{
391
+		$retVal=0;
392
+		// Get all mib objects from all mibs
393
+		$snmpCommand=$this->snmptranslate . ' -m ALL -M +'.$this->snmptranslateDirs.' -On -Tto 2>/dev/null';
394
+		$this->logging->log('Getting all traps : '.$snmpCommand,DEBUG );
395
+		unset($this->objectsAll);
396
+		exec($snmpCommand,$this->objectsAll,$retVal);
397
+		if ($retVal!=0)
398
+		{
399
+			$this->logging->log('error executing snmptranslate',ERROR,'');
400
+		}
401
+		// Count elements to show progress
402
+		$numElements=count($this->objectsAll);
403
+		$this->logging->log('Total snmp objects returned by snmptranslate : '.$numElements,INFO );
404
+		return $numElements;
405
+	}
406 406
 
407
-    /**
408
-     * load all mib objects db in dbOidAll (raw) and index in dbOidIndex
409
-     */
410
-    private function load_mibs_from_db()
411
-    {
412
-        // Get all mibs from databse to have a memory index
407
+	/**
408
+	 * load all mib objects db in dbOidAll (raw) and index in dbOidIndex
409
+	 */
410
+	private function load_mibs_from_db()
411
+	{
412
+		// Get all mibs from databse to have a memory index
413 413
         
414
-        $db_conn=$this->trapsDB->db_connect_trap();
414
+		$db_conn=$this->trapsDB->db_connect_trap();
415 415
         
416
-        $sql='SELECT * from '.$this->trapsDB->dbPrefix.'mib_cache;';
417
-        $this->logging->log('SQL query : '.$sql,DEBUG );
418
-        if (($ret_code=$db_conn->query($sql)) === false) {
419
-            $this->logging->log('No result in query : ' . $sql,ERROR,'');
420
-        }
421
-        $this->dbOidAll=$ret_code->fetchAll();
422
-        $this->dbOidIndex=array();
423
-        // Create the index for db;
424
-        foreach($this->dbOidAll as $key=>$val)
425
-        {
426
-            $this->dbOidIndex[$val['oid']]['key']=$key;
427
-            $this->dbOidIndex[$val['oid']]['id']=$val['id'];
428
-        }
429
-    }
416
+		$sql='SELECT * from '.$this->trapsDB->dbPrefix.'mib_cache;';
417
+		$this->logging->log('SQL query : '.$sql,DEBUG );
418
+		if (($ret_code=$db_conn->query($sql)) === false) {
419
+			$this->logging->log('No result in query : ' . $sql,ERROR,'');
420
+		}
421
+		$this->dbOidAll=$ret_code->fetchAll();
422
+		$this->dbOidIndex=array();
423
+		// Create the index for db;
424
+		foreach($this->dbOidAll as $key=>$val)
425
+		{
426
+			$this->dbOidIndex[$val['oid']]['key']=$key;
427
+			$this->dbOidIndex[$val['oid']]['id']=$val['id'];
428
+		}
429
+	}
430 430
 
431
-    /**
432
-     * Reset all update timers & count to zero
433
-     */
434
-    private function reset_update_timers()
435
-    {
436
-        $this->timing['base_parse_time']=0;
437
-        $this->timing['base_check_time']=0;
438
-        $this->timing['type0_check_time']=0;
439
-        $this->timing['nottrap_time']=0;
440
-        $this->timing['update_time']=0;
441
-        $this->timing['objects_time']=0;
442
-        $this->timing['base_parse_num']=0;
443
-        $this->timing['base_check_num']=0;
444
-        $this->timing['type0_check_num']=0;
445
-        $this->timing['nottrap_num']=0;
446
-        $this->timing['update_num']=0;
447
-        $this->timing['objects_num']=0;
448
-        $this->timing['num_traps']=0;
449
-    }
431
+	/**
432
+	 * Reset all update timers & count to zero
433
+	 */
434
+	private function reset_update_timers()
435
+	{
436
+		$this->timing['base_parse_time']=0;
437
+		$this->timing['base_check_time']=0;
438
+		$this->timing['type0_check_time']=0;
439
+		$this->timing['nottrap_time']=0;
440
+		$this->timing['update_time']=0;
441
+		$this->timing['objects_time']=0;
442
+		$this->timing['base_parse_num']=0;
443
+		$this->timing['base_check_num']=0;
444
+		$this->timing['type0_check_num']=0;
445
+		$this->timing['nottrap_num']=0;
446
+		$this->timing['update_num']=0;
447
+		$this->timing['objects_num']=0;
448
+		$this->timing['num_traps']=0;
449
+	}
450 450
 
451
-    /**
452
-     * Detect if $this->objectsAll[$curElement] is a trap 
453
-     * @param integer $curElement
454
-     * @param bool $onlyTraps : set to false to get all and not only traps.
455
-     * @return boolean : false if it's a trap , true if not
456
-     */
457
-    private function detect_trap($curElement,$onlyTraps)
458
-    {
459
-        // Get oid or pass if not found
460
-        if (!preg_match('/^\.[0-9\.]+$/',$this->objectsAll[$curElement]))
461
-        {
462
-            $this->timing['base_parse_time'] += microtime(true) - $this->timing['base_time'];
463
-            $this->timing['base_parse_num'] ++;
464
-            return true;
465
-        }
466
-        $this->oidDesc['oid']=$this->objectsAll[$curElement];
451
+	/**
452
+	 * Detect if $this->objectsAll[$curElement] is a trap 
453
+	 * @param integer $curElement
454
+	 * @param bool $onlyTraps : set to false to get all and not only traps.
455
+	 * @return boolean : false if it's a trap , true if not
456
+	 */
457
+	private function detect_trap($curElement,$onlyTraps)
458
+	{
459
+		// Get oid or pass if not found
460
+		if (!preg_match('/^\.[0-9\.]+$/',$this->objectsAll[$curElement]))
461
+		{
462
+			$this->timing['base_parse_time'] += microtime(true) - $this->timing['base_time'];
463
+			$this->timing['base_parse_num'] ++;
464
+			return true;
465
+		}
466
+		$this->oidDesc['oid']=$this->objectsAll[$curElement];
467 467
         
468
-        // get next line
469
-        $curElement++;
470
-        $match=$snmptrans=array();
471
-        if (!preg_match('/ +([^\(]+)\(.+\) type=([0-9]+)( tc=([0-9]+))?( hint=(.+))?/',
472
-            $this->objectsAll[$curElement],$match))
473
-        {
474
-            $this->timing['base_check_time'] += microtime(true) - $this->timing['base_time'];
475
-            $this->timing['base_check_num']++;
476
-            return true;
477
-        }
468
+		// get next line
469
+		$curElement++;
470
+		$match=$snmptrans=array();
471
+		if (!preg_match('/ +([^\(]+)\(.+\) type=([0-9]+)( tc=([0-9]+))?( hint=(.+))?/',
472
+			$this->objectsAll[$curElement],$match))
473
+		{
474
+			$this->timing['base_check_time'] += microtime(true) - $this->timing['base_time'];
475
+			$this->timing['base_check_num']++;
476
+			return true;
477
+		}
478 478
         
479
-        $this->oidDesc['name']=$match[1]; // Name
480
-        $this->oidDesc['type']=$match[2]; // type (21=trap, 0: may be trap, else : not trap
479
+		$this->oidDesc['name']=$match[1]; // Name
480
+		$this->oidDesc['type']=$match[2]; // type (21=trap, 0: may be trap, else : not trap
481 481
         
482
-        if ($this->oidDesc['type']==0) // object type=0 : check if v1 trap
483
-        {
484
-            // Check if next is suboid -> in that case is cannot be a trap
485
-            if (preg_match("/^".$this->oidDesc['oid']."/",$this->objectsAll[$curElement+1]))
486
-            {
487
-                $this->timing['type0_check_time'] += microtime(true) - $this->timing['base_time'];
488
-                $this->timing['type0_check_num']++;
489
-                return true;
490
-            }
491
-            unset($snmptrans);
492
-            $retVal=0;
493
-            exec($this->snmptranslate . ' -m ALL -M +'.$this->snmptranslateDirs.
494
-                ' -Td '.$this->oidDesc['oid'] . ' | grep OBJECTS ',$snmptrans,$retVal);
495
-            if ($retVal!=0)
496
-            {
497
-                $this->timing['type0_check_time'] += microtime(true) - $this->timing['base_time'];
498
-                $this->timing['type0_check_num']++;
499
-                return true;
500
-            }
501
-            //echo "\n v1 trap found : $this->oidDesc['oid'] \n";
502
-            // Force as trap.
503
-            $this->oidDesc['type']=21;
504
-        }
505
-        if ($onlyTraps===true && $this->oidDesc['type']!=21) // if only traps and not a trap, continue
506
-        {
507
-            $this->timing['nottrap_time'] += microtime(true) - $this->timing['base_time'];
508
-            $this->timing['nottrap_num']++;
509
-            return true;
510
-        }
511
-        return false;
512
-    }
482
+		if ($this->oidDesc['type']==0) // object type=0 : check if v1 trap
483
+		{
484
+			// Check if next is suboid -> in that case is cannot be a trap
485
+			if (preg_match("/^".$this->oidDesc['oid']."/",$this->objectsAll[$curElement+1]))
486
+			{
487
+				$this->timing['type0_check_time'] += microtime(true) - $this->timing['base_time'];
488
+				$this->timing['type0_check_num']++;
489
+				return true;
490
+			}
491
+			unset($snmptrans);
492
+			$retVal=0;
493
+			exec($this->snmptranslate . ' -m ALL -M +'.$this->snmptranslateDirs.
494
+				' -Td '.$this->oidDesc['oid'] . ' | grep OBJECTS ',$snmptrans,$retVal);
495
+			if ($retVal!=0)
496
+			{
497
+				$this->timing['type0_check_time'] += microtime(true) - $this->timing['base_time'];
498
+				$this->timing['type0_check_num']++;
499
+				return true;
500
+			}
501
+			//echo "\n v1 trap found : $this->oidDesc['oid'] \n";
502
+			// Force as trap.
503
+			$this->oidDesc['type']=21;
504
+		}
505
+		if ($onlyTraps===true && $this->oidDesc['type']!=21) // if only traps and not a trap, continue
506
+		{
507
+			$this->timing['nottrap_time'] += microtime(true) - $this->timing['base_time'];
508
+			$this->timing['nottrap_num']++;
509
+			return true;
510
+		}
511
+		return false;
512
+	}
513 513
    
514
-    /**
515
-     * get_trap_mib_description
516
-     * @return array|null : array of snmptranslate output or null on error
517
-    **/
518
-    private function get_trap_mib_description()
519
-    {
520
-        $retVal=0;
521
-        $match=$snmptrans=array();
522
-        exec($this->snmptranslate . ' -m ALL -M +'.$this->snmptranslateDirs.
523
-            ' -Td '.$this->oidDesc['oid'],$snmptrans,$retVal);
524
-        if ($retVal!=0)
525
-        {
526
-            $this->logging->log('error executing snmptranslate',ERROR);
527
-            return $snmptrans;
528
-        }
514
+	/**
515
+	 * get_trap_mib_description
516
+	 * @return array|null : array of snmptranslate output or null on error
517
+	 **/
518
+	private function get_trap_mib_description()
519
+	{
520
+		$retVal=0;
521
+		$match=$snmptrans=array();
522
+		exec($this->snmptranslate . ' -m ALL -M +'.$this->snmptranslateDirs.
523
+			' -Td '.$this->oidDesc['oid'],$snmptrans,$retVal);
524
+		if ($retVal!=0)
525
+		{
526
+			$this->logging->log('error executing snmptranslate',ERROR);
527
+			return $snmptrans;
528
+		}
529 529
         
530
-        if (!preg_match('/^(.*)::/',$snmptrans[0],$match))
531
-        {
532
-            $this->logging->log('Error getting mib from trap '.$this->oidDesc['oid'].' : ' . $snmptrans[0],ERROR);
533
-            return $snmptrans;
534
-        }
535
-        $this->oidDesc['mib']=$match[1];
530
+		if (!preg_match('/^(.*)::/',$snmptrans[0],$match))
531
+		{
532
+			$this->logging->log('Error getting mib from trap '.$this->oidDesc['oid'].' : ' . $snmptrans[0],ERROR);
533
+			return $snmptrans;
534
+		}
535
+		$this->oidDesc['mib']=$match[1];
536 536
         
537
-        $numLine=1;
538
-        while (isset($snmptrans[$numLine]) && !preg_match('/^[\t ]+DESCRIPTION[\t ]+"(.*)/',$snmptrans[$numLine],$match)) $numLine++;
539
-        if (isset($snmptrans[$numLine]))
540
-        {
541
-            $snmptrans[$numLine] = preg_replace('/^[\t ]+DESCRIPTION[\t ]+"/','',$snmptrans[$numLine]);
537
+		$numLine=1;
538
+		while (isset($snmptrans[$numLine]) && !preg_match('/^[\t ]+DESCRIPTION[\t ]+"(.*)/',$snmptrans[$numLine],$match)) $numLine++;
539
+		if (isset($snmptrans[$numLine]))
540
+		{
541
+			$snmptrans[$numLine] = preg_replace('/^[\t ]+DESCRIPTION[\t ]+"/','',$snmptrans[$numLine]);
542 542
             
543
-            while (isset($snmptrans[$numLine]) && !preg_match('/"/',$snmptrans[$numLine]))
544
-            {
545
-                $this->oidDesc['description'].=preg_replace('/[\t ]+/',' ',$snmptrans[$numLine]);
546
-                $numLine++;
547
-            }
548
-            if (isset($snmptrans[$numLine])) {
549
-                $this->oidDesc['description'].=preg_replace('/".*/','',$snmptrans[$numLine]);
550
-                $this->oidDesc['description']=preg_replace('/[\t ]+/',' ',$this->oidDesc['description']);
551
-            }
543
+			while (isset($snmptrans[$numLine]) && !preg_match('/"/',$snmptrans[$numLine]))
544
+			{
545
+				$this->oidDesc['description'].=preg_replace('/[\t ]+/',' ',$snmptrans[$numLine]);
546
+				$numLine++;
547
+			}
548
+			if (isset($snmptrans[$numLine])) {
549
+				$this->oidDesc['description'].=preg_replace('/".*/','',$snmptrans[$numLine]);
550
+				$this->oidDesc['description']=preg_replace('/[\t ]+/',' ',$this->oidDesc['description']);
551
+			}
552 552
             
553
-        }
554
-        return $snmptrans;
555
-    }
553
+		}
554
+		return $snmptrans;
555
+	}
556 556
 
557
-    /**
558
-     * Get trap objects
559
-     * @param array $snmptrans : output of snmptranslate for TrapModuleConfig
560
-     * @return array|null : array of objects or null if not found
561
-    **/
562
-    private function get_trap_objects($snmptrans)
563
-    {
564
-        $objectName=null;
565
-        $match=array();
566
-        foreach ($snmptrans as $line)
567
-        {
568
-            if (preg_match('/OBJECTS.*\{([^\}]+)\}/',$line,$match))
569
-            {
570
-                $objectName=$match[1];
571
-            }
572
-        }
573
-        if ($objectName == null)
574
-        {
575
-            $this->logging->log('No objects for ' . $this->oidDesc['oid'],DEBUG);
576
-            $this->timing['objects_time'] += microtime(true) - $this->timing['base_time'];
577
-            return null;
578
-        }
557
+	/**
558
+	 * Get trap objects
559
+	 * @param array $snmptrans : output of snmptranslate for TrapModuleConfig
560
+	 * @return array|null : array of objects or null if not found
561
+	 **/
562
+	private function get_trap_objects($snmptrans)
563
+	{
564
+		$objectName=null;
565
+		$match=array();
566
+		foreach ($snmptrans as $line)
567
+		{
568
+			if (preg_match('/OBJECTS.*\{([^\}]+)\}/',$line,$match))
569
+			{
570
+				$objectName=$match[1];
571
+			}
572
+		}
573
+		if ($objectName == null)
574
+		{
575
+			$this->logging->log('No objects for ' . $this->oidDesc['oid'],DEBUG);
576
+			$this->timing['objects_time'] += microtime(true) - $this->timing['base_time'];
577
+			return null;
578
+		}
579 579
         
580
-        $trapObjects=array();
581
-        while (preg_match('/ *([^ ,]+) *,* */',$objectName,$match))
582
-        {
583
-            array_push($trapObjects,$match[1]);
584
-            $objectName=preg_replace('/'.$match[0].'/','',$objectName);
585
-        }
586
-        return $trapObjects;
587
-    }
580
+		$trapObjects=array();
581
+		while (preg_match('/ *([^ ,]+) *,* */',$objectName,$match))
582
+		{
583
+			array_push($trapObjects,$match[1]);
584
+			$objectName=preg_replace('/'.$match[0].'/','',$objectName);
585
+		}
586
+		return $trapObjects;
587
+	}
588 588
     
589
-    /**
590
-     * Cache mib in database
591
-     * @param boolean $display_progress : Display progress on standard output
592
-     * @param boolean $check_change : Force check of trap params & objects
593
-     * @param boolean $onlyTraps : only cache traps and objects (true) or all (false)
594
-     * @param string $startOID : only cache under startOID (NOT IMPLEMENTED)
595
-     */
596
-    public function update_mib_database($display_progress=false,$check_change=false,$onlyTraps=true,$startOID='.1')
597
-    {
598
-        // Global Timing
599
-        $timeTaken = microtime(true);
589
+	/**
590
+	 * Cache mib in database
591
+	 * @param boolean $display_progress : Display progress on standard output
592
+	 * @param boolean $check_change : Force check of trap params & objects
593
+	 * @param boolean $onlyTraps : only cache traps and objects (true) or all (false)
594
+	 * @param string $startOID : only cache under startOID (NOT IMPLEMENTED)
595
+	 */
596
+	public function update_mib_database($display_progress=false,$check_change=false,$onlyTraps=true,$startOID='.1')
597
+	{
598
+		// Global Timing
599
+		$timeTaken = microtime(true);
600 600
         
601
-        $numElements=$this->load_mibs_snmptranslate(); // Load objectsAll
601
+		$numElements=$this->load_mibs_snmptranslate(); // Load objectsAll
602 602
         
603
-        $this->load_mibs_from_db(); // Load from db dbOidAll & dbOidIndex
603
+		$this->load_mibs_from_db(); // Load from db dbOidAll & dbOidIndex
604 604
         
605
-        $step=$basestep=$numElements/10; // output display of % done
606
-        $num_step=0;
607
-        $timeFiveSec = microtime(true); // Used for display a '.' every <n> seconds
605
+		$step=$basestep=$numElements/10; // output display of % done
606
+		$num_step=0;
607
+		$timeFiveSec = microtime(true); // Used for display a '.' every <n> seconds
608 608
         
609
-        // Create index for trap objects
610
-        $this->trapObjectsIndex=array();
609
+		// Create index for trap objects
610
+		$this->trapObjectsIndex=array();
611 611
         
612
-        // detailed timing (time_* vars)
613
-        $this->reset_update_timers();
612
+		// detailed timing (time_* vars)
613
+		$this->reset_update_timers();
614 614
         
615
-        for ($curElement=0;$curElement < $numElements;$curElement++)
616
-        {
617
-            $this->timing['base_time']= microtime(true);
618
-            if ($display_progress)
619
-            {
620
-                if ((microtime(true)-$timeFiveSec) > 2)
621
-                { // echo a . every 2 sec
622
-                    echo '.';
623
-                    $timeFiveSec = microtime(true);
624
-                }
625
-                if ($curElement>$step)
626
-                { // display progress
627
-                    $num_step++;
628
-                    $step+=$basestep;   
629
-                    echo "\n" . ($num_step*10). '% : ';
630
-                }
631
-            }
615
+		for ($curElement=0;$curElement < $numElements;$curElement++)
616
+		{
617
+			$this->timing['base_time']= microtime(true);
618
+			if ($display_progress)
619
+			{
620
+				if ((microtime(true)-$timeFiveSec) > 2)
621
+				{ // echo a . every 2 sec
622
+					echo '.';
623
+					$timeFiveSec = microtime(true);
624
+				}
625
+				if ($curElement>$step)
626
+				{ // display progress
627
+					$num_step++;
628
+					$step+=$basestep;   
629
+					echo "\n" . ($num_step*10). '% : ';
630
+				}
631
+			}
632 632
             
633
-            $this->reset_oidDesc();
634
-            if ($this->detect_trap($curElement,$onlyTraps)===true)
635
-            {
636
-                continue;
637
-            }
633
+			$this->reset_oidDesc();
634
+			if ($this->detect_trap($curElement,$onlyTraps)===true)
635
+			{
636
+				continue;
637
+			}
638 638
             
639
-            $this->timing['num_traps']++;
639
+			$this->timing['num_traps']++;
640 640
             
641
-            $this->logging->log('Found trap : '.$this->oidDesc['name'] . ' / OID : '.$this->oidDesc['oid'],INFO );
642
-            if ($display_progress) echo '#'; // echo a # when trap found
641
+			$this->logging->log('Found trap : '.$this->oidDesc['name'] . ' / OID : '.$this->oidDesc['oid'],INFO );
642
+			if ($display_progress) echo '#'; // echo a # when trap found
643 643
 
644
-            // get trap objects & source MIB
644
+			// get trap objects & source MIB
645 645
             
646
-            $snmptrans=$this->get_trap_mib_description(); // get MIB & description
646
+			$snmptrans=$this->get_trap_mib_description(); // get MIB & description
647 647
 
648 648
 
649
-            $update=$this->update_oid(); // Do update of trap.
649
+			$update=$this->update_oid(); // Do update of trap.
650 650
             
651
-            $this->timing['update_time'] += microtime(true) - $this->timing['base_time'];
652
-            $this->timing['update_num']++;
651
+			$this->timing['update_time'] += microtime(true) - $this->timing['base_time'];
652
+			$this->timing['update_num']++;
653 653
             
654
-            $this->timing['base_time']= microtime(true); // Reset to check object time
654
+			$this->timing['base_time']= microtime(true); // Reset to check object time
655 655
             
656
-            if (($update==0) && ($check_change===false))
657
-            { // Trapd didn't change & force check disabled
658
-                $this->timing['objects_time'] += microtime(true) - $this->timing['base_time'];
659
-                if ($display_progress) echo "C";
660
-                continue;
661
-            }
656
+			if (($update==0) && ($check_change===false))
657
+			{ // Trapd didn't change & force check disabled
658
+				$this->timing['objects_time'] += microtime(true) - $this->timing['base_time'];
659
+				if ($display_progress) echo "C";
660
+				continue;
661
+			}
662 662
             
663
-            $trapObjects=$this->get_trap_objects($snmptrans); // Get trap objects from snmptranslate output            
664
-            if ($trapObjects == null)
665
-            {
666
-                continue;
667
-            }
663
+			$trapObjects=$this->get_trap_objects($snmptrans); // Get trap objects from snmptranslate output            
664
+			if ($trapObjects == null)
665
+			{
666
+				continue;
667
+			}
668 668
            
669
-            $this->trap_objects($this->oidDesc['oid'], $this->oidDesc['mib'], $trapObjects, false);
669
+			$this->trap_objects($this->oidDesc['oid'], $this->oidDesc['mib'], $trapObjects, false);
670 670
             
671
-            $this->timing['objects_time'] += microtime(true) - $this->timing['base_time'];
672
-            $this->timing['objects_num']++;
673
-        }
671
+			$this->timing['objects_time'] += microtime(true) - $this->timing['base_time'];
672
+			$this->timing['objects_num']++;
673
+		}
674 674
         
675
-        if ($display_progress)
676
-        {
677
-            echo "\nNumber of processed traps :  ". $this->timing['num_traps'] ."\n";
678
-            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";
679
-            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";
680
-            echo "Trap processing (".$this->timing['update_num']."): ".number_format($this->timing['update_time'],1)." sec , ";
681
-            echo "Objects processing (".$this->timing['objects_num'].") : ".number_format($this->timing['objects_time'],1)." sec \n";
675
+		if ($display_progress)
676
+		{
677
+			echo "\nNumber of processed traps :  ". $this->timing['num_traps'] ."\n";
678
+			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";
679
+			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";
680
+			echo "Trap processing (".$this->timing['update_num']."): ".number_format($this->timing['update_time'],1)." sec , ";
681
+			echo "Objects processing (".$this->timing['objects_num'].") : ".number_format($this->timing['objects_time'],1)." sec \n";
682 682
             
683
-            $timeTaken=microtime(true) - $timeTaken;
684
-            echo "Global time : ".round($timeTaken)." seconds\n";
685
-        }
686
-    }
683
+			$timeTaken=microtime(true) - $timeTaken;
684
+			echo "Global time : ".round($timeTaken)." seconds\n";
685
+		}
686
+	}
687 687
     
688 688
     
689 689
 }
690 690
\ No newline at end of file
Please login to merge, or discard this patch.
Spacing   +111 added lines, -111 removed lines patch added patch discarded remove patch
@@ -32,7 +32,7 @@  discard block
 block discarded – undo
32 32
      * @param Logging $logClass : where to log
33 33
      * @param Database $dbClass : Database
34 34
      */
35
-    function __construct($logClass,$dbClass,$snmptrans,$snmptransdir)
35
+    function __construct($logClass, $dbClass, $snmptrans, $snmptransdir)
36 36
     {
37 37
         $this->logging=$logClass;
38 38
         $this->trapsDB=$dbClass;
@@ -56,9 +56,9 @@  discard block
 block discarded – undo
56 56
         }
57 57
         $oidIndex=$this->dbOidIndex[$this->oidDesc['oid']]['key']; // Get index in dbOidAll
58 58
         $dbOid=$this->dbOidAll[$oidIndex]; // Get array of element
59
-        if ( $this->oidDesc['name'] != $dbOid['name'] ||
59
+        if ($this->oidDesc['name'] != $dbOid['name'] ||
60 60
             $this->oidDesc['mib'] != $dbOid['mib'] ||
61
-            $this->oidDesc['type'] !=$dbOid['type']
61
+            $this->oidDesc['type'] != $dbOid['type']
62 62
             )
63 63
         { // Do update
64 64
             $sql='UPDATE '.$this->trapsDB->dbPrefix.'mib_cache SET '.
@@ -72,22 +72,22 @@  discard block
 block discarded – undo
72 72
                 ':type' => $this->oidDesc['type'],
73 73
                 ':mib' => $this->oidDesc['mib'],
74 74
                 ':tc' =>  $this->oidDesc['textconv']??'null',
75
-                ':display_hint' => $this->oidDesc['dispHint']??'null' ,
76
-                ':syntax' => $this->oidDesc['syntax']==null??'null',
75
+                ':display_hint' => $this->oidDesc['dispHint']??'null',
76
+                ':syntax' => $this->oidDesc['syntax'] == null??'null',
77 77
                 ':type_enum' => $this->oidDesc['type_enum']??'null',
78 78
                 ':description' => $this->oidDesc['description']??'null',
79 79
                 ':id' => $this->dbOidAll[$this->dbOidIndex[$this->oidDesc['oid']]['id']]
80 80
             );
81 81
             
82 82
             if ($sqlQuery->execute($sqlParam) === false) {
83
-                $this->logging->log('Error in query : ' . $sql,ERROR,'');
83
+                $this->logging->log('Error in query : '.$sql, ERROR, '');
84 84
             }
85
-            $this->logging->log('Trap updated : '.$this->oidDesc['name'] . ' / OID : '.$this->oidDesc['oid'],DEBUG );
85
+            $this->logging->log('Trap updated : '.$this->oidDesc['name'].' / OID : '.$this->oidDesc['oid'], DEBUG);
86 86
             return 1;
87 87
         }
88 88
         else
89 89
         {
90
-            $this->logging->log('Trap unchanged : '.$this->oidDesc['name'] . ' / OID : '.$this->oidDesc['oid'],DEBUG );
90
+            $this->logging->log('Trap unchanged : '.$this->oidDesc['name'].' / OID : '.$this->oidDesc['oid'], DEBUG);
91 91
             return 0;
92 92
         }
93 93
     }
@@ -103,11 +103,11 @@  discard block
 block discarded – undo
103 103
         $db_conn=$this->trapsDB->db_connect_trap();
104 104
         $sql='INSERT INTO '.$this->trapsDB->dbPrefix.'mib_cache '.
105 105
             '(oid, name, type , mib, textual_convention, display_hint '.
106
-            ', syntax, type_enum , description ) ' .
106
+            ', syntax, type_enum , description ) '.
107 107
             'values (:oid, :name , :type ,:mib ,:tc , :display_hint'.
108 108
             ', :syntax, :type_enum, :description )';
109 109
         
110
-        if ($this->trapsDB->trapDBType == 'pgsql') $sql .= 'RETURNING id';
110
+        if ($this->trapsDB->trapDBType == 'pgsql') $sql.='RETURNING id';
111 111
         
112 112
         $sqlQuery=$db_conn->prepare($sql);
113 113
         
@@ -124,7 +124,7 @@  discard block
 block discarded – undo
124 124
         );
125 125
         
126 126
         if ($sqlQuery->execute($sqlParam) === false) {
127
-            $this->logging->log('Error in query : ' . $sql,1,'');
127
+            $this->logging->log('Error in query : '.$sql, 1, '');
128 128
         }
129 129
         
130 130
         switch ($this->trapsDB->trapDBType)
@@ -132,10 +132,10 @@  discard block
 block discarded – undo
132 132
             case 'pgsql':
133 133
                 // Get last id to insert oid/values in secondary table
134 134
                 if (($inserted_id_ret=$sqlQuery->fetch(PDO::FETCH_ASSOC)) === false) {
135
-                    $this->logging->log('Error getting id - pgsql - ',1,'');
135
+                    $this->logging->log('Error getting id - pgsql - ', 1, '');
136 136
                 }
137
-                if (! isset($inserted_id_ret['id'])) {
138
-                    $this->logging->log('Error getting id - pgsql - empty.',ERROR);
137
+                if (!isset($inserted_id_ret['id'])) {
138
+                    $this->logging->log('Error getting id - pgsql - empty.', ERROR);
139 139
                     return 0;
140 140
                 }
141 141
                 $this->dbOidIndex[$this->oidDesc['oid']]['id']=$inserted_id_ret['id'];
@@ -144,16 +144,16 @@  discard block
 block discarded – undo
144 144
                 // Get last id to insert oid/values in secondary table
145 145
                 $sql='SELECT LAST_INSERT_ID();';
146 146
                 if (($ret_code=$db_conn->query($sql)) === false) {
147
-                    $this->logging->log('Erreur getting id - mysql - ',ERROR);
147
+                    $this->logging->log('Erreur getting id - mysql - ', ERROR);
148 148
                     return 0;
149 149
                 }
150 150
                 
151 151
                 $inserted_id=$ret_code->fetch(PDO::FETCH_ASSOC)['LAST_INSERT_ID()'];
152
-                if ($inserted_id==false) throw new Exception("Weird SQL error : last_insert_id returned false : open issue");
152
+                if ($inserted_id == false) throw new Exception("Weird SQL error : last_insert_id returned false : open issue");
153 153
                 $this->dbOidIndex[$this->oidDesc['oid']]['id']=$inserted_id;
154 154
                 break;
155 155
             default:
156
-                $this->logging->log('Error SQL type Unknown : '.$this->trapsDB->trapDBType,ERROR);
156
+                $this->logging->log('Error SQL type Unknown : '.$this->trapsDB->trapDBType, ERROR);
157 157
                 return 0;
158 158
         }
159 159
         
@@ -193,9 +193,9 @@  discard block
 block discarded – undo
193 193
         $db_conn=$this->trapsDB->db_connect_trap();
194 194
         // Get all objects
195 195
         $sql='SELECT * FROM '.$this->trapsDB->dbPrefix.'mib_cache_trap_object where trap_id='.$trapId.';';
196
-        $this->logging->log('SQL query get all traps: '.$sql,DEBUG );
196
+        $this->logging->log('SQL query get all traps: '.$sql, DEBUG);
197 197
         if (($ret_code=$db_conn->query($sql)) === false) {
198
-            $this->logging->log('No result in query : ' . $sql,1,'');
198
+            $this->logging->log('No result in query : '.$sql, 1, '');
199 199
         }
200 200
         $dbObjectsRaw=$ret_code->fetchAll();
201 201
         
@@ -212,30 +212,30 @@  discard block
 block discarded – undo
212 212
  * @param string $trapmib : mib of trap
213 213
  * @return NULL|array : null if not found, or output of snmptranslate
214 214
  */
215
-    private function get_object_details($object,$trapmib)
215
+    private function get_object_details($object, $trapmib)
216 216
     {
217 217
         $match=$snmptrans=array();
218 218
         $retVal=0;
219 219
         $this->oidDesc['mib']=$trapmib;
220
-        exec($this->snmptranslate . ' -m ALL -M +'.$this->snmptranslateDirs.
221
-            ' -On -Td '.$this->oidDesc['mib'].'::'.$object . ' 2>/dev/null',$snmptrans,$retVal);
222
-        if ($retVal!=0)
220
+        exec($this->snmptranslate.' -m ALL -M +'.$this->snmptranslateDirs.
221
+            ' -On -Td '.$this->oidDesc['mib'].'::'.$object.' 2>/dev/null', $snmptrans, $retVal);
222
+        if ($retVal != 0)
223 223
         {
224 224
             // Maybe not trap mib, search with IR
225
-            exec($this->snmptranslate . ' -m ALL -M +'.$this->snmptranslateDirs.
226
-                ' -IR '.$object . ' 2>/dev/null',$snmptrans,$retVal);
227
-            if ($retVal != 0 || !preg_match('/(.*)::(.*)/',$snmptrans[0],$match))
225
+            exec($this->snmptranslate.' -m ALL -M +'.$this->snmptranslateDirs.
226
+                ' -IR '.$object.' 2>/dev/null', $snmptrans, $retVal);
227
+            if ($retVal != 0 || !preg_match('/(.*)::(.*)/', $snmptrans[0], $match))
228 228
             { // Not found -> continue with warning
229
-                $this->logging->log('Error finding trap object : '.$trapmib.'::'.$object,2,'');
229
+                $this->logging->log('Error finding trap object : '.$trapmib.'::'.$object, 2, '');
230 230
                 return null;
231 231
             }
232 232
             $this->oidDesc['mib']=$match[1];
233 233
             
234 234
             // Do the snmptranslate again.
235
-            exec($this->snmptranslate . ' -m ALL -M +'.$this->snmptranslateDirs.
236
-                ' -On -Td '.$this->oidDesc['mib'].'::'.$object,$snmptrans,$retVal);
237
-            if ($retVal!=0) {
238
-                $this->logging->log('Error finding trap object : '.$this->oidDesc['mib'].'::'.$object,2,'');
235
+            exec($this->snmptranslate.' -m ALL -M +'.$this->snmptranslateDirs.
236
+                ' -On -Td '.$this->oidDesc['mib'].'::'.$object, $snmptrans, $retVal);
237
+            if ($retVal != 0) {
238
+                $this->logging->log('Error finding trap object : '.$this->oidDesc['mib'].'::'.$object, 2, '');
239 239
                 return null;
240 240
             }
241 241
             
@@ -255,12 +255,12 @@  discard block
 block discarded – undo
255 255
         
256 256
         foreach ($snmptrans as $line)
257 257
         {
258
-            if ($indesc===true)
258
+            if ($indesc === true)
259 259
             {
260
-                $line=preg_replace('/[\t ]+/',' ',$line);
261
-                if (preg_match('/(.*)"$/', $line,$match))
260
+                $line=preg_replace('/[\t ]+/', ' ', $line);
261
+                if (preg_match('/(.*)"$/', $line, $match))
262 262
                 {
263
-                    $this->oidDesc['description'] = $tmpdesc . $match[1];
263
+                    $this->oidDesc['description']=$tmpdesc.$match[1];
264 264
                     $indesc=false;
265 265
                 }
266 266
                 $tmpdesc.=$line;
@@ -271,34 +271,34 @@  discard block
 block discarded – undo
271 271
                 $this->oidDesc['oid']=$line;
272 272
                 continue;
273 273
             }
274
-            if (preg_match('/^[\t ]+SYNTAX[\t ]+([^{]*) \{(.*)\}/',$line,$match))
274
+            if (preg_match('/^[\t ]+SYNTAX[\t ]+([^{]*) \{(.*)\}/', $line, $match))
275 275
             {
276 276
                 $this->oidDesc['syntax']=$match[1];
277 277
                 $this->oidDesc['type_enum']=$match[2];
278 278
                 continue;
279 279
             }
280
-            if (preg_match('/^[\t ]+SYNTAX[\t ]+(.*)/',$line,$match))
280
+            if (preg_match('/^[\t ]+SYNTAX[\t ]+(.*)/', $line, $match))
281 281
             {
282 282
                 $this->oidDesc['syntax']=$match[1];
283 283
                 continue;
284 284
             }
285
-            if (preg_match('/^[\t ]+DISPLAY-HINT[\t ]+"(.*)"/',$line,$match))
285
+            if (preg_match('/^[\t ]+DISPLAY-HINT[\t ]+"(.*)"/', $line, $match))
286 286
             {
287 287
                 $this->oidDesc['dispHint']=$match[1];
288 288
                 continue;
289 289
             }
290
-            if (preg_match('/^[\t ]+DESCRIPTION[\t ]+"(.*)"/',$line,$match))
290
+            if (preg_match('/^[\t ]+DESCRIPTION[\t ]+"(.*)"/', $line, $match))
291 291
             {
292 292
                 $this->oidDesc['description']=$match[1];
293 293
                 continue;
294 294
             }
295
-            if (preg_match('/^[\t ]+DESCRIPTION[\t ]+"(.*)/',$line,$match))
295
+            if (preg_match('/^[\t ]+DESCRIPTION[\t ]+"(.*)/', $line, $match))
296 296
             {
297 297
                 $tmpdesc=$match[1];
298 298
                 $indesc=true;
299 299
                 continue;
300 300
             }
301
-            if (preg_match('/^[\t ]+-- TEXTUAL CONVENTION[\t ]+(.*)/',$line,$match))
301
+            if (preg_match('/^[\t ]+-- TEXTUAL CONVENTION[\t ]+(.*)/', $line, $match))
302 302
             {
303 303
                 $this->oidDesc['textconv']=$match[1];
304 304
                 continue;
@@ -313,9 +313,9 @@  discard block
 block discarded – undo
313 313
      * @param array $objects : array of objects name (without MIB)
314 314
      * @param bool $check_existing : check instead of create
315 315
      */
316
-    public function trap_objects($trapOID,$trapmib,$objects,$check_existing)
316
+    public function trap_objects($trapOID, $trapmib, $objects, $check_existing)
317 317
     {              
318
-        $trapId = $this->dbOidIndex[$trapOID]['id']; // Get id of trap
318
+        $trapId=$this->dbOidIndex[$trapOID]['id']; // Get id of trap
319 319
         
320 320
         if ($check_existing === true)
321 321
         {
@@ -332,9 +332,9 @@  discard block
 block discarded – undo
332 332
             
333 333
             $this->parse_object($snmptrans);
334 334
 
335
-            $this->oidDesc['name'] = $object;
335
+            $this->oidDesc['name']=$object;
336 336
             
337
-            $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 );
337
+            $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);
338 338
 
339 339
             // Update
340 340
             $this->update_oid();
@@ -359,7 +359,7 @@  discard block
 block discarded – undo
359 359
             );
360 360
             
361 361
             if ($sqlQuery->execute($sqlParam) === false) {
362
-                $this->logging->log('Error adding trap object : ' . $sql . ' / ' . $trapId . '/'. $this->dbOidIndex[$this->oidDesc['oid']]['id'] ,1,'');
362
+                $this->logging->log('Error adding trap object : '.$sql.' / '.$trapId.'/'.$this->dbOidIndex[$this->oidDesc['oid']]['id'], 1, '');
363 363
             }
364 364
         }
365 365
         if ($check_existing === true)
@@ -376,7 +376,7 @@  discard block
 block discarded – undo
376 376
         $this->oidDesc['type']=null;
377 377
         $this->oidDesc['mib']=null;
378 378
         $this->oidDesc['textconv']=null;
379
-        $this->oidDesc['dispHint'] =null;
379
+        $this->oidDesc['dispHint']=null;
380 380
         $this->oidDesc['syntax']=null;
381 381
         $this->oidDesc['type_enum']=null;
382 382
         $this->oidDesc['description']=null;
@@ -390,17 +390,17 @@  discard block
 block discarded – undo
390 390
     {
391 391
         $retVal=0;
392 392
         // Get all mib objects from all mibs
393
-        $snmpCommand=$this->snmptranslate . ' -m ALL -M +'.$this->snmptranslateDirs.' -On -Tto 2>/dev/null';
394
-        $this->logging->log('Getting all traps : '.$snmpCommand,DEBUG );
393
+        $snmpCommand=$this->snmptranslate.' -m ALL -M +'.$this->snmptranslateDirs.' -On -Tto 2>/dev/null';
394
+        $this->logging->log('Getting all traps : '.$snmpCommand, DEBUG);
395 395
         unset($this->objectsAll);
396
-        exec($snmpCommand,$this->objectsAll,$retVal);
397
-        if ($retVal!=0)
396
+        exec($snmpCommand, $this->objectsAll, $retVal);
397
+        if ($retVal != 0)
398 398
         {
399
-            $this->logging->log('error executing snmptranslate',ERROR,'');
399
+            $this->logging->log('error executing snmptranslate', ERROR, '');
400 400
         }
401 401
         // Count elements to show progress
402 402
         $numElements=count($this->objectsAll);
403
-        $this->logging->log('Total snmp objects returned by snmptranslate : '.$numElements,INFO );
403
+        $this->logging->log('Total snmp objects returned by snmptranslate : '.$numElements, INFO);
404 404
         return $numElements;
405 405
     }
406 406
 
@@ -414,14 +414,14 @@  discard block
 block discarded – undo
414 414
         $db_conn=$this->trapsDB->db_connect_trap();
415 415
         
416 416
         $sql='SELECT * from '.$this->trapsDB->dbPrefix.'mib_cache;';
417
-        $this->logging->log('SQL query : '.$sql,DEBUG );
417
+        $this->logging->log('SQL query : '.$sql, DEBUG);
418 418
         if (($ret_code=$db_conn->query($sql)) === false) {
419
-            $this->logging->log('No result in query : ' . $sql,ERROR,'');
419
+            $this->logging->log('No result in query : '.$sql, ERROR, '');
420 420
         }
421 421
         $this->dbOidAll=$ret_code->fetchAll();
422 422
         $this->dbOidIndex=array();
423 423
         // Create the index for db;
424
-        foreach($this->dbOidAll as $key=>$val)
424
+        foreach ($this->dbOidAll as $key=>$val)
425 425
         {
426 426
             $this->dbOidIndex[$val['oid']]['key']=$key;
427 427
             $this->dbOidIndex[$val['oid']]['id']=$val['id'];
@@ -454,13 +454,13 @@  discard block
 block discarded – undo
454 454
      * @param bool $onlyTraps : set to false to get all and not only traps.
455 455
      * @return boolean : false if it's a trap , true if not
456 456
      */
457
-    private function detect_trap($curElement,$onlyTraps)
457
+    private function detect_trap($curElement, $onlyTraps)
458 458
     {
459 459
         // Get oid or pass if not found
460
-        if (!preg_match('/^\.[0-9\.]+$/',$this->objectsAll[$curElement]))
460
+        if (!preg_match('/^\.[0-9\.]+$/', $this->objectsAll[$curElement]))
461 461
         {
462
-            $this->timing['base_parse_time'] += microtime(true) - $this->timing['base_time'];
463
-            $this->timing['base_parse_num'] ++;
462
+            $this->timing['base_parse_time']+=microtime(true) - $this->timing['base_time'];
463
+            $this->timing['base_parse_num']++;
464 464
             return true;
465 465
         }
466 466
         $this->oidDesc['oid']=$this->objectsAll[$curElement];
@@ -469,9 +469,9 @@  discard block
 block discarded – undo
469 469
         $curElement++;
470 470
         $match=$snmptrans=array();
471 471
         if (!preg_match('/ +([^\(]+)\(.+\) type=([0-9]+)( tc=([0-9]+))?( hint=(.+))?/',
472
-            $this->objectsAll[$curElement],$match))
472
+            $this->objectsAll[$curElement], $match))
473 473
         {
474
-            $this->timing['base_check_time'] += microtime(true) - $this->timing['base_time'];
474
+            $this->timing['base_check_time']+=microtime(true) - $this->timing['base_time'];
475 475
             $this->timing['base_check_num']++;
476 476
             return true;
477 477
         }
@@ -479,22 +479,22 @@  discard block
 block discarded – undo
479 479
         $this->oidDesc['name']=$match[1]; // Name
480 480
         $this->oidDesc['type']=$match[2]; // type (21=trap, 0: may be trap, else : not trap
481 481
         
482
-        if ($this->oidDesc['type']==0) // object type=0 : check if v1 trap
482
+        if ($this->oidDesc['type'] == 0) // object type=0 : check if v1 trap
483 483
         {
484 484
             // Check if next is suboid -> in that case is cannot be a trap
485
-            if (preg_match("/^".$this->oidDesc['oid']."/",$this->objectsAll[$curElement+1]))
485
+            if (preg_match("/^".$this->oidDesc['oid']."/", $this->objectsAll[$curElement + 1]))
486 486
             {
487
-                $this->timing['type0_check_time'] += microtime(true) - $this->timing['base_time'];
487
+                $this->timing['type0_check_time']+=microtime(true) - $this->timing['base_time'];
488 488
                 $this->timing['type0_check_num']++;
489 489
                 return true;
490 490
             }
491 491
             unset($snmptrans);
492 492
             $retVal=0;
493
-            exec($this->snmptranslate . ' -m ALL -M +'.$this->snmptranslateDirs.
494
-                ' -Td '.$this->oidDesc['oid'] . ' | grep OBJECTS ',$snmptrans,$retVal);
495
-            if ($retVal!=0)
493
+            exec($this->snmptranslate.' -m ALL -M +'.$this->snmptranslateDirs.
494
+                ' -Td '.$this->oidDesc['oid'].' | grep OBJECTS ', $snmptrans, $retVal);
495
+            if ($retVal != 0)
496 496
             {
497
-                $this->timing['type0_check_time'] += microtime(true) - $this->timing['base_time'];
497
+                $this->timing['type0_check_time']+=microtime(true) - $this->timing['base_time'];
498 498
                 $this->timing['type0_check_num']++;
499 499
                 return true;
500 500
             }
@@ -502,9 +502,9 @@  discard block
 block discarded – undo
502 502
             // Force as trap.
503 503
             $this->oidDesc['type']=21;
504 504
         }
505
-        if ($onlyTraps===true && $this->oidDesc['type']!=21) // if only traps and not a trap, continue
505
+        if ($onlyTraps === true && $this->oidDesc['type'] != 21) // if only traps and not a trap, continue
506 506
         {
507
-            $this->timing['nottrap_time'] += microtime(true) - $this->timing['base_time'];
507
+            $this->timing['nottrap_time']+=microtime(true) - $this->timing['base_time'];
508 508
             $this->timing['nottrap_num']++;
509 509
             return true;
510 510
         }
@@ -519,35 +519,35 @@  discard block
 block discarded – undo
519 519
     {
520 520
         $retVal=0;
521 521
         $match=$snmptrans=array();
522
-        exec($this->snmptranslate . ' -m ALL -M +'.$this->snmptranslateDirs.
523
-            ' -Td '.$this->oidDesc['oid'],$snmptrans,$retVal);
524
-        if ($retVal!=0)
522
+        exec($this->snmptranslate.' -m ALL -M +'.$this->snmptranslateDirs.
523
+            ' -Td '.$this->oidDesc['oid'], $snmptrans, $retVal);
524
+        if ($retVal != 0)
525 525
         {
526
-            $this->logging->log('error executing snmptranslate',ERROR);
526
+            $this->logging->log('error executing snmptranslate', ERROR);
527 527
             return $snmptrans;
528 528
         }
529 529
         
530
-        if (!preg_match('/^(.*)::/',$snmptrans[0],$match))
530
+        if (!preg_match('/^(.*)::/', $snmptrans[0], $match))
531 531
         {
532
-            $this->logging->log('Error getting mib from trap '.$this->oidDesc['oid'].' : ' . $snmptrans[0],ERROR);
532
+            $this->logging->log('Error getting mib from trap '.$this->oidDesc['oid'].' : '.$snmptrans[0], ERROR);
533 533
             return $snmptrans;
534 534
         }
535 535
         $this->oidDesc['mib']=$match[1];
536 536
         
537 537
         $numLine=1;
538
-        while (isset($snmptrans[$numLine]) && !preg_match('/^[\t ]+DESCRIPTION[\t ]+"(.*)/',$snmptrans[$numLine],$match)) $numLine++;
538
+        while (isset($snmptrans[$numLine]) && !preg_match('/^[\t ]+DESCRIPTION[\t ]+"(.*)/', $snmptrans[$numLine], $match)) $numLine++;
539 539
         if (isset($snmptrans[$numLine]))
540 540
         {
541
-            $snmptrans[$numLine] = preg_replace('/^[\t ]+DESCRIPTION[\t ]+"/','',$snmptrans[$numLine]);
541
+            $snmptrans[$numLine]=preg_replace('/^[\t ]+DESCRIPTION[\t ]+"/', '', $snmptrans[$numLine]);
542 542
             
543
-            while (isset($snmptrans[$numLine]) && !preg_match('/"/',$snmptrans[$numLine]))
543
+            while (isset($snmptrans[$numLine]) && !preg_match('/"/', $snmptrans[$numLine]))
544 544
             {
545
-                $this->oidDesc['description'].=preg_replace('/[\t ]+/',' ',$snmptrans[$numLine]);
545
+                $this->oidDesc['description'].=preg_replace('/[\t ]+/', ' ', $snmptrans[$numLine]);
546 546
                 $numLine++;
547 547
             }
548 548
             if (isset($snmptrans[$numLine])) {
549
-                $this->oidDesc['description'].=preg_replace('/".*/','',$snmptrans[$numLine]);
550
-                $this->oidDesc['description']=preg_replace('/[\t ]+/',' ',$this->oidDesc['description']);
549
+                $this->oidDesc['description'].=preg_replace('/".*/', '', $snmptrans[$numLine]);
550
+                $this->oidDesc['description']=preg_replace('/[\t ]+/', ' ', $this->oidDesc['description']);
551 551
             }
552 552
             
553 553
         }
@@ -565,23 +565,23 @@  discard block
 block discarded – undo
565 565
         $match=array();
566 566
         foreach ($snmptrans as $line)
567 567
         {
568
-            if (preg_match('/OBJECTS.*\{([^\}]+)\}/',$line,$match))
568
+            if (preg_match('/OBJECTS.*\{([^\}]+)\}/', $line, $match))
569 569
             {
570 570
                 $objectName=$match[1];
571 571
             }
572 572
         }
573 573
         if ($objectName == null)
574 574
         {
575
-            $this->logging->log('No objects for ' . $this->oidDesc['oid'],DEBUG);
576
-            $this->timing['objects_time'] += microtime(true) - $this->timing['base_time'];
575
+            $this->logging->log('No objects for '.$this->oidDesc['oid'], DEBUG);
576
+            $this->timing['objects_time']+=microtime(true) - $this->timing['base_time'];
577 577
             return null;
578 578
         }
579 579
         
580 580
         $trapObjects=array();
581
-        while (preg_match('/ *([^ ,]+) *,* */',$objectName,$match))
581
+        while (preg_match('/ *([^ ,]+) *,* */', $objectName, $match))
582 582
         {
583
-            array_push($trapObjects,$match[1]);
584
-            $objectName=preg_replace('/'.$match[0].'/','',$objectName);
583
+            array_push($trapObjects, $match[1]);
584
+            $objectName=preg_replace('/'.$match[0].'/', '', $objectName);
585 585
         }
586 586
         return $trapObjects;
587 587
     }
@@ -593,18 +593,18 @@  discard block
 block discarded – undo
593 593
      * @param boolean $onlyTraps : only cache traps and objects (true) or all (false)
594 594
      * @param string $startOID : only cache under startOID (NOT IMPLEMENTED)
595 595
      */
596
-    public function update_mib_database($display_progress=false,$check_change=false,$onlyTraps=true,$startOID='.1')
596
+    public function update_mib_database($display_progress=false, $check_change=false, $onlyTraps=true, $startOID='.1')
597 597
     {
598 598
         // Global Timing
599
-        $timeTaken = microtime(true);
599
+        $timeTaken=microtime(true);
600 600
         
601 601
         $numElements=$this->load_mibs_snmptranslate(); // Load objectsAll
602 602
         
603 603
         $this->load_mibs_from_db(); // Load from db dbOidAll & dbOidIndex
604 604
         
605
-        $step=$basestep=$numElements/10; // output display of % done
605
+        $step=$basestep=$numElements / 10; // output display of % done
606 606
         $num_step=0;
607
-        $timeFiveSec = microtime(true); // Used for display a '.' every <n> seconds
607
+        $timeFiveSec=microtime(true); // Used for display a '.' every <n> seconds
608 608
         
609 609
         // Create index for trap objects
610 610
         $this->trapObjectsIndex=array();
@@ -612,33 +612,33 @@  discard block
 block discarded – undo
612 612
         // detailed timing (time_* vars)
613 613
         $this->reset_update_timers();
614 614
         
615
-        for ($curElement=0;$curElement < $numElements;$curElement++)
615
+        for ($curElement=0; $curElement < $numElements; $curElement++)
616 616
         {
617
-            $this->timing['base_time']= microtime(true);
617
+            $this->timing['base_time']=microtime(true);
618 618
             if ($display_progress)
619 619
             {
620
-                if ((microtime(true)-$timeFiveSec) > 2)
620
+                if ((microtime(true) - $timeFiveSec) > 2)
621 621
                 { // echo a . every 2 sec
622 622
                     echo '.';
623
-                    $timeFiveSec = microtime(true);
623
+                    $timeFiveSec=microtime(true);
624 624
                 }
625
-                if ($curElement>$step)
625
+                if ($curElement > $step)
626 626
                 { // display progress
627 627
                     $num_step++;
628 628
                     $step+=$basestep;   
629
-                    echo "\n" . ($num_step*10). '% : ';
629
+                    echo "\n".($num_step * 10).'% : ';
630 630
                 }
631 631
             }
632 632
             
633 633
             $this->reset_oidDesc();
634
-            if ($this->detect_trap($curElement,$onlyTraps)===true)
634
+            if ($this->detect_trap($curElement, $onlyTraps) === true)
635 635
             {
636 636
                 continue;
637 637
             }
638 638
             
639 639
             $this->timing['num_traps']++;
640 640
             
641
-            $this->logging->log('Found trap : '.$this->oidDesc['name'] . ' / OID : '.$this->oidDesc['oid'],INFO );
641
+            $this->logging->log('Found trap : '.$this->oidDesc['name'].' / OID : '.$this->oidDesc['oid'], INFO);
642 642
             if ($display_progress) echo '#'; // echo a # when trap found
643 643
 
644 644
             // get trap objects & source MIB
@@ -648,14 +648,14 @@  discard block
 block discarded – undo
648 648
 
649 649
             $update=$this->update_oid(); // Do update of trap.
650 650
             
651
-            $this->timing['update_time'] += microtime(true) - $this->timing['base_time'];
651
+            $this->timing['update_time']+=microtime(true) - $this->timing['base_time'];
652 652
             $this->timing['update_num']++;
653 653
             
654
-            $this->timing['base_time']= microtime(true); // Reset to check object time
654
+            $this->timing['base_time']=microtime(true); // Reset to check object time
655 655
             
656
-            if (($update==0) && ($check_change===false))
656
+            if (($update == 0) && ($check_change === false))
657 657
             { // Trapd didn't change & force check disabled
658
-                $this->timing['objects_time'] += microtime(true) - $this->timing['base_time'];
658
+                $this->timing['objects_time']+=microtime(true) - $this->timing['base_time'];
659 659
                 if ($display_progress) echo "C";
660 660
                 continue;
661 661
             }
@@ -668,17 +668,17 @@  discard block
 block discarded – undo
668 668
            
669 669
             $this->trap_objects($this->oidDesc['oid'], $this->oidDesc['mib'], $trapObjects, false);
670 670
             
671
-            $this->timing['objects_time'] += microtime(true) - $this->timing['base_time'];
671
+            $this->timing['objects_time']+=microtime(true) - $this->timing['base_time'];
672 672
             $this->timing['objects_num']++;
673 673
         }
674 674
         
675 675
         if ($display_progress)
676 676
         {
677
-            echo "\nNumber of processed traps :  ". $this->timing['num_traps'] ."\n";
678
-            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";
679
-            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";
680
-            echo "Trap processing (".$this->timing['update_num']."): ".number_format($this->timing['update_time'],1)." sec , ";
681
-            echo "Objects processing (".$this->timing['objects_num'].") : ".number_format($this->timing['objects_time'],1)." sec \n";
677
+            echo "\nNumber of processed traps :  ".$this->timing['num_traps']."\n";
678
+            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";
679
+            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";
680
+            echo "Trap processing (".$this->timing['update_num']."): ".number_format($this->timing['update_time'], 1)." sec , ";
681
+            echo "Objects processing (".$this->timing['objects_num'].") : ".number_format($this->timing['objects_time'], 1)." sec \n";
682 682
             
683 683
             $timeTaken=microtime(true) - $timeTaken;
684 684
             echo "Global time : ".round($timeTaken)." seconds\n";
Please login to merge, or discard this patch.
bin/trap_class.php 3 patches
Indentation   +210 added lines, -210 removed lines patch added patch discarded remove patch
@@ -58,7 +58,7 @@  discard block
 block discarded – undo
58 58
 	
59 59
 	function __construct($etc_dir='/etc/icingaweb2',$baseLogLevel=null,$baseLogMode='syslog',$baseLogFile='')
60 60
 	{
61
-	    // Paths of ini files
61
+		// Paths of ini files
62 62
 		$this->icingaweb2_etc=$etc_dir;
63 63
 		$this->trap_module_config=$this->icingaweb2_etc."/modules/trapdirector/config.ini";		
64 64
 		$this->icingaweb2_ressources=$this->icingaweb2_etc."/resources.ini";
@@ -67,18 +67,18 @@  discard block
 block discarded – undo
67 67
 		$this->logging = new Logging();
68 68
 		if ($baseLogLevel != null)
69 69
 		{
70
-		    $this->logging->setLogging($baseLogLevel, $baseLogMode,$baseLogFile);
71
-		    $this->logSetup=true;
70
+			$this->logging->setLogging($baseLogLevel, $baseLogMode,$baseLogFile);
71
+			$this->logSetup=true;
72 72
 		}
73 73
 		else
74
-		    $this->logSetup=false;
74
+			$this->logSetup=false;
75 75
 		$this->logging->log('Loggin started', INFO);
76 76
 
77 77
 		// Get options from ini files
78 78
 		$trapConfig=parse_ini_file($this->trap_module_config,true);
79 79
 		if ($trapConfig == false)
80 80
 		{
81
-		    $this->logging->log("Error reading ini file : ".$this->trap_module_config,ERROR,'syslog');
81
+			$this->logging->log("Error reading ini file : ".$this->trap_module_config,ERROR,'syslog');
82 82
 		}
83 83
 		$this->getMainOptions($trapConfig); // Get main options from ini file
84 84
 		$this->setupDatabase($trapConfig); // Setup database class
@@ -112,26 +112,26 @@  discard block
 block discarded – undo
112 112
 	 */
113 113
 	protected function getOptionIfSet($option_array,$option_category,$option_name, &$option_var, $log_level = 2, $message = null)
114 114
 	{
115
-	    if (!isset($option_array[$option_category][$option_name]))
116
-	    {
117
-	        if ($message === null)
118
-	        {
119
-	            $message='No ' . $option_name . ' in config file: '. $this->trap_module_config;
120
-	        }
121
-	        $this->logging->log($message,$log_level,'syslog');
122
-	        return false;
123
-	    }
124
-	    else
125
-	    {
126
-	        $option_var=$option_array[$option_category][$option_name];
127
-	        return true;
128
-	    }
115
+		if (!isset($option_array[$option_category][$option_name]))
116
+		{
117
+			if ($message === null)
118
+			{
119
+				$message='No ' . $option_name . ' in config file: '. $this->trap_module_config;
120
+			}
121
+			$this->logging->log($message,$log_level,'syslog');
122
+			return false;
123
+		}
124
+		else
125
+		{
126
+			$option_var=$option_array[$option_category][$option_name];
127
+			return true;
128
+		}
129 129
 	}
130 130
 	
131 131
 	/** 
132 132
 	 * Get options from ini file
133 133
 	 * @param array $trap_config : ini file array
134
-	*/
134
+	 */
135 135
 	protected function getMainOptions($trapConfig)
136 136
 	{
137 137
 
@@ -150,10 +150,10 @@  discard block
 block discarded – undo
150 150
 		// API options
151 151
 		if ($this->getOptionIfSet($trapConfig,'config','icingaAPI_host', $this->api_hostname))
152 152
 		{
153
-		    $this->api_use=true;
154
-		    $this->getOptionIfSet($trapConfig,'config','icingaAPI_port', $this->api_port);
155
-		    $this->getOptionIfSet($trapConfig,'config','icingaAPI_user', $this->api_username);
156
-		    $this->getOptionIfSet($trapConfig,'config','icingaAPI_password', $this->api_password);
153
+			$this->api_use=true;
154
+			$this->getOptionIfSet($trapConfig,'config','icingaAPI_port', $this->api_port);
155
+			$this->getOptionIfSet($trapConfig,'config','icingaAPI_user', $this->api_username);
156
+			$this->getOptionIfSet($trapConfig,'config','icingaAPI_password', $this->api_password);
157 157
 		}
158 158
 	}
159 159
 	
@@ -163,45 +163,45 @@  discard block
 block discarded – undo
163 163
 	 */
164 164
 	protected function setupDatabase($trapConfig)
165 165
 	{
166
-	    // Trap database
167
-	    if (!array_key_exists('database',$trapConfig['config']))
168
-        {
169
-            $this->logging->log("No database in config file: ".$this->trap_module_config,ERROR,'');
170
-            return;
171
-        }
172
-        $dbTrapName=$trapConfig['config']['database'];
173
-        $this->logging->log("Found database in config file: ".$dbTrapName,INFO );
166
+		// Trap database
167
+		if (!array_key_exists('database',$trapConfig['config']))
168
+		{
169
+			$this->logging->log("No database in config file: ".$this->trap_module_config,ERROR,'');
170
+			return;
171
+		}
172
+		$dbTrapName=$trapConfig['config']['database'];
173
+		$this->logging->log("Found database in config file: ".$dbTrapName,INFO );
174 174
 	    
175 175
 	   if ( ($dbConfig=parse_ini_file($this->icingaweb2_ressources,true)) === false)
176
-	    {
177
-	        $this->logging->log("Error reading ini file : ".$this->icingaweb2_ressources,ERROR,'');
178
-	        return;
179
-	    }
180
-	    if (!array_key_exists($dbTrapName,$dbConfig))
181
-	    {
182
-	        $this->logging->log("No database '.$dbTrapName.' in config file: ".$this->icingaweb2_ressources,ERROR,'');
183
-	        return;
184
-	    }
176
+		{
177
+			$this->logging->log("Error reading ini file : ".$this->icingaweb2_ressources,ERROR,'');
178
+			return;
179
+		}
180
+		if (!array_key_exists($dbTrapName,$dbConfig))
181
+		{
182
+			$this->logging->log("No database '.$dbTrapName.' in config file: ".$this->icingaweb2_ressources,ERROR,'');
183
+			return;
184
+		}
185 185
 	    
186
-	    $this->trapsDB = new Database($this->logging,$dbConfig[$dbTrapName],$this->db_prefix);
186
+		$this->trapsDB = new Database($this->logging,$dbConfig[$dbTrapName],$this->db_prefix);
187 187
 	    
188
-	    if ($this->api_use === true) return; // In case of API use, no IDO is necessary
188
+		if ($this->api_use === true) return; // In case of API use, no IDO is necessary
189 189
         
190
-	    // IDO Database
191
-	    if (!array_key_exists('IDOdatabase',$trapConfig['config']))
192
-	    {
193
-	        $this->logging->log("No IDOdatabase in config file: ".$this->trap_module_config,ERROR,'');
194
-	    }
195
-	    $dbIdoName=$trapConfig['config']['IDOdatabase'];		
196
-
197
-	    $this->logging->log("Found IDO database in config file: ".$dbIdoName,INFO );
198
-        if (!array_key_exists($dbIdoName,$dbConfig))
199
-	    {
200
-	        $this->logging->log("No database '.$dbIdoName.' in config file: ".$this->icingaweb2_ressources,ERROR,'');
201
-	        return;
202
-	    }
190
+		// IDO Database
191
+		if (!array_key_exists('IDOdatabase',$trapConfig['config']))
192
+		{
193
+			$this->logging->log("No IDOdatabase in config file: ".$this->trap_module_config,ERROR,'');
194
+		}
195
+		$dbIdoName=$trapConfig['config']['IDOdatabase'];		
196
+
197
+		$this->logging->log("Found IDO database in config file: ".$dbIdoName,INFO );
198
+		if (!array_key_exists($dbIdoName,$dbConfig))
199
+		{
200
+			$this->logging->log("No database '.$dbIdoName.' in config file: ".$this->icingaweb2_ressources,ERROR,'');
201
+			return;
202
+		}
203 203
 	    
204
-	    $this->trapsDB->setupIDO($dbConfig[$dbIdoName]);
204
+		$this->trapsDB->setupIDO($dbConfig[$dbIdoName]);
205 205
 	}
206 206
 	
207 207
 	/**
@@ -212,9 +212,9 @@  discard block
 block discarded – undo
212 212
 		// Database options
213 213
 		if ($this->logSetup === false) // Only if logging was no setup in constructor
214 214
 		{
215
-    		$this->getDBConfigIfSet('log_level',$this->logging->debugLevel);
216
-    		$this->getDBConfigIfSet('log_destination',$this->logging->outputMode);
217
-    		$this->getDBConfigIfSet('log_file',$this->logging->outputFile);
215
+			$this->getDBConfigIfSet('log_level',$this->logging->debugLevel);
216
+			$this->getDBConfigIfSet('log_destination',$this->logging->outputMode);
217
+			$this->getDBConfigIfSet('log_file',$this->logging->outputFile);
218 218
 		}
219 219
 	}
220 220
 
@@ -225,10 +225,10 @@  discard block
 block discarded – undo
225 225
 	}
226 226
 	
227 227
 	/** 
228
-	*   Get data from db_config
229
-	*	@param $element string name of param
230
-	*	@return mixed : value (or null)
231
-	*/	
228
+	 *   Get data from db_config
229
+	 *	@param $element string name of param
230
+	 *	@return mixed : value (or null)
231
+	 */	
232 232
 	protected function getDBConfig($element)
233 233
 	{
234 234
 		$db_conn=$this->trapsDB->db_connect_trap();
@@ -246,15 +246,15 @@  discard block
 block discarded – undo
246 246
 	}
247 247
 	
248 248
 	/** OBSOLETE Send log. Throws exception on critical error
249
-	*	@param	string $message Message to log
250
-	*	@param	int $level 1=critical 2=warning 3=trace 4=debug
251
-	*	@param  string $destination file/syslog/display
252
-	*	@return void
253
-	**/	
249
+	 *	@param	string $message Message to log
250
+	 *	@param	int $level 1=critical 2=warning 3=trace 4=debug
251
+	 *	@param  string $destination file/syslog/display
252
+	 *	@return void
253
+	 **/	
254 254
 	public function trapLog( $message, $level, $destination ='') // OBSOLETE
255 255
 	{	
256 256
 		// TODO : replace ref with $this->logging->log 
257
-	    $this->logging->log($message, $level, $destination);
257
+		$this->logging->log($message, $level, $destination);
258 258
 	}
259 259
 	
260 260
 	public function setLogging($debugLvl,$outputType,$outputOption=null)  // OBSOLETE
@@ -264,19 +264,19 @@  discard block
 block discarded – undo
264 264
 	
265 265
 	protected function getAPI()
266 266
 	{
267
-	    if ($this->icinga2api == null)
268
-	    {
269
-	        $this->icinga2api = new Icinga2API($this->api_hostname,$this->api_port);
270
-	    }
271
-	    return $this->icinga2api;
267
+		if ($this->icinga2api == null)
268
+		{
269
+			$this->icinga2api = new Icinga2API($this->api_hostname,$this->api_port);
270
+		}
271
+		return $this->icinga2api;
272 272
 	}
273 273
 	
274 274
 	
275 275
 	/** 
276 276
 	 * read data from stream
277
-	*	@param $stream string input stream, defaults to "php://stdin"
278
-	*	@return mixed array trap data or exception with error
279
-	*/
277
+	 *	@param $stream string input stream, defaults to "php://stdin"
278
+	 *	@return mixed array trap data or exception with error
279
+	 */
280 280
 	public function read_trap($stream='php://stdin')
281 281
 	{
282 282
 		//Read data from snmptrapd from stdin
@@ -284,7 +284,7 @@  discard block
 block discarded – undo
284 284
 
285 285
 		if ($input_stream === false)
286 286
 		{
287
-		    $this->writeTrapErrorToDB("Error reading trap (code 1/Stdin)");
287
+			$this->writeTrapErrorToDB("Error reading trap (code 1/Stdin)");
288 288
 			$this->logging->log("Error reading stdin !",ERROR,'');
289 289
 			return null; // note : exception thrown by logging
290 290
 		}
@@ -293,21 +293,21 @@  discard block
 block discarded – undo
293 293
 		$this->receivingHost=chop(fgets($input_stream));
294 294
 		if ($this->receivingHost === false)
295 295
 		{
296
-		    $this->writeTrapErrorToDB("Error reading trap (code 1/Line Host)");
296
+			$this->writeTrapErrorToDB("Error reading trap (code 1/Line Host)");
297 297
 			$this->logging->log("Error reading Host !",ERROR,''); 
298 298
 		}
299 299
 		// line 2 IP:port=>IP:port
300 300
 		$IP=chop(fgets($input_stream));
301 301
 		if ($IP === false)
302 302
 		{
303
-		    $this->writeTrapErrorToDB("Error reading trap (code 1/Line IP)");
303
+			$this->writeTrapErrorToDB("Error reading trap (code 1/Line IP)");
304 304
 			$this->logging->log("Error reading IP !",ERROR,''); 
305 305
 		}
306 306
 		$matches=array();
307 307
 		$ret_code=preg_match('/.DP: \[(.*)\]:(.*)->\[(.*)\]:(.*)/',$IP,$matches);
308 308
 		if ($ret_code===0 || $ret_code===false) 
309 309
 		{
310
-		    $this->writeTrapErrorToDB("Error parsing trap (code 2/IP)");
310
+			$this->writeTrapErrorToDB("Error parsing trap (code 2/IP)");
311 311
 			$this->logging->log('Error parsing IP : '.$IP,ERROR,'');
312 312
 		} 
313 313
 		else 
@@ -328,7 +328,7 @@  discard block
 block discarded – undo
328 328
 			}
329 329
 			else 
330 330
 			{
331
-			    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'))
331
+				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'))
332 332
 				{
333 333
 					$this->trap_data['trap_oid']=$matches[2];				
334 334
 				}
@@ -344,7 +344,7 @@  discard block
 block discarded – undo
344 344
 
345 345
 		if ($this->trap_data['trap_oid']=='unknown') 
346 346
 		{
347
-		    $this->writeTrapErrorToDB("No trap oid found : check snmptrapd configuration (code 3/OID)",$this->trap_data['source_ip']);
347
+			$this->writeTrapErrorToDB("No trap oid found : check snmptrapd configuration (code 3/OID)",$this->trap_data['source_ip']);
348 348
 			$this->logging->log('no trap oid found',ERROR,'');
349 349
 		} 
350 350
 
@@ -374,9 +374,9 @@  discard block
 block discarded – undo
374 374
 
375 375
 	/** 
376 376
 	 * Translate oid into array(MIB,Name)
377
-	* @param $oid string oid to translate
378
-	* @return mixed : null if not found or array(MIB,Name)
379
-	*/
377
+	 * @param $oid string oid to translate
378
+	 * @return mixed : null if not found or array(MIB,Name)
379
+	 */
380 380
 	public function translateOID($oid)
381 381
 	{
382 382
 		// try from database
@@ -409,7 +409,7 @@  discard block
 block discarded – undo
409 409
 		
410 410
 		// Try to get oid name from snmptranslate
411 411
 		$translate=exec($this->snmptranslate . ' -m ALL -M +'.$this->snmptranslate_dirs.
412
-		    ' '.$oid);
412
+			' '.$oid);
413 413
 		$matches=array();
414 414
 		$ret_code=preg_match('/(.*)::(.*)/',$translate,$matches);
415 415
 		if ($ret_code===0 || $ret_code === false) {
@@ -422,9 +422,9 @@  discard block
 block discarded – undo
422 422
 	
423 423
 	/** 
424 424
 	 * Erase old trap records 
425
-	*	@param integer $days : erase traps when more than $days old
426
-	*	@return integer : number of lines deleted
427
-	**/
425
+	 *	@param integer $days : erase traps when more than $days old
426
+	 *	@return integer : number of lines deleted
427
+	 **/
428 428
 	public function eraseOldTraps($days=0)
429 429
 	{
430 430
 		if ($days==0)
@@ -449,72 +449,72 @@  discard block
 block discarded – undo
449 449
 	public function writeTrapErrorToDB($message,$sourceIP=null,$trapoid=null)
450 450
 	{
451 451
 	    
452
-	    $db_conn=$this->trapsDB->db_connect_trap();
452
+		$db_conn=$this->trapsDB->db_connect_trap();
453 453
 	    
454
-	    // add date time
455
-	    $insert_col ='date_received,status';
456
-	    $insert_val = "'" . date("Y-m-d H:i:s")."','error'";
454
+		// add date time
455
+		$insert_col ='date_received,status';
456
+		$insert_val = "'" . date("Y-m-d H:i:s")."','error'";
457 457
         
458
-	    if ($sourceIP !=null)
459
-	    {
460
-	        $insert_col .=',source_ip';
461
-	        $insert_val .=",'". $sourceIP ."'";
462
-	    }
463
-	    if ($trapoid !=null)
464
-	    {
465
-	        $insert_col .=',trap_oid';
466
-	        $insert_val .=",'". $trapoid ."'";
467
-	    }
468
-	    $insert_col .=',status_detail';
469
-	    $insert_val .=",'". $message ."'";
458
+		if ($sourceIP !=null)
459
+		{
460
+			$insert_col .=',source_ip';
461
+			$insert_val .=",'". $sourceIP ."'";
462
+		}
463
+		if ($trapoid !=null)
464
+		{
465
+			$insert_col .=',trap_oid';
466
+			$insert_val .=",'". $trapoid ."'";
467
+		}
468
+		$insert_col .=',status_detail';
469
+		$insert_val .=",'". $message ."'";
470 470
 	    
471
-	    $sql= 'INSERT INTO '.$this->db_prefix.'received (' . $insert_col . ') VALUES ('.$insert_val.')';
471
+		$sql= 'INSERT INTO '.$this->db_prefix.'received (' . $insert_col . ') VALUES ('.$insert_val.')';
472 472
 	    
473
-	    switch ($this->trapsDB->trapDBType)
474
-	    {
475
-	        case 'pgsql':
476
-	            $sql .= ' RETURNING id;';
477
-	            $this->logging->log('sql : '.$sql,INFO);
478
-	            if (($ret_code=$db_conn->query($sql)) === false) {
479
-	                $this->logging->log('Error SQL insert : '.$sql,1,'');
480
-	            }
481
-	            $this->logging->log('SQL insertion OK',INFO );
482
-	            // Get last id to insert oid/values in secondary table
483
-	            if (($inserted_id_ret=$ret_code->fetch(PDO::FETCH_ASSOC)) === false) {
473
+		switch ($this->trapsDB->trapDBType)
474
+		{
475
+			case 'pgsql':
476
+				$sql .= ' RETURNING id;';
477
+				$this->logging->log('sql : '.$sql,INFO);
478
+				if (($ret_code=$db_conn->query($sql)) === false) {
479
+					$this->logging->log('Error SQL insert : '.$sql,1,'');
480
+				}
481
+				$this->logging->log('SQL insertion OK',INFO );
482
+				// Get last id to insert oid/values in secondary table
483
+				if (($inserted_id_ret=$ret_code->fetch(PDO::FETCH_ASSOC)) === false) {
484 484
 	                
485
-	                $this->logging->log('Erreur recuperation id',1,'');
486
-	            }
487
-	            if (! isset($inserted_id_ret['id'])) {
488
-	                $this->logging->log('Error getting id',1,'');
489
-	            }
490
-	            $this->trap_id=$inserted_id_ret['id'];
491
-	            break;
492
-	        case 'mysql':
493
-	            $sql .= ';';
494
-	            $this->logging->log('sql : '.$sql,INFO );
495
-	            if ($db_conn->query($sql) === false) {
496
-	                $this->logging->log('Error SQL insert : '.$sql,1,'');
497
-	            }
498
-	            $this->logging->log('SQL insertion OK',INFO );
499
-	            // Get last id to insert oid/values in secondary table
500
-	            $sql='SELECT LAST_INSERT_ID();';
501
-	            if (($ret_code=$db_conn->query($sql)) === false) {
502
-	                $this->logging->log('Erreur recuperation id',1,'');
503
-	            }
485
+					$this->logging->log('Erreur recuperation id',1,'');
486
+				}
487
+				if (! isset($inserted_id_ret['id'])) {
488
+					$this->logging->log('Error getting id',1,'');
489
+				}
490
+				$this->trap_id=$inserted_id_ret['id'];
491
+				break;
492
+			case 'mysql':
493
+				$sql .= ';';
494
+				$this->logging->log('sql : '.$sql,INFO );
495
+				if ($db_conn->query($sql) === false) {
496
+					$this->logging->log('Error SQL insert : '.$sql,1,'');
497
+				}
498
+				$this->logging->log('SQL insertion OK',INFO );
499
+				// Get last id to insert oid/values in secondary table
500
+				$sql='SELECT LAST_INSERT_ID();';
501
+				if (($ret_code=$db_conn->query($sql)) === false) {
502
+					$this->logging->log('Erreur recuperation id',1,'');
503
+				}
504 504
 	            
505
-	            $inserted_id=$ret_code->fetch(PDO::FETCH_ASSOC)['LAST_INSERT_ID()'];
506
-	            if ($inserted_id==false) throw new Exception("Weird SQL error : last_insert_id returned false : open issue");
507
-	            $this->trap_id=$inserted_id;
508
-	            break;
509
-	        default:
510
-	            $this->logging->log('Error SQL type unknown  : '.$this->trapsDB->trapDBType,1,'');
511
-	    }
505
+				$inserted_id=$ret_code->fetch(PDO::FETCH_ASSOC)['LAST_INSERT_ID()'];
506
+				if ($inserted_id==false) throw new Exception("Weird SQL error : last_insert_id returned false : open issue");
507
+				$this->trap_id=$inserted_id;
508
+				break;
509
+			default:
510
+				$this->logging->log('Error SQL type unknown  : '.$this->trapsDB->trapDBType,1,'');
511
+		}
512 512
 	    
513
-	    $this->logging->log('id found: '. $this->trap_id,INFO );    
513
+		$this->logging->log('id found: '. $this->trap_id,INFO );    
514 514
 	}
515 515
 	
516 516
 	/** Write trap data to trap database
517
-	*/
517
+	 */
518 518
 	public function writeTrapToDB()
519 519
 	{
520 520
 		
@@ -612,10 +612,10 @@  discard block
 block discarded – undo
612 612
 	}
613 613
 
614 614
 	/** Get rules from rule database with ip and oid
615
-	*	@param $ip string ipv4 or ipv6
616
-	*	@param $oid string oid in numeric
617
-	*	@return mixed : PDO object or false
618
-	*/	
615
+	 *	@param $ip string ipv4 or ipv6
616
+	 *	@param $oid string oid in numeric
617
+	 *	@return mixed : PDO object or false
618
+	 */	
619 619
 	protected function getRules($ip,$oid)
620 620
 	{
621 621
 		$db_conn=$this->trapsDB->db_connect_trap();
@@ -674,9 +674,9 @@  discard block
 block discarded – undo
674 674
 	}
675 675
 
676 676
 	/** Add rule match to rule
677
-	*	@param id int : rule id
678
-	*   @param set int : value to set
679
-	*/
677
+	 *	@param id int : rule id
678
+	 *   @param set int : value to set
679
+	 */
680 680
 	protected function add_rule_match($id, $set)
681 681
 	{
682 682
 		$db_conn=$this->trapsDB->db_connect_trap();
@@ -693,53 +693,53 @@  discard block
 block discarded – undo
693 693
 	 * @param integer $state numerical staus 
694 694
 	 * @param string $display
695 695
 	 * @returnn bool true is service check was sent without error
696
-	*/
696
+	 */
697 697
 	public function serviceCheckResult($host,$service,$state,$display)
698 698
 	{
699
-	    if ($this->api_use === false)
700
-	    {
701
-    		$send = '[' . date('U') .'] PROCESS_SERVICE_CHECK_RESULT;' .
702
-    			$host.';' .$service .';' . $state . ';'.$display;
703
-    		$this->logging->log( $send." : to : " .$this->icinga2cmd,INFO );
699
+		if ($this->api_use === false)
700
+		{
701
+			$send = '[' . date('U') .'] PROCESS_SERVICE_CHECK_RESULT;' .
702
+				$host.';' .$service .';' . $state . ';'.$display;
703
+			$this->logging->log( $send." : to : " .$this->icinga2cmd,INFO );
704 704
     		
705
-    		// TODO : file_put_contents & fopen (,'w' or 'a') does not work. See why. Or not as using API will be by default....
706
-    		exec('echo "'.$send.'" > ' .$this->icinga2cmd);
707
-    		return true;
708
-	    }
709
-	    else
710
-	    {
711
-	        $api = $this->getAPI();
712
-	        $api->setCredentials($this->api_username, $this->api_password);
713
-	        list($retcode,$retmessage)=$api->serviceCheckResult($host,$service,$state,$display);
714
-	        if ($retcode == false)
715
-	        {
716
-	            $this->logging->log( "Error sending result : " .$retmessage,WARN,'');
717
-	            return false;
718
-	        }
719
-	        else 
720
-	        {
721
-	            $this->logging->log( "Sent result : " .$retmessage,INFO );
722
-	            return true;
723
-	        }
724
-	    }
705
+			// TODO : file_put_contents & fopen (,'w' or 'a') does not work. See why. Or not as using API will be by default....
706
+			exec('echo "'.$send.'" > ' .$this->icinga2cmd);
707
+			return true;
708
+		}
709
+		else
710
+		{
711
+			$api = $this->getAPI();
712
+			$api->setCredentials($this->api_username, $this->api_password);
713
+			list($retcode,$retmessage)=$api->serviceCheckResult($host,$service,$state,$display);
714
+			if ($retcode == false)
715
+			{
716
+				$this->logging->log( "Error sending result : " .$retmessage,WARN,'');
717
+				return false;
718
+			}
719
+			else 
720
+			{
721
+				$this->logging->log( "Sent result : " .$retmessage,INFO );
722
+				return true;
723
+			}
724
+		}
725 725
 	}
726 726
 	
727 727
 	public function getHostByIP($ip)
728 728
 	{
729
-	    $api = $this->getAPI();
730
-	    $api->setCredentials($this->api_username, $this->api_password);
731
-	    return $api->getHostByIP($ip);
729
+		$api = $this->getAPI();
730
+		$api->setCredentials($this->api_username, $this->api_password);
731
+		return $api->getHostByIP($ip);
732 732
 	}
733 733
 	
734 734
 	/** Resolve display. 
735
-	*	Changes OID(<oid>) to value if found or text "<not in trap>"
736
-	*	@param $display string
737
-	*	@return string display
738
-	*/
735
+	 *	Changes OID(<oid>) to value if found or text "<not in trap>"
736
+	 *	@param $display string
737
+	 *	@return string display
738
+	 */
739 739
 	protected function applyDisplay($display)
740 740
 	{
741
-	    $matches=array();
742
-	    while (preg_match('/_OID\(([0-9\.]+)\)/',$display,$matches) == 1)
741
+		$matches=array();
742
+		while (preg_match('/_OID\(([0-9\.]+)\)/',$display,$matches) == 1)
743 743
 		{
744 744
 			$oid=$matches[1];
745 745
 			$found=0;
@@ -773,7 +773,7 @@  discard block
 block discarded – undo
773 773
 	}
774 774
 	
775 775
 	/** Match rules for current trap and do action
776
-	*/
776
+	 */
777 777
 	public function applyRules()
778 778
 	{
779 779
 		$rules = $this->getRules($this->trap_data['source_ip'],$this->trap_data['trap_oid']);
@@ -811,12 +811,12 @@  discard block
 block discarded – undo
811 811
 					{
812 812
 						if ($this->serviceCheckResult($host_name,$service_name,$action,$display) == false)
813 813
 						{
814
-						    $this->trap_action.='Error sending status : check cmd/API';
814
+							$this->trap_action.='Error sending status : check cmd/API';
815 815
 						}
816 816
 						else
817 817
 						{
818
-						    $this->add_rule_match($rule['id'],$rule['num_match']+1);
819
-						    $this->trap_action.='Status '.$action.' to '.$host_name.'/'.$service_name;
818
+							$this->add_rule_match($rule['id'],$rule['num_match']+1);
819
+							$this->trap_action.='Status '.$action.' to '.$host_name.'/'.$service_name;
820 820
 						}
821 821
 					}
822 822
 					else
@@ -833,15 +833,15 @@  discard block
 block discarded – undo
833 833
 					$this->logging->log('action NOK : '.$action,INFO );
834 834
 					if ($action >= 0)
835 835
 					{
836
-					    if ($this->serviceCheckResult($host_name,$service_name,$action,$display)==false)
837
-					    {
838
-					        $this->trap_action.='Error sending status : check cmd/API';
839
-					    }
840
-					    else
841
-					    {
842
-    						$this->add_rule_match($rule['id'],$rule['num_match']+1);
843
-    						$this->trap_action.='Status '.$action.' to '.$host_name.'/'.$service_name;
844
-					    }
836
+						if ($this->serviceCheckResult($host_name,$service_name,$action,$display)==false)
837
+						{
838
+							$this->trap_action.='Error sending status : check cmd/API';
839
+						}
840
+						else
841
+						{
842
+							$this->add_rule_match($rule['id'],$rule['num_match']+1);
843
+							$this->trap_action.='Status '.$action.' to '.$host_name.'/'.$service_name;
844
+						}
845 845
 					}
846 846
 					else
847 847
 					{
@@ -864,9 +864,9 @@  discard block
 block discarded – undo
864 864
 			}
865 865
 			catch (Exception $e) 
866 866
 			{ 
867
-			    $this->logging->log('Error in rule eval : '.$e->getMessage(),WARN,'');
868
-			    $this->trap_action.=' ERR : '.$e->getMessage();
869
-			    $this->trap_data['status']='error';
867
+				$this->logging->log('Error in rule eval : '.$e->getMessage(),WARN,'');
868
+				$this->trap_action.=' ERR : '.$e->getMessage();
869
+				$this->trap_data['status']='error';
870 870
 			}
871 871
 			
872 872
 		}
@@ -881,8 +881,8 @@  discard block
 block discarded – undo
881 881
 	}
882 882
 
883 883
 	/** Add Time a action to rule
884
-	*	@param string $time : time to process to insert in SQL
885
-	*/
884
+	 *	@param string $time : time to process to insert in SQL
885
+	 */
886 886
 	public function add_rule_final($time)
887 887
 	{
888 888
 		$db_conn=$this->trapsDB->db_connect_trap();
@@ -899,9 +899,9 @@  discard block
 block discarded – undo
899 899
 	/*********** UTILITIES *********************/
900 900
 	
901 901
 	/** reset service to OK after time defined in rule
902
-	*	TODO logic is : get all service in error + all rules, see if getting all rules then select services is better 
903
-	*	@return integer : not in use
904
-	**/
902
+	 *	TODO logic is : get all service in error + all rules, see if getting all rules then select services is better 
903
+	 *	@return integer : not in use
904
+	 **/
905 905
 	public function reset_services()
906 906
 	{
907 907
 		// Get all services not in 'ok' state
Please login to merge, or discard this patch.
Spacing   +190 added lines, -190 removed lines patch added patch discarded remove patch
@@ -36,8 +36,8 @@  discard block
 block discarded – undo
36 36
 	protected $api_password='';
37 37
 
38 38
 	// Logs 
39
-	protected $logging;    //< Logging class.
40
-	protected $logSetup;   //< bool true if log was setup in constructor
39
+	protected $logging; //< Logging class.
40
+	protected $logSetup; //< bool true if log was setup in constructor
41 41
 	
42 42
 	// Databases
43 43
 	public $trapsDB; //< Database class
@@ -56,7 +56,7 @@  discard block
 block discarded – undo
56 56
 	// Rule evaluation 
57 57
 	public $ruleClass; // Rule class
58 58
 	
59
-	function __construct($etc_dir='/etc/icingaweb2',$baseLogLevel=null,$baseLogMode='syslog',$baseLogFile='')
59
+	function __construct($etc_dir='/etc/icingaweb2', $baseLogLevel=null, $baseLogMode='syslog', $baseLogFile='')
60 60
 	{
61 61
 	    // Paths of ini files
62 62
 		$this->icingaweb2_etc=$etc_dir;
@@ -64,10 +64,10 @@  discard block
 block discarded – undo
64 64
 		$this->icingaweb2_ressources=$this->icingaweb2_etc."/resources.ini";
65 65
 
66 66
 		// Setup logging
67
-		$this->logging = new Logging();
67
+		$this->logging=new Logging();
68 68
 		if ($baseLogLevel != null)
69 69
 		{
70
-		    $this->logging->setLogging($baseLogLevel, $baseLogMode,$baseLogFile);
70
+		    $this->logging->setLogging($baseLogLevel, $baseLogMode, $baseLogFile);
71 71
 		    $this->logSetup=true;
72 72
 		}
73 73
 		else
@@ -75,10 +75,10 @@  discard block
 block discarded – undo
75 75
 		$this->logging->log('Loggin started', INFO);
76 76
 
77 77
 		// Get options from ini files
78
-		$trapConfig=parse_ini_file($this->trap_module_config,true);
78
+		$trapConfig=parse_ini_file($this->trap_module_config, true);
79 79
 		if ($trapConfig == false)
80 80
 		{
81
-		    $this->logging->log("Error reading ini file : ".$this->trap_module_config,ERROR,'syslog');
81
+		    $this->logging->log("Error reading ini file : ".$this->trap_module_config, ERROR, 'syslog');
82 82
 		}
83 83
 		$this->getMainOptions($trapConfig); // Get main options from ini file
84 84
 		$this->setupDatabase($trapConfig); // Setup database class
@@ -86,9 +86,9 @@  discard block
 block discarded – undo
86 86
 		$this->getDatabaseOptions(); // Get options in database
87 87
 		if ($this->api_use === true) $this->getAPI(); // Setup API
88 88
 		
89
-		$this->mibClass = new Mib($this->logging,$this->trapsDB,$this->snmptranslate,$this->snmptranslate_dirs); // Create Mib class
89
+		$this->mibClass=new Mib($this->logging, $this->trapsDB, $this->snmptranslate, $this->snmptranslate_dirs); // Create Mib class
90 90
 		
91
-		$this->ruleClass = new Rule($this->logging); //< Create Rule class
91
+		$this->ruleClass=new Rule($this->logging); //< Create Rule class
92 92
 		
93 93
 		$this->trap_data=array(
94 94
 			'source_ip'	=> 'unknown',
@@ -110,15 +110,15 @@  discard block
 block discarded – undo
110 110
 	 * @param string $message warning message if not found
111 111
 	 * @return boolean true if found, or false
112 112
 	 */
113
-	protected function getOptionIfSet($option_array,$option_category,$option_name, &$option_var, $log_level = 2, $message = null)
113
+	protected function getOptionIfSet($option_array, $option_category, $option_name, &$option_var, $log_level=2, $message=null)
114 114
 	{
115 115
 	    if (!isset($option_array[$option_category][$option_name]))
116 116
 	    {
117 117
 	        if ($message === null)
118 118
 	        {
119
-	            $message='No ' . $option_name . ' in config file: '. $this->trap_module_config;
119
+	            $message='No '.$option_name.' in config file: '.$this->trap_module_config;
120 120
 	        }
121
-	        $this->logging->log($message,$log_level,'syslog');
121
+	        $this->logging->log($message, $log_level, 'syslog');
122 122
 	        return false;
123 123
 	    }
124 124
 	    else
@@ -136,24 +136,24 @@  discard block
 block discarded – undo
136 136
 	{
137 137
 
138 138
 		// Snmptranslate binary path
139
-		$this->getOptionIfSet($trapConfig,'config','snmptranslate', $this->snmptranslate);
139
+		$this->getOptionIfSet($trapConfig, 'config', 'snmptranslate', $this->snmptranslate);
140 140
 
141 141
 		// mibs path
142
-		$this->getOptionIfSet($trapConfig,'config','snmptranslate_dirs', $this->snmptranslate_dirs);
142
+		$this->getOptionIfSet($trapConfig, 'config', 'snmptranslate_dirs', $this->snmptranslate_dirs);
143 143
 
144 144
 		// icinga2cmd path
145
-		$this->getOptionIfSet($trapConfig,'config','icingacmd', $this->icinga2cmd);
145
+		$this->getOptionIfSet($trapConfig, 'config', 'icingacmd', $this->icinga2cmd);
146 146
 		
147 147
 		// table prefix
148
-		$this->getOptionIfSet($trapConfig,'config','database_prefix', $this->db_prefix);
148
+		$this->getOptionIfSet($trapConfig, 'config', 'database_prefix', $this->db_prefix);
149 149
 
150 150
 		// API options
151
-		if ($this->getOptionIfSet($trapConfig,'config','icingaAPI_host', $this->api_hostname))
151
+		if ($this->getOptionIfSet($trapConfig, 'config', 'icingaAPI_host', $this->api_hostname))
152 152
 		{
153 153
 		    $this->api_use=true;
154
-		    $this->getOptionIfSet($trapConfig,'config','icingaAPI_port', $this->api_port);
155
-		    $this->getOptionIfSet($trapConfig,'config','icingaAPI_user', $this->api_username);
156
-		    $this->getOptionIfSet($trapConfig,'config','icingaAPI_password', $this->api_password);
154
+		    $this->getOptionIfSet($trapConfig, 'config', 'icingaAPI_port', $this->api_port);
155
+		    $this->getOptionIfSet($trapConfig, 'config', 'icingaAPI_user', $this->api_username);
156
+		    $this->getOptionIfSet($trapConfig, 'config', 'icingaAPI_password', $this->api_password);
157 157
 		}
158 158
 	}
159 159
 	
@@ -164,40 +164,40 @@  discard block
 block discarded – undo
164 164
 	protected function setupDatabase($trapConfig)
165 165
 	{
166 166
 	    // Trap database
167
-	    if (!array_key_exists('database',$trapConfig['config']))
167
+	    if (!array_key_exists('database', $trapConfig['config']))
168 168
         {
169
-            $this->logging->log("No database in config file: ".$this->trap_module_config,ERROR,'');
169
+            $this->logging->log("No database in config file: ".$this->trap_module_config, ERROR, '');
170 170
             return;
171 171
         }
172 172
         $dbTrapName=$trapConfig['config']['database'];
173
-        $this->logging->log("Found database in config file: ".$dbTrapName,INFO );
173
+        $this->logging->log("Found database in config file: ".$dbTrapName, INFO);
174 174
 	    
175
-	   if ( ($dbConfig=parse_ini_file($this->icingaweb2_ressources,true)) === false)
175
+	   if (($dbConfig=parse_ini_file($this->icingaweb2_ressources, true)) === false)
176 176
 	    {
177
-	        $this->logging->log("Error reading ini file : ".$this->icingaweb2_ressources,ERROR,'');
177
+	        $this->logging->log("Error reading ini file : ".$this->icingaweb2_ressources, ERROR, '');
178 178
 	        return;
179 179
 	    }
180
-	    if (!array_key_exists($dbTrapName,$dbConfig))
180
+	    if (!array_key_exists($dbTrapName, $dbConfig))
181 181
 	    {
182
-	        $this->logging->log("No database '.$dbTrapName.' in config file: ".$this->icingaweb2_ressources,ERROR,'');
182
+	        $this->logging->log("No database '.$dbTrapName.' in config file: ".$this->icingaweb2_ressources, ERROR, '');
183 183
 	        return;
184 184
 	    }
185 185
 	    
186
-	    $this->trapsDB = new Database($this->logging,$dbConfig[$dbTrapName],$this->db_prefix);
186
+	    $this->trapsDB=new Database($this->logging, $dbConfig[$dbTrapName], $this->db_prefix);
187 187
 	    
188 188
 	    if ($this->api_use === true) return; // In case of API use, no IDO is necessary
189 189
         
190 190
 	    // IDO Database
191
-	    if (!array_key_exists('IDOdatabase',$trapConfig['config']))
191
+	    if (!array_key_exists('IDOdatabase', $trapConfig['config']))
192 192
 	    {
193
-	        $this->logging->log("No IDOdatabase in config file: ".$this->trap_module_config,ERROR,'');
193
+	        $this->logging->log("No IDOdatabase in config file: ".$this->trap_module_config, ERROR, '');
194 194
 	    }
195 195
 	    $dbIdoName=$trapConfig['config']['IDOdatabase'];		
196 196
 
197
-	    $this->logging->log("Found IDO database in config file: ".$dbIdoName,INFO );
198
-        if (!array_key_exists($dbIdoName,$dbConfig))
197
+	    $this->logging->log("Found IDO database in config file: ".$dbIdoName, INFO);
198
+        if (!array_key_exists($dbIdoName, $dbConfig))
199 199
 	    {
200
-	        $this->logging->log("No database '.$dbIdoName.' in config file: ".$this->icingaweb2_ressources,ERROR,'');
200
+	        $this->logging->log("No database '.$dbIdoName.' in config file: ".$this->icingaweb2_ressources, ERROR, '');
201 201
 	        return;
202 202
 	    }
203 203
 	    
@@ -212,13 +212,13 @@  discard block
 block discarded – undo
212 212
 		// Database options
213 213
 		if ($this->logSetup === false) // Only if logging was no setup in constructor
214 214
 		{
215
-    		$this->getDBConfigIfSet('log_level',$this->logging->debugLevel);
216
-    		$this->getDBConfigIfSet('log_destination',$this->logging->outputMode);
217
-    		$this->getDBConfigIfSet('log_file',$this->logging->outputFile);
215
+    		$this->getDBConfigIfSet('log_level', $this->logging->debugLevel);
216
+    		$this->getDBConfigIfSet('log_destination', $this->logging->outputMode);
217
+    		$this->getDBConfigIfSet('log_file', $this->logging->outputFile);
218 218
 		}
219 219
 	}
220 220
 
221
-	protected function getDBConfigIfSet($element,&$variable)
221
+	protected function getDBConfigIfSet($element, &$variable)
222 222
 	{
223 223
 		$value=$this->getDBConfig($element);
224 224
 		if ($value != 'null') $variable=$value;
@@ -234,7 +234,7 @@  discard block
 block discarded – undo
234 234
 		$db_conn=$this->trapsDB->db_connect_trap();
235 235
 		$sql='SELECT value from '.$this->db_prefix.'db_config WHERE ( name=\''.$element.'\' )';
236 236
 		if (($ret_code=$db_conn->query($sql)) === false) {
237
-			$this->logging->log('No result in query : ' . $sql,WARN,'');
237
+			$this->logging->log('No result in query : '.$sql, WARN, '');
238 238
 			return null;
239 239
 		}
240 240
 		$value=$ret_code->fetch();
@@ -251,22 +251,22 @@  discard block
 block discarded – undo
251 251
 	*	@param  string $destination file/syslog/display
252 252
 	*	@return void
253 253
 	**/	
254
-	public function trapLog( $message, $level, $destination ='') // OBSOLETE
254
+	public function trapLog($message, $level, $destination='') // OBSOLETE
255 255
 	{	
256 256
 		// TODO : replace ref with $this->logging->log 
257 257
 	    $this->logging->log($message, $level, $destination);
258 258
 	}
259 259
 	
260
-	public function setLogging($debugLvl,$outputType,$outputOption=null)  // OBSOLETE
260
+	public function setLogging($debugLvl, $outputType, $outputOption=null)  // OBSOLETE
261 261
 	{
262
-		$this->logging->setLogging($debugLvl, $outputType,$outputOption);
262
+		$this->logging->setLogging($debugLvl, $outputType, $outputOption);
263 263
 	}
264 264
 	
265 265
 	protected function getAPI()
266 266
 	{
267 267
 	    if ($this->icinga2api == null)
268 268
 	    {
269
-	        $this->icinga2api = new Icinga2API($this->api_hostname,$this->api_port);
269
+	        $this->icinga2api=new Icinga2API($this->api_hostname, $this->api_port);
270 270
 	    }
271 271
 	    return $this->icinga2api;
272 272
 	}
@@ -285,7 +285,7 @@  discard block
 block discarded – undo
285 285
 		if ($input_stream === false)
286 286
 		{
287 287
 		    $this->writeTrapErrorToDB("Error reading trap (code 1/Stdin)");
288
-			$this->logging->log("Error reading stdin !",ERROR,'');
288
+			$this->logging->log("Error reading stdin !", ERROR, '');
289 289
 			return null; // note : exception thrown by logging
290 290
 		}
291 291
 
@@ -294,21 +294,21 @@  discard block
 block discarded – undo
294 294
 		if ($this->receivingHost === false)
295 295
 		{
296 296
 		    $this->writeTrapErrorToDB("Error reading trap (code 1/Line Host)");
297
-			$this->logging->log("Error reading Host !",ERROR,''); 
297
+			$this->logging->log("Error reading Host !", ERROR, ''); 
298 298
 		}
299 299
 		// line 2 IP:port=>IP:port
300 300
 		$IP=chop(fgets($input_stream));
301 301
 		if ($IP === false)
302 302
 		{
303 303
 		    $this->writeTrapErrorToDB("Error reading trap (code 1/Line IP)");
304
-			$this->logging->log("Error reading IP !",ERROR,''); 
304
+			$this->logging->log("Error reading IP !", ERROR, ''); 
305 305
 		}
306 306
 		$matches=array();
307
-		$ret_code=preg_match('/.DP: \[(.*)\]:(.*)->\[(.*)\]:(.*)/',$IP,$matches);
308
-		if ($ret_code===0 || $ret_code===false) 
307
+		$ret_code=preg_match('/.DP: \[(.*)\]:(.*)->\[(.*)\]:(.*)/', $IP, $matches);
308
+		if ($ret_code === 0 || $ret_code === false) 
309 309
 		{
310 310
 		    $this->writeTrapErrorToDB("Error parsing trap (code 2/IP)");
311
-			$this->logging->log('Error parsing IP : '.$IP,ERROR,'');
311
+			$this->logging->log('Error parsing IP : '.$IP, ERROR, '');
312 312
 		} 
313 313
 		else 
314 314
 		{		
@@ -318,34 +318,34 @@  discard block
 block discarded – undo
318 318
 			$this->trap_data['destination_port']=$matches[4];
319 319
 		}
320 320
 
321
-		while (($vars=fgets($input_stream)) !==false)
321
+		while (($vars=fgets($input_stream)) !== false)
322 322
 		{
323 323
 			$vars=chop($vars);
324
-			$ret_code=preg_match('/^([^ ]+) (.*)$/',$vars,$matches);
325
-			if ($ret_code===0 || $ret_code===false) 
324
+			$ret_code=preg_match('/^([^ ]+) (.*)$/', $vars, $matches);
325
+			if ($ret_code === 0 || $ret_code === false) 
326 326
 			{
327
-				$this->logging->log('No match on trap data : '.$vars,WARN,'');
327
+				$this->logging->log('No match on trap data : '.$vars, WARN, '');
328 328
 			}
329 329
 			else 
330 330
 			{
331
-			    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'))
331
+			    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'))
332 332
 				{
333 333
 					$this->trap_data['trap_oid']=$matches[2];				
334 334
 				}
335 335
 				else
336 336
 				{
337
-					$object= new stdClass;
338
-					$object->oid =$matches[1];
339
-					$object->value = $matches[2];
340
-					array_push($this->trap_data_ext,$object);
337
+					$object=new stdClass;
338
+					$object->oid=$matches[1];
339
+					$object->value=$matches[2];
340
+					array_push($this->trap_data_ext, $object);
341 341
 				}
342 342
 			}
343 343
 		}
344 344
 
345
-		if ($this->trap_data['trap_oid']=='unknown') 
345
+		if ($this->trap_data['trap_oid'] == 'unknown') 
346 346
 		{
347
-		    $this->writeTrapErrorToDB("No trap oid found : check snmptrapd configuration (code 3/OID)",$this->trap_data['source_ip']);
348
-			$this->logging->log('no trap oid found',ERROR,'');
347
+		    $this->writeTrapErrorToDB("No trap oid found : check snmptrapd configuration (code 3/OID)", $this->trap_data['source_ip']);
348
+			$this->logging->log('no trap oid found', ERROR, '');
349 349
 		} 
350 350
 
351 351
 		// Translate oids.
@@ -367,7 +367,7 @@  discard block
 block discarded – undo
367 367
 		}
368 368
 		
369 369
 
370
-		$this->trap_data['status']= 'waiting';
370
+		$this->trap_data['status']='waiting';
371 371
 		
372 372
 		return $this->trap_data;
373 373
 	}
@@ -383,40 +383,40 @@  discard block
 block discarded – undo
383 383
 		$db_conn=$this->trapsDB->db_connect_trap();
384 384
 		
385 385
 		$sql='SELECT mib,name from '.$this->db_prefix.'mib_cache WHERE oid=\''.$oid.'\';';
386
-		$this->logging->log('SQL query : '.$sql,DEBUG );
386
+		$this->logging->log('SQL query : '.$sql, DEBUG);
387 387
 		if (($ret_code=$db_conn->query($sql)) === false) {
388
-			$this->logging->log('No result in query : ' . $sql,ERROR,'');
388
+			$this->logging->log('No result in query : '.$sql, ERROR, '');
389 389
 		}
390 390
 		$name=$ret_code->fetch();
391 391
 		if ($name['name'] != null)
392 392
 		{
393
-			return array('trap_name_mib'=>$name['mib'],'trap_name'=>$name['name']);
393
+			return array('trap_name_mib'=>$name['mib'], 'trap_name'=>$name['name']);
394 394
 		}
395 395
 		
396 396
 		// Also check if it is an instance of OID
397
-		$oid_instance=preg_replace('/\.[0-9]+$/','',$oid);
397
+		$oid_instance=preg_replace('/\.[0-9]+$/', '', $oid);
398 398
 		
399 399
 		$sql='SELECT mib,name from '.$this->db_prefix.'mib_cache WHERE oid=\''.$oid_instance.'\';';
400
-		$this->logging->log('SQL query : '.$sql,DEBUG );
400
+		$this->logging->log('SQL query : '.$sql, DEBUG);
401 401
 		if (($ret_code=$db_conn->query($sql)) === false) {
402
-			$this->logging->log('No result in query : ' . $sql,ERROR,'');
402
+			$this->logging->log('No result in query : '.$sql, ERROR, '');
403 403
 		}
404 404
 		$name=$ret_code->fetch();
405 405
 		if ($name['name'] != null)
406 406
 		{
407
-			return array('trap_name_mib'=>$name['mib'],'trap_name'=>$name['name']);
407
+			return array('trap_name_mib'=>$name['mib'], 'trap_name'=>$name['name']);
408 408
 		}
409 409
 		
410 410
 		// Try to get oid name from snmptranslate
411
-		$translate=exec($this->snmptranslate . ' -m ALL -M +'.$this->snmptranslate_dirs.
411
+		$translate=exec($this->snmptranslate.' -m ALL -M +'.$this->snmptranslate_dirs.
412 412
 		    ' '.$oid);
413 413
 		$matches=array();
414
-		$ret_code=preg_match('/(.*)::(.*)/',$translate,$matches);
415
-		if ($ret_code===0 || $ret_code === false) {
414
+		$ret_code=preg_match('/(.*)::(.*)/', $translate, $matches);
415
+		if ($ret_code === 0 || $ret_code === false) {
416 416
 			return NULL;
417 417
 		} else {
418
-			$this->logging->log('Found name with snmptrapd and not in DB for oid='.$oid,INFO);
419
-			return array('trap_name_mib'=>$matches[1],'trap_name'=>$matches[2]);
418
+			$this->logging->log('Found name with snmptrapd and not in DB for oid='.$oid, INFO);
419
+			return array('trap_name_mib'=>$matches[1], 'trap_name'=>$matches[2]);
420 420
 		}	
421 421
 	}
422 422
 	
@@ -427,90 +427,90 @@  discard block
 block discarded – undo
427 427
 	**/
428 428
 	public function eraseOldTraps($days=0)
429 429
 	{
430
-		if ($days==0)
430
+		if ($days == 0)
431 431
 		{
432 432
 			if (($days=$this->getDBConfig('db_remove_days')) == null)
433 433
 			{
434
-				$this->logging->log('No days specified & no db value : no tap erase' ,WARN,'');
434
+				$this->logging->log('No days specified & no db value : no tap erase', WARN, '');
435 435
 				return;
436 436
 			}
437 437
 		}
438 438
 		$db_conn=$this->trapsDB->db_connect_trap();
439
-		$daysago = strtotime("-".$days." day");
440
-		$sql= 'delete from '.$this->db_prefix.'received where date_received < \''.date("Y-m-d H:i:s",$daysago).'\';';
439
+		$daysago=strtotime("-".$days." day");
440
+		$sql='delete from '.$this->db_prefix.'received where date_received < \''.date("Y-m-d H:i:s", $daysago).'\';';
441 441
 		if ($db_conn->query($sql) === false) {
442
-			$this->logging->log('Error erasing traps : '.$sql,ERROR,'');
442
+			$this->logging->log('Error erasing traps : '.$sql, ERROR, '');
443 443
 		}
444
-		$this->logging->log('Erased traps older than '.$days.' day(s) : '.$sql,INFO);
444
+		$this->logging->log('Erased traps older than '.$days.' day(s) : '.$sql, INFO);
445 445
 	}
446 446
 
447 447
 	/** Write error to received trap database
448 448
 	 */
449
-	public function writeTrapErrorToDB($message,$sourceIP=null,$trapoid=null)
449
+	public function writeTrapErrorToDB($message, $sourceIP=null, $trapoid=null)
450 450
 	{
451 451
 	    
452 452
 	    $db_conn=$this->trapsDB->db_connect_trap();
453 453
 	    
454 454
 	    // add date time
455
-	    $insert_col ='date_received,status';
456
-	    $insert_val = "'" . date("Y-m-d H:i:s")."','error'";
455
+	    $insert_col='date_received,status';
456
+	    $insert_val="'".date("Y-m-d H:i:s")."','error'";
457 457
         
458
-	    if ($sourceIP !=null)
458
+	    if ($sourceIP != null)
459 459
 	    {
460
-	        $insert_col .=',source_ip';
461
-	        $insert_val .=",'". $sourceIP ."'";
460
+	        $insert_col.=',source_ip';
461
+	        $insert_val.=",'".$sourceIP."'";
462 462
 	    }
463
-	    if ($trapoid !=null)
463
+	    if ($trapoid != null)
464 464
 	    {
465
-	        $insert_col .=',trap_oid';
466
-	        $insert_val .=",'". $trapoid ."'";
465
+	        $insert_col.=',trap_oid';
466
+	        $insert_val.=",'".$trapoid."'";
467 467
 	    }
468
-	    $insert_col .=',status_detail';
469
-	    $insert_val .=",'". $message ."'";
468
+	    $insert_col.=',status_detail';
469
+	    $insert_val.=",'".$message."'";
470 470
 	    
471
-	    $sql= 'INSERT INTO '.$this->db_prefix.'received (' . $insert_col . ') VALUES ('.$insert_val.')';
471
+	    $sql='INSERT INTO '.$this->db_prefix.'received ('.$insert_col.') VALUES ('.$insert_val.')';
472 472
 	    
473 473
 	    switch ($this->trapsDB->trapDBType)
474 474
 	    {
475 475
 	        case 'pgsql':
476
-	            $sql .= ' RETURNING id;';
477
-	            $this->logging->log('sql : '.$sql,INFO);
476
+	            $sql.=' RETURNING id;';
477
+	            $this->logging->log('sql : '.$sql, INFO);
478 478
 	            if (($ret_code=$db_conn->query($sql)) === false) {
479
-	                $this->logging->log('Error SQL insert : '.$sql,1,'');
479
+	                $this->logging->log('Error SQL insert : '.$sql, 1, '');
480 480
 	            }
481
-	            $this->logging->log('SQL insertion OK',INFO );
481
+	            $this->logging->log('SQL insertion OK', INFO);
482 482
 	            // Get last id to insert oid/values in secondary table
483 483
 	            if (($inserted_id_ret=$ret_code->fetch(PDO::FETCH_ASSOC)) === false) {
484 484
 	                
485
-	                $this->logging->log('Erreur recuperation id',1,'');
485
+	                $this->logging->log('Erreur recuperation id', 1, '');
486 486
 	            }
487
-	            if (! isset($inserted_id_ret['id'])) {
488
-	                $this->logging->log('Error getting id',1,'');
487
+	            if (!isset($inserted_id_ret['id'])) {
488
+	                $this->logging->log('Error getting id', 1, '');
489 489
 	            }
490 490
 	            $this->trap_id=$inserted_id_ret['id'];
491 491
 	            break;
492 492
 	        case 'mysql':
493
-	            $sql .= ';';
494
-	            $this->logging->log('sql : '.$sql,INFO );
493
+	            $sql.=';';
494
+	            $this->logging->log('sql : '.$sql, INFO);
495 495
 	            if ($db_conn->query($sql) === false) {
496
-	                $this->logging->log('Error SQL insert : '.$sql,1,'');
496
+	                $this->logging->log('Error SQL insert : '.$sql, 1, '');
497 497
 	            }
498
-	            $this->logging->log('SQL insertion OK',INFO );
498
+	            $this->logging->log('SQL insertion OK', INFO);
499 499
 	            // Get last id to insert oid/values in secondary table
500 500
 	            $sql='SELECT LAST_INSERT_ID();';
501 501
 	            if (($ret_code=$db_conn->query($sql)) === false) {
502
-	                $this->logging->log('Erreur recuperation id',1,'');
502
+	                $this->logging->log('Erreur recuperation id', 1, '');
503 503
 	            }
504 504
 	            
505 505
 	            $inserted_id=$ret_code->fetch(PDO::FETCH_ASSOC)['LAST_INSERT_ID()'];
506
-	            if ($inserted_id==false) throw new Exception("Weird SQL error : last_insert_id returned false : open issue");
506
+	            if ($inserted_id == false) throw new Exception("Weird SQL error : last_insert_id returned false : open issue");
507 507
 	            $this->trap_id=$inserted_id;
508 508
 	            break;
509 509
 	        default:
510
-	            $this->logging->log('Error SQL type unknown  : '.$this->trapsDB->trapDBType,1,'');
510
+	            $this->logging->log('Error SQL type unknown  : '.$this->trapsDB->trapDBType, 1, '');
511 511
 	    }
512 512
 	    
513
-	    $this->logging->log('id found: '. $this->trap_id,INFO );    
513
+	    $this->logging->log('id found: '.$this->trap_id, INFO);    
514 514
 	}
515 515
 	
516 516
 	/** Write trap data to trap database
@@ -527,86 +527,86 @@  discard block
 block discarded – undo
527 527
 		$insert_col='';
528 528
 		$insert_val='';
529 529
 		// add date time
530
-		$this->trap_data['date_received'] = date("Y-m-d H:i:s");
530
+		$this->trap_data['date_received']=date("Y-m-d H:i:s");
531 531
 
532 532
 		$firstcol=1;
533 533
 		foreach ($this->trap_data as $col => $val)
534 534
 		{
535
-			if ($firstcol==0) 
535
+			if ($firstcol == 0) 
536 536
 			{
537
-				$insert_col .=',';
538
-				$insert_val .=',';
537
+				$insert_col.=',';
538
+				$insert_val.=',';
539 539
 			}
540
-			$insert_col .= $col ;
541
-			$insert_val .= ($val==null)? 'NULL' : $db_conn->quote($val);
540
+			$insert_col.=$col;
541
+			$insert_val.=($val == null) ? 'NULL' : $db_conn->quote($val);
542 542
 			$firstcol=0;
543 543
 		}
544 544
 		
545
-		$sql= 'INSERT INTO '.$this->db_prefix.'received (' . $insert_col . ') VALUES ('.$insert_val.')';
545
+		$sql='INSERT INTO '.$this->db_prefix.'received ('.$insert_col.') VALUES ('.$insert_val.')';
546 546
 		switch ($this->trapsDB->trapDBType)
547 547
 		{
548 548
 			case 'pgsql': 
549
-				$sql .= ' RETURNING id;';
550
-				$this->logging->log('sql : '.$sql,INFO );
549
+				$sql.=' RETURNING id;';
550
+				$this->logging->log('sql : '.$sql, INFO);
551 551
 				if (($ret_code=$db_conn->query($sql)) === false) {
552
-					$this->logging->log('Error SQL insert : '.$sql,ERROR,'');
552
+					$this->logging->log('Error SQL insert : '.$sql, ERROR, '');
553 553
 				}
554
-				$this->logging->log('SQL insertion OK',INFO );
554
+				$this->logging->log('SQL insertion OK', INFO);
555 555
 				// Get last id to insert oid/values in secondary table
556 556
 				if (($inserted_id_ret=$ret_code->fetch(PDO::FETCH_ASSOC)) === false) {
557 557
 														   
558
-					$this->logging->log('Erreur recuperation id',ERROR,'');
558
+					$this->logging->log('Erreur recuperation id', ERROR, '');
559 559
 				}
560
-				if (! isset($inserted_id_ret['id'])) {
561
-					$this->logging->log('Error getting id',ERROR,'');
560
+				if (!isset($inserted_id_ret['id'])) {
561
+					$this->logging->log('Error getting id', ERROR, '');
562 562
 				}
563 563
 				$this->trap_id=$inserted_id_ret['id'];
564 564
 			break;
565 565
 			case 'mysql': 
566
-				$sql .= ';';
567
-				$this->logging->log('sql : '.$sql,INFO );
566
+				$sql.=';';
567
+				$this->logging->log('sql : '.$sql, INFO);
568 568
 				if ($db_conn->query($sql) === false) {
569
-					$this->logging->log('Error SQL insert : '.$sql,ERROR,'');
569
+					$this->logging->log('Error SQL insert : '.$sql, ERROR, '');
570 570
 				}
571
-				$this->logging->log('SQL insertion OK',INFO );
571
+				$this->logging->log('SQL insertion OK', INFO);
572 572
 				// Get last id to insert oid/values in secondary table
573 573
 				$sql='SELECT LAST_INSERT_ID();';
574 574
 				if (($ret_code=$db_conn->query($sql)) === false) {
575
-					$this->logging->log('Erreur recuperation id',ERROR,'');
575
+					$this->logging->log('Erreur recuperation id', ERROR, '');
576 576
 				}
577 577
 
578 578
 				$inserted_id=$ret_code->fetch(PDO::FETCH_ASSOC)['LAST_INSERT_ID()'];
579
-				if ($inserted_id==false) throw new Exception("Weird SQL error : last_insert_id returned false : open issue");
579
+				if ($inserted_id == false) throw new Exception("Weird SQL error : last_insert_id returned false : open issue");
580 580
 				$this->trap_id=$inserted_id;
581 581
 			break;
582 582
 			default: 
583
-				$this->logging->log('Error SQL type unknown : '.$this->trapsDB->trapDBType,ERROR,'');
583
+				$this->logging->log('Error SQL type unknown : '.$this->trapsDB->trapDBType, ERROR, '');
584 584
 		}
585
-		$this->logging->log('id found: '.$this->trap_id,INFO );
585
+		$this->logging->log('id found: '.$this->trap_id, INFO);
586 586
 		
587 587
 		// Fill trap extended data table
588 588
 		foreach ($this->trap_data_ext as $value) {			
589 589
 			// TODO : detect if trap value is encoded and decode it to UTF-8 for database
590 590
 			$firstcol=1;
591
-			$value->trap_id = $this->trap_id;
591
+			$value->trap_id=$this->trap_id;
592 592
 			$insert_col='';
593 593
 			$insert_val='';
594 594
 			foreach ($value as $col => $val)
595 595
 			{
596
-				if ($firstcol==0) 
596
+				if ($firstcol == 0) 
597 597
 				{
598
-					$insert_col .=',';
599
-					$insert_val .=',';
598
+					$insert_col.=',';
599
+					$insert_val.=',';
600 600
 				}
601
-				$insert_col .= $col;
602
-				$insert_val .= ($val==null)? 'NULL' : $db_conn->quote($val);
601
+				$insert_col.=$col;
602
+				$insert_val.=($val == null) ? 'NULL' : $db_conn->quote($val);
603 603
 				$firstcol=0;
604 604
 			}
605 605
 
606
-			$sql= 'INSERT INTO '.$this->db_prefix.'received_data (' . $insert_col . ') VALUES ('.$insert_val.');';			
606
+			$sql='INSERT INTO '.$this->db_prefix.'received_data ('.$insert_col.') VALUES ('.$insert_val.');';			
607 607
 
608 608
 			if ($db_conn->query($sql) === false) {
609
-				$this->logging->log('Erreur insertion data : ' . $sql,WARN,'');
609
+				$this->logging->log('Erreur insertion data : '.$sql, WARN, '');
610 610
 			}	
611 611
 		}	
612 612
 	}
@@ -616,14 +616,14 @@  discard block
 block discarded – undo
616 616
 	*	@param $oid string oid in numeric
617 617
 	*	@return mixed : PDO object or false
618 618
 	*/	
619
-	protected function getRules($ip,$oid)
619
+	protected function getRules($ip, $oid)
620 620
 	{
621 621
 		$db_conn=$this->trapsDB->db_connect_trap();
622 622
 		// fetch rules based on IP in rule and OID
623 623
 		$sql='SELECT * from '.$this->db_prefix.'rules WHERE trap_oid=\''.$oid.'\' ';
624
-		$this->logging->log('SQL query : '.$sql,DEBUG );
624
+		$this->logging->log('SQL query : '.$sql, DEBUG);
625 625
 		if (($ret_code=$db_conn->query($sql)) === false) {
626
-			$this->logging->log('No result in query : ' . $sql,WARN,'');
626
+			$this->logging->log('No result in query : '.$sql, WARN, '');
627 627
 			return false;
628 628
 		}
629 629
 		$rules_all=$ret_code->fetchAll();
@@ -632,7 +632,7 @@  discard block
 block discarded – undo
632 632
 		$rule_ret_key=0;
633 633
 		foreach ($rules_all as $key => $rule)
634 634
 		{
635
-			if ($rule['ip4']==$ip || $rule['ip6']==$ip)
635
+			if ($rule['ip4'] == $ip || $rule['ip6'] == $ip)
636 636
 			{
637 637
 				$rules_ret[$rule_ret_key]=$rules_all[$key];
638 638
 				//TODO : get host name by API (and check if correct in rule).
@@ -640,7 +640,7 @@  discard block
 block discarded – undo
640 640
 				continue;
641 641
 			}
642 642
 			// TODO : get hosts IP by API
643
-			if (isset($rule['host_group_name']) && $rule['host_group_name']!=null)
643
+			if (isset($rule['host_group_name']) && $rule['host_group_name'] != null)
644 644
 			{ // get ips of group members by oid
645 645
 				$db_conn2=$this->trapsDB->db_connect_ido();
646 646
 				$sql="SELECT m.host_object_id, a.address as ip4, a.address6 as ip6, b.name1 as host_name
@@ -651,15 +651,15 @@  discard block
 block discarded – undo
651 651
 						LEFT JOIN icinga_objects as b ON b.object_id = a.host_object_id
652 652
 						WHERE o.name1='".$rule['host_group_name']."';";
653 653
 				if (($ret_code2=$db_conn2->query($sql)) === false) {
654
-					$this->logging->log('No result in query : ' . $sql,WARN,'');
654
+					$this->logging->log('No result in query : '.$sql, WARN, '');
655 655
 					continue;
656 656
 				}
657 657
 				$grouphosts=$ret_code2->fetchAll();
658 658
 				//echo "rule grp :\n";print_r($grouphosts);echo "\n";
659
-				foreach ( $grouphosts as $host)
659
+				foreach ($grouphosts as $host)
660 660
 				{
661 661
 					//echo $host['ip4']."\n";
662
-					if ($host['ip4']==$ip || $host['ip6']==$ip)
662
+					if ($host['ip4'] == $ip || $host['ip6'] == $ip)
663 663
 					{
664 664
 						//echo "Rule added \n";
665 665
 						$rules_ret[$rule_ret_key]=$rules_all[$key];
@@ -682,7 +682,7 @@  discard block
 block discarded – undo
682 682
 		$db_conn=$this->trapsDB->db_connect_trap();
683 683
 		$sql="UPDATE ".$this->db_prefix."rules SET num_match = '".$set."' WHERE (id = '".$id."');";
684 684
 		if ($db_conn->query($sql) === false) {
685
-			$this->logging->log('Error in update query : ' . $sql,WARN,'');
685
+			$this->logging->log('Error in update query : '.$sql, WARN, '');
686 686
 		}
687 687
 	}
688 688
 	
@@ -694,31 +694,31 @@  discard block
 block discarded – undo
694 694
 	 * @param string $display
695 695
 	 * @returnn bool true is service check was sent without error
696 696
 	*/
697
-	public function serviceCheckResult($host,$service,$state,$display)
697
+	public function serviceCheckResult($host, $service, $state, $display)
698 698
 	{
699 699
 	    if ($this->api_use === false)
700 700
 	    {
701
-    		$send = '[' . date('U') .'] PROCESS_SERVICE_CHECK_RESULT;' .
702
-    			$host.';' .$service .';' . $state . ';'.$display;
703
-    		$this->logging->log( $send." : to : " .$this->icinga2cmd,INFO );
701
+    		$send='['.date('U').'] PROCESS_SERVICE_CHECK_RESULT;'.
702
+    			$host.';'.$service.';'.$state.';'.$display;
703
+    		$this->logging->log($send." : to : ".$this->icinga2cmd, INFO);
704 704
     		
705 705
     		// TODO : file_put_contents & fopen (,'w' or 'a') does not work. See why. Or not as using API will be by default....
706
-    		exec('echo "'.$send.'" > ' .$this->icinga2cmd);
706
+    		exec('echo "'.$send.'" > '.$this->icinga2cmd);
707 707
     		return true;
708 708
 	    }
709 709
 	    else
710 710
 	    {
711
-	        $api = $this->getAPI();
711
+	        $api=$this->getAPI();
712 712
 	        $api->setCredentials($this->api_username, $this->api_password);
713
-	        list($retcode,$retmessage)=$api->serviceCheckResult($host,$service,$state,$display);
713
+	        list($retcode, $retmessage)=$api->serviceCheckResult($host, $service, $state, $display);
714 714
 	        if ($retcode == false)
715 715
 	        {
716
-	            $this->logging->log( "Error sending result : " .$retmessage,WARN,'');
716
+	            $this->logging->log("Error sending result : ".$retmessage, WARN, '');
717 717
 	            return false;
718 718
 	        }
719 719
 	        else 
720 720
 	        {
721
-	            $this->logging->log( "Sent result : " .$retmessage,INFO );
721
+	            $this->logging->log("Sent result : ".$retmessage, INFO);
722 722
 	            return true;
723 723
 	        }
724 724
 	    }
@@ -726,7 +726,7 @@  discard block
 block discarded – undo
726 726
 	
727 727
 	public function getHostByIP($ip)
728 728
 	{
729
-	    $api = $this->getAPI();
729
+	    $api=$this->getAPI();
730 730
 	    $api->setCredentials($this->api_username, $this->api_password);
731 731
 	    return $api->getHostByIP($ip);
732 732
 	}
@@ -739,32 +739,32 @@  discard block
 block discarded – undo
739 739
 	protected function applyDisplay($display)
740 740
 	{
741 741
 	    $matches=array();
742
-	    while (preg_match('/_OID\(([0-9\.]+)\)/',$display,$matches) == 1)
742
+	    while (preg_match('/_OID\(([0-9\.]+)\)/', $display, $matches) == 1)
743 743
 		{
744 744
 			$oid=$matches[1];
745 745
 			$found=0;
746
-			foreach($this->trap_data_ext as $val)
746
+			foreach ($this->trap_data_ext as $val)
747 747
 			{
748 748
 				if ($oid == $val->oid)
749 749
 				{
750
-					$val->value=preg_replace('/"/','',$val->value);
750
+					$val->value=preg_replace('/"/', '', $val->value);
751 751
 					$rep=0;
752
-					$display=preg_replace('/_OID\('.$oid.'\)/',$val->value,$display,-1,$rep);
753
-					if ($rep==0)
752
+					$display=preg_replace('/_OID\('.$oid.'\)/', $val->value, $display, -1, $rep);
753
+					if ($rep == 0)
754 754
 					{
755
-						$this->logging->log("Error in display",WARN,'');
755
+						$this->logging->log("Error in display", WARN, '');
756 756
 						return $display;
757 757
 					}
758 758
 					$found=1;
759 759
 					break;
760 760
 				}
761 761
 			}
762
-			if ($found==0)
762
+			if ($found == 0)
763 763
 			{
764
-				$display=preg_replace('/_OID\('.$oid.'\)/','<not in trap>',$display,-1,$rep);
765
-				if ($rep==0)
764
+				$display=preg_replace('/_OID\('.$oid.'\)/', '<not in trap>', $display, -1, $rep);
765
+				if ($rep == 0)
766 766
 				{
767
-					$this->logging->log("Error in display",WARN,'');
767
+					$this->logging->log("Error in display", WARN, '');
768 768
 					return $display;
769 769
 				}				
770 770
 			}
@@ -776,11 +776,11 @@  discard block
 block discarded – undo
776 776
 	*/
777 777
 	public function applyRules()
778 778
 	{
779
-		$rules = $this->getRules($this->trap_data['source_ip'],$this->trap_data['trap_oid']);
779
+		$rules=$this->getRules($this->trap_data['source_ip'], $this->trap_data['trap_oid']);
780 780
 		
781
-		if ($rules===false || count($rules)==0)
781
+		if ($rules === false || count($rules) == 0)
782 782
 		{
783
-			$this->logging->log('No rules found for this trap',INFO );
783
+			$this->logging->log('No rules found for this trap', INFO);
784 784
 			$this->trap_data['status']='unknown';
785 785
 			$this->trap_to_db=true;
786 786
 			return;
@@ -795,59 +795,59 @@  discard block
 block discarded – undo
795 795
 			$service_name=$rule['service_name'];
796 796
 			
797 797
 			$display=$this->applyDisplay($rule['display']);
798
-			$this->trap_action = ($this->trap_action==null)? '' : $this->trap_action . ', ';
798
+			$this->trap_action=($this->trap_action == null) ? '' : $this->trap_action.', ';
799 799
 			try
800 800
 			{
801
-				$this->logging->log('Rule to eval : '.$rule['rule'],INFO );
802
-				$evalr=$this->ruleClass->eval_rule($rule['rule'], $this->trap_data_ext) ;
801
+				$this->logging->log('Rule to eval : '.$rule['rule'], INFO);
802
+				$evalr=$this->ruleClass->eval_rule($rule['rule'], $this->trap_data_ext);
803 803
 				//->eval_rule($rule['rule']);
804 804
 				
805 805
 				if ($evalr == true)
806 806
 				{
807 807
 					//$this->logging->log('rules OOK: '.print_r($rule),INFO );
808 808
 					$action=$rule['action_match'];
809
-					$this->logging->log('action OK : '.$action,INFO );
809
+					$this->logging->log('action OK : '.$action, INFO);
810 810
 					if ($action >= 0)
811 811
 					{
812
-						if ($this->serviceCheckResult($host_name,$service_name,$action,$display) == false)
812
+						if ($this->serviceCheckResult($host_name, $service_name, $action, $display) == false)
813 813
 						{
814 814
 						    $this->trap_action.='Error sending status : check cmd/API';
815 815
 						}
816 816
 						else
817 817
 						{
818
-						    $this->add_rule_match($rule['id'],$rule['num_match']+1);
818
+						    $this->add_rule_match($rule['id'], $rule['num_match'] + 1);
819 819
 						    $this->trap_action.='Status '.$action.' to '.$host_name.'/'.$service_name;
820 820
 						}
821 821
 					}
822 822
 					else
823 823
 					{
824
-						$this->add_rule_match($rule['id'],$rule['num_match']+1);
824
+						$this->add_rule_match($rule['id'], $rule['num_match'] + 1);
825 825
 					}
826
-					$this->trap_to_db=($action==-2)?false:true;
826
+					$this->trap_to_db=($action == -2) ?false:true;
827 827
 				}
828 828
 				else
829 829
 				{
830 830
 					//$this->logging->log('rules KOO : '.print_r($rule),INFO );
831 831
 					
832 832
 					$action=$rule['action_nomatch'];
833
-					$this->logging->log('action NOK : '.$action,INFO );
833
+					$this->logging->log('action NOK : '.$action, INFO);
834 834
 					if ($action >= 0)
835 835
 					{
836
-					    if ($this->serviceCheckResult($host_name,$service_name,$action,$display)==false)
836
+					    if ($this->serviceCheckResult($host_name, $service_name, $action, $display) == false)
837 837
 					    {
838 838
 					        $this->trap_action.='Error sending status : check cmd/API';
839 839
 					    }
840 840
 					    else
841 841
 					    {
842
-    						$this->add_rule_match($rule['id'],$rule['num_match']+1);
842
+    						$this->add_rule_match($rule['id'], $rule['num_match'] + 1);
843 843
     						$this->trap_action.='Status '.$action.' to '.$host_name.'/'.$service_name;
844 844
 					    }
845 845
 					}
846 846
 					else
847 847
 					{
848
-						$this->add_rule_match($rule['id'],$rule['num_match']+1);
848
+						$this->add_rule_match($rule['id'], $rule['num_match'] + 1);
849 849
 					}
850
-					$this->trap_to_db=($action==-2)?false:true;					
850
+					$this->trap_to_db=($action == -2) ?false:true;					
851 851
 				}
852 852
 				// Put name in source_name
853 853
 				if (!isset($this->trap_data['source_name']))
@@ -856,7 +856,7 @@  discard block
 block discarded – undo
856 856
 				}
857 857
 				else
858 858
 				{
859
-					if (!preg_match('/'.$rule['host_name'].'/',$this->trap_data['source_name']))
859
+					if (!preg_match('/'.$rule['host_name'].'/', $this->trap_data['source_name']))
860 860
 					{ // only add if not present
861 861
 						$this->trap_data['source_name'].=','.$rule['host_name'];
862 862
 					}
@@ -864,13 +864,13 @@  discard block
 block discarded – undo
864 864
 			}
865 865
 			catch (Exception $e) 
866 866
 			{ 
867
-			    $this->logging->log('Error in rule eval : '.$e->getMessage(),WARN,'');
867
+			    $this->logging->log('Error in rule eval : '.$e->getMessage(), WARN, '');
868 868
 			    $this->trap_action.=' ERR : '.$e->getMessage();
869 869
 			    $this->trap_data['status']='error';
870 870
 			}
871 871
 			
872 872
 		}
873
-		if ($this->trap_data['status']=='error')
873
+		if ($this->trap_data['status'] == 'error')
874 874
 		{
875 875
 		  $this->trap_to_db=true; // Always put errors in DB for the use can see
876 876
 		}
@@ -886,13 +886,13 @@  discard block
 block discarded – undo
886 886
 	public function add_rule_final($time)
887 887
 	{
888 888
 		$db_conn=$this->trapsDB->db_connect_trap();
889
-		if ($this->trap_action==null) 
889
+		if ($this->trap_action == null) 
890 890
 		{
891 891
 			$this->trap_action='No action';
892 892
 		}
893 893
 		$sql="UPDATE ".$this->db_prefix."received SET process_time = '".$time."' , status_detail='".$this->trap_action."'  WHERE (id = '".$this->trap_id."');";
894 894
 		if ($db_conn->query($sql) === false) {
895
-			$this->logging->log('Error in update query : ' . $sql,WARN,'');
895
+			$this->logging->log('Error in update query : '.$sql, WARN, '');
896 896
 		}
897 897
 	}
898 898
 	
@@ -915,7 +915,7 @@  discard block
 block discarded – undo
915 915
     WHERE s.current_state != 0;";
916 916
 		$db_conn=$this->trapsDB->db_connect_ido();
917 917
 		if (($services_db=$db_conn->query($sql_query)) === false) { // set err to 1 to throw exception.
918
-			$this->logging->log('No result in query : ' . $sql_query,ERROR,'');
918
+			$this->logging->log('No result in query : '.$sql_query, ERROR, '');
919 919
 			return 0;
920 920
 		}
921 921
 		$services=$services_db->fetchAll();
@@ -924,7 +924,7 @@  discard block
 block discarded – undo
924 924
 		$sql_query="SELECT host_name, service_name, revert_ok FROM ".$this->db_prefix."rules where revert_ok != 0;";
925 925
 		$db_conn2=$this->trapsDB->db_connect_trap();
926 926
 		if (($rules_db=$db_conn2->query($sql_query)) === false) {
927
-			$this->logging->log('No result in query : ' . $sql_query,ERROR,'');
927
+			$this->logging->log('No result in query : '.$sql_query, ERROR, '');
928 928
 			return 0;
929 929
 		}
930 930
 		$rules=$rules_db->fetchAll();
@@ -940,13 +940,13 @@  discard block
 block discarded – undo
940 940
 					$service['host_name'] == $rule['host_name'] &&
941 941
 					($service['last_check'] + $rule['revert_ok']) < $now)
942 942
 				{
943
-					$this->serviceCheckResult($service['host_name'],$service['service_name'],0,'Reset service to OK after '.$rule['revert_ok'].' seconds');
943
+					$this->serviceCheckResult($service['host_name'], $service['service_name'], 0, 'Reset service to OK after '.$rule['revert_ok'].' seconds');
944 944
 					$numreset++;
945 945
 				}
946 946
 			}
947 947
 		}
948 948
 		echo "\n";
949
-		echo $numreset . " service(s) reset to OK\n";
949
+		echo $numreset." service(s) reset to OK\n";
950 950
 		return 0;
951 951
 		
952 952
 	}
Please login to merge, or discard this patch.
Braces   +39 added lines, -37 removed lines patch added patch discarded remove patch
@@ -69,9 +69,9 @@  discard block
 block discarded – undo
69 69
 		{
70 70
 		    $this->logging->setLogging($baseLogLevel, $baseLogMode,$baseLogFile);
71 71
 		    $this->logSetup=true;
72
+		} else {
73
+				    $this->logSetup=false;
72 74
 		}
73
-		else
74
-		    $this->logSetup=false;
75 75
 		$this->logging->log('Loggin started', INFO);
76 76
 
77 77
 		// Get options from ini files
@@ -84,7 +84,10 @@  discard block
 block discarded – undo
84 84
 		$this->setupDatabase($trapConfig); // Setup database class
85 85
 		
86 86
 		$this->getDatabaseOptions(); // Get options in database
87
-		if ($this->api_use === true) $this->getAPI(); // Setup API
87
+		if ($this->api_use === true) {
88
+			$this->getAPI();
89
+		}
90
+		// Setup API
88 91
 		
89 92
 		$this->mibClass = new Mib($this->logging,$this->trapsDB,$this->snmptranslate,$this->snmptranslate_dirs); // Create Mib class
90 93
 		
@@ -120,8 +123,7 @@  discard block
 block discarded – undo
120 123
 	        }
121 124
 	        $this->logging->log($message,$log_level,'syslog');
122 125
 	        return false;
123
-	    }
124
-	    else
126
+	    } else
125 127
 	    {
126 128
 	        $option_var=$option_array[$option_category][$option_name];
127 129
 	        return true;
@@ -185,7 +187,10 @@  discard block
 block discarded – undo
185 187
 	    
186 188
 	    $this->trapsDB = new Database($this->logging,$dbConfig[$dbTrapName],$this->db_prefix);
187 189
 	    
188
-	    if ($this->api_use === true) return; // In case of API use, no IDO is necessary
190
+	    if ($this->api_use === true) {
191
+	    	return;
192
+	    }
193
+	    // In case of API use, no IDO is necessary
189 194
         
190 195
 	    // IDO Database
191 196
 	    if (!array_key_exists('IDOdatabase',$trapConfig['config']))
@@ -210,9 +215,11 @@  discard block
 block discarded – undo
210 215
 	protected function getDatabaseOptions()
211 216
 	{
212 217
 		// Database options
213
-		if ($this->logSetup === false) // Only if logging was no setup in constructor
218
+		if ($this->logSetup === false) {
219
+			// Only if logging was no setup in constructor
214 220
 		{
215 221
     		$this->getDBConfigIfSet('log_level',$this->logging->debugLevel);
222
+		}
216 223
     		$this->getDBConfigIfSet('log_destination',$this->logging->outputMode);
217 224
     		$this->getDBConfigIfSet('log_file',$this->logging->outputFile);
218 225
 		}
@@ -221,7 +228,9 @@  discard block
 block discarded – undo
221 228
 	protected function getDBConfigIfSet($element,&$variable)
222 229
 	{
223 230
 		$value=$this->getDBConfig($element);
224
-		if ($value != 'null') $variable=$value;
231
+		if ($value != 'null') {
232
+			$variable=$value;
233
+		}
225 234
 	}
226 235
 	
227 236
 	/** 
@@ -309,8 +318,7 @@  discard block
 block discarded – undo
309 318
 		{
310 319
 		    $this->writeTrapErrorToDB("Error parsing trap (code 2/IP)");
311 320
 			$this->logging->log('Error parsing IP : '.$IP,ERROR,'');
312
-		} 
313
-		else 
321
+		} else 
314 322
 		{		
315 323
 			$this->trap_data['source_ip']=$matches[1];
316 324
 			$this->trap_data['destination_ip']=$matches[3];
@@ -325,14 +333,12 @@  discard block
 block discarded – undo
325 333
 			if ($ret_code===0 || $ret_code===false) 
326 334
 			{
327 335
 				$this->logging->log('No match on trap data : '.$vars,WARN,'');
328
-			}
329
-			else 
336
+			} else 
330 337
 			{
331 338
 			    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'))
332 339
 				{
333 340
 					$this->trap_data['trap_oid']=$matches[2];				
334
-				}
335
-				else
341
+				} else
336 342
 				{
337 343
 					$object= new stdClass;
338 344
 					$object->oid =$matches[1];
@@ -503,7 +509,9 @@  discard block
 block discarded – undo
503 509
 	            }
504 510
 	            
505 511
 	            $inserted_id=$ret_code->fetch(PDO::FETCH_ASSOC)['LAST_INSERT_ID()'];
506
-	            if ($inserted_id==false) throw new Exception("Weird SQL error : last_insert_id returned false : open issue");
512
+	            if ($inserted_id==false) {
513
+	            	throw new Exception("Weird SQL error : last_insert_id returned false : open issue");
514
+	            }
507 515
 	            $this->trap_id=$inserted_id;
508 516
 	            break;
509 517
 	        default:
@@ -519,7 +527,9 @@  discard block
 block discarded – undo
519 527
 	{
520 528
 		
521 529
 		// If action is ignore -> don't send t DB
522
-		if ($this->trap_to_db === false) return;
530
+		if ($this->trap_to_db === false) {
531
+			return;
532
+		}
523 533
 		
524 534
 		
525 535
 		$db_conn=$this->trapsDB->db_connect_trap();
@@ -576,7 +586,9 @@  discard block
 block discarded – undo
576 586
 				}
577 587
 
578 588
 				$inserted_id=$ret_code->fetch(PDO::FETCH_ASSOC)['LAST_INSERT_ID()'];
579
-				if ($inserted_id==false) throw new Exception("Weird SQL error : last_insert_id returned false : open issue");
589
+				if ($inserted_id==false) {
590
+					throw new Exception("Weird SQL error : last_insert_id returned false : open issue");
591
+				}
580 592
 				$this->trap_id=$inserted_id;
581 593
 			break;
582 594
 			default: 
@@ -705,8 +717,7 @@  discard block
 block discarded – undo
705 717
     		// TODO : file_put_contents & fopen (,'w' or 'a') does not work. See why. Or not as using API will be by default....
706 718
     		exec('echo "'.$send.'" > ' .$this->icinga2cmd);
707 719
     		return true;
708
-	    }
709
-	    else
720
+	    } else
710 721
 	    {
711 722
 	        $api = $this->getAPI();
712 723
 	        $api->setCredentials($this->api_username, $this->api_password);
@@ -715,8 +726,7 @@  discard block
 block discarded – undo
715 726
 	        {
716 727
 	            $this->logging->log( "Error sending result : " .$retmessage,WARN,'');
717 728
 	            return false;
718
-	        }
719
-	        else 
729
+	        } else 
720 730
 	        {
721 731
 	            $this->logging->log( "Sent result : " .$retmessage,INFO );
722 732
 	            return true;
@@ -812,20 +822,17 @@  discard block
 block discarded – undo
812 822
 						if ($this->serviceCheckResult($host_name,$service_name,$action,$display) == false)
813 823
 						{
814 824
 						    $this->trap_action.='Error sending status : check cmd/API';
815
-						}
816
-						else
825
+						} else
817 826
 						{
818 827
 						    $this->add_rule_match($rule['id'],$rule['num_match']+1);
819 828
 						    $this->trap_action.='Status '.$action.' to '.$host_name.'/'.$service_name;
820 829
 						}
821
-					}
822
-					else
830
+					} else
823 831
 					{
824 832
 						$this->add_rule_match($rule['id'],$rule['num_match']+1);
825 833
 					}
826 834
 					$this->trap_to_db=($action==-2)?false:true;
827
-				}
828
-				else
835
+				} else
829 836
 				{
830 837
 					//$this->logging->log('rules KOO : '.print_r($rule),INFO );
831 838
 					
@@ -836,14 +843,12 @@  discard block
 block discarded – undo
836 843
 					    if ($this->serviceCheckResult($host_name,$service_name,$action,$display)==false)
837 844
 					    {
838 845
 					        $this->trap_action.='Error sending status : check cmd/API';
839
-					    }
840
-					    else
846
+					    } else
841 847
 					    {
842 848
     						$this->add_rule_match($rule['id'],$rule['num_match']+1);
843 849
     						$this->trap_action.='Status '.$action.' to '.$host_name.'/'.$service_name;
844 850
 					    }
845
-					}
846
-					else
851
+					} else
847 852
 					{
848 853
 						$this->add_rule_match($rule['id'],$rule['num_match']+1);
849 854
 					}
@@ -853,16 +858,14 @@  discard block
 block discarded – undo
853 858
 				if (!isset($this->trap_data['source_name']))
854 859
 				{
855 860
 					$this->trap_data['source_name']=$rule['host_name'];
856
-				}
857
-				else
861
+				} else
858 862
 				{
859 863
 					if (!preg_match('/'.$rule['host_name'].'/',$this->trap_data['source_name']))
860 864
 					{ // only add if not present
861 865
 						$this->trap_data['source_name'].=','.$rule['host_name'];
862 866
 					}
863 867
 				}
864
-			}
865
-			catch (Exception $e) 
868
+			} catch (Exception $e) 
866 869
 			{ 
867 870
 			    $this->logging->log('Error in rule eval : '.$e->getMessage(),WARN,'');
868 871
 			    $this->trap_action.=' ERR : '.$e->getMessage();
@@ -873,8 +876,7 @@  discard block
 block discarded – undo
873 876
 		if ($this->trap_data['status']=='error')
874 877
 		{
875 878
 		  $this->trap_to_db=true; // Always put errors in DB for the use can see
876
-		}
877
-		else
879
+		} else
878 880
 		{
879 881
 		  $this->trap_data['status']='done';
880 882
 		}
Please login to merge, or discard this patch.
tests/expr_test.php 2 patches
Spacing   +10 added lines, -10 removed lines patch added patch discarded remove patch
@@ -3,18 +3,18 @@  discard block
 block discarded – undo
3 3
 
4 4
 require_once 'bin/trap_class.php';
5 5
 
6
-$options = getopt("r:d:");
6
+$options=getopt("r:d:");
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);
13
-$trap->setLogging($debugLevel,'display');
12
+$trap=new trap($icingaweb2Etc);
13
+$trap->setLogging($debugLevel, 'display');
14 14
 
15
-$input=array_key_exists('r',$options);
15
+$input=array_key_exists('r', $options);
16 16
 
17
-if (! $input) {
17
+if (!$input) {
18 18
   $inputStream=fopen('php://stdin', 'r');
19 19
   $rule=chop(fgets($inputStream));
20 20
 } else
@@ -25,11 +25,11 @@  discard block
 block discarded – undo
25 25
   $rule=$trap->ruleClass->eval_cleanup($rule);
26 26
   //echo 'After cleanup : #'.$rule."#\n";
27 27
   $item=0;
28
-  $val = $trap->ruleClass->evaluation($rule,$item);
29
-  if ($val==true) { printf( "true"); } else { printf( "false");}
28
+  $val=$trap->ruleClass->evaluation($rule, $item);
29
+  if ($val == true) { printf("true"); } else { printf("false"); }
30 30
   printf("\n");
31 31
 }
32
-catch (Exception $e) { printf("%s\n",$e->getMessage()); exit(1);}
32
+catch (Exception $e) { printf("%s\n", $e->getMessage()); exit(1); }
33 33
 
34 34
 exit(0);
35 35
 ?>
Please login to merge, or discard this patch.
Braces   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -17,8 +17,9 @@  discard block
 block discarded – undo
17 17
 if (! $input) {
18 18
   $inputStream=fopen('php://stdin', 'r');
19 19
   $rule=chop(fgets($inputStream));
20
-} else
20
+} else {
21 21
   $rule=$options['r'];
22
+}
22 23
 
23 24
 try
24 25
 {
@@ -28,8 +29,7 @@  discard block
 block discarded – undo
28 29
   $val = $trap->ruleClass->evaluation($rule,$item);
29 30
   if ($val==true) { printf( "true"); } else { printf( "false");}
30 31
   printf("\n");
31
-}
32
-catch (Exception $e) { printf("%s\n",$e->getMessage()); exit(1);}
32
+} catch (Exception $e) { printf("%s\n",$e->getMessage()); exit(1);}
33 33
 
34 34
 exit(0);
35 35
 ?>
Please login to merge, or discard this patch.
application/controllers/HelperController.php 3 patches
Indentation   +84 added lines, -84 removed lines patch added patch discarded remove patch
@@ -12,8 +12,8 @@  discard block
 block discarded – undo
12 12
 {
13 13
 	
14 14
 	/** Get host list with filter (IP or name) : host=<filter>
15
-	*	returns in JSON : status=>OK/NOK  hosts=>array of hosts
16
-	*/
15
+	 *	returns in JSON : status=>OK/NOK  hosts=>array of hosts
16
+	 */
17 17
 	public function gethostsAction()
18 18
 	{
19 19
 		$postData=$this->getRequest()->getPost();
@@ -40,8 +40,8 @@  discard block
 block discarded – undo
40 40
 
41 41
 	
42 42
 	/** Get hostgroup list with filter (name) : hostgroup=<hostFilter>
43
-	*	returns in JSON : status=>OK/NOK  hosts=>array of hosts
44
-	*/
43
+	 *	returns in JSON : status=>OK/NOK  hosts=>array of hosts
44
+	 */
45 45
 	public function gethostgroupsAction()
46 46
 	{
47 47
 		$postData=$this->getRequest()->getPost();
@@ -68,11 +68,11 @@  discard block
 block discarded – undo
68 68
 
69 69
 	
70 70
 	/** Get service list by host name ( host=<host> )
71
-	*	returns in JSON : 
72
-	*		status=>OK/No services found/More than one host matches
73
-	*		services=>array of services (name)
74
-	*		hostid = host object id or -1 if not found.
75
-	*/
71
+	 *	returns in JSON : 
72
+	 *		status=>OK/No services found/More than one host matches
73
+	 *		services=>array of services (name)
74
+	 *		hostid = host object id or -1 if not found.
75
+	 */
76 76
 	public function getservicesAction()
77 77
 	{
78 78
 		$postData=$this->getRequest()->getPost();
@@ -112,11 +112,11 @@  discard block
 block discarded – undo
112 112
 	}
113 113
 	
114 114
 	/** Get service list by host group ( name=<host> )
115
-	*	returns in JSON : 
116
-	*		status=>OK/No services found/More than one host matches
117
-	*		services=>array of services (name)
118
-	*		groupid = group object id or -1 if not found.
119
-	*/
115
+	 *	returns in JSON : 
116
+	 *		status=>OK/No services found/More than one host matches
117
+	 *		services=>array of services (name)
118
+	 *		groupid = group object id or -1 if not found.
119
+	 */
120 120
 	public function gethostgroupservicesAction()
121 121
 	{
122 122
 		$postData=$this->getRequest()->getPost();
@@ -153,10 +153,10 @@  discard block
 block discarded – undo
153 153
 	}
154 154
 
155 155
 	/** Get traps from mib  : entry : mib=<mib>
156
-	*	returns in JSON : 
157
-	*		status=>OK/No mib/Error getting mibs
158
-	*		traps=>array of array( oid -> name)
159
-	*/
156
+	 *	returns in JSON : 
157
+	 *		status=>OK/No mib/Error getting mibs
158
+	 *		traps=>array of array( oid -> name)
159
+	 */
160 160
 	public function gettrapsAction()
161 161
 	{
162 162
 		$postData=$this->getRequest()->getPost();
@@ -182,10 +182,10 @@  discard block
 block discarded – undo
182 182
 	}	
183 183
 
184 184
 	/** Get trap objects from mib  : entry : trap=<oid>
185
-	*	returns in JSON : 
186
-	*		status=>OK/no trap/not found
187
-	*		objects=>array of array( oid -> name, oid->mib)
188
-	*/
185
+	 *	returns in JSON : 
186
+	 *		status=>OK/no trap/not found
187
+	 *		objects=>array of array( oid -> name, oid->mib)
188
+	 */
189 189
 	public function gettrapobjectsAction()
190 190
 	{
191 191
 		$postData=$this->getRequest()->getPost();
@@ -211,8 +211,8 @@  discard block
 block discarded – undo
211 211
 	}	
212 212
 	
213 213
 	/** Get list of all loaded mibs : entry : none
214
-	*	return : array of strings.
215
-	*/
214
+	 *	return : array of strings.
215
+	 */
216 216
 	public function getmiblistAction()
217 217
 	{
218 218
 		try
@@ -227,10 +227,10 @@  discard block
 block discarded – undo
227 227
 	}
228 228
 	
229 229
 	/** Get MIB::Name from OID : entry : oid
230
-	*		status=>OK/No oid/not found
231
-	*		mib=>string
232
-	*		name=>string
233
-	*/	
230
+	 *		status=>OK/No oid/not found
231
+	 *		mib=>string
232
+	 *		name=>string
233
+	 */	
234 234
 	public function translateoidAction()
235 235
 	{
236 236
 		$postData=$this->getRequest()->getPost();
@@ -258,7 +258,7 @@  discard block
 block discarded – undo
258 258
 					'name' => $object['name'],
259 259
 					'type' => $object['type'],
260 260
 					'type_enum' => $object['type_enum'],
261
-				    'description' => $object['description']
261
+					'description' => $object['description']
262 262
 				)
263 263
 			);
264 264
 		}
@@ -267,10 +267,10 @@  discard block
 block discarded – undo
267 267
 
268 268
 	
269 269
 	/** Save or execute database purge of <n> days
270
-	*	days=>int 
271
-	*	action=>save/execute
272
-	*	return : status=>OK/Message error
273
-	*/
270
+	 *	days=>int 
271
+	 *	action=>save/execute
272
+	 *	return : status=>OK/Message error
273
+	 */
274 274
 	public function dbmaintenanceAction()
275 275
 	{
276 276
 		
@@ -339,11 +339,11 @@  discard block
 block discarded – undo
339 339
 	}	
340 340
 
341 341
 	/** Save log output to db
342
-	*	destination=>log destination 
343
-	*	file=>file name
344
-	*	level => int 
345
-	*	return : status=>OK/Message error
346
-	*/
342
+	 *	destination=>log destination 
343
+	 *	file=>file name
344
+	 *	level => int 
345
+	 *	return : status=>OK/Message error
346
+	 */
347 347
 	public function logdestinationAction()
348 348
 	{
349 349
 		$postData=$this->getRequest()->getPost();
@@ -367,8 +367,8 @@  discard block
 block discarded – undo
367 367
 			$fileHandler=@fopen($file,'w');
368 368
 			if ($fileHandler == false)
369 369
 			{   // File os note writabe / cannot create
370
-			    $this->_helper->json(array('status'=>'File not writable :  '.$file));
371
-			    return;
370
+				$this->_helper->json(array('status'=>'File not writable :  '.$file));
371
+				return;
372 372
 			}
373 373
 		}
374 374
 		else
@@ -418,50 +418,50 @@  discard block
 block discarded – undo
418 418
 	public function testruleAction()
419 419
 	{
420 420
 	    
421
-	    $postData=$this->getRequest()->getPost();
422
-	    if (isset($postData['rule']))
423
-	    {
424
-	        $rule=$postData['rule'];
425
-	    }
426
-	    else
427
-	    {
428
-	        $this->_helper->json(array('status'=>'No Rule'));
429
-	    }
430
-	    if (isset($postData['action']))
431
-	    {
432
-	        $action=$postData['action'];
433
-	        if ($action != 'evaluate')
434
-	        {
435
-	            $this->_helper->json(array('status'=>'unknown action '.$action));
436
-	            return;
437
-	        }
438
-	    }
439
-	    else
440
-	    {
441
-	        $this->_helper->json(array('status'=>'No action'));
442
-	        return;
443
-	    }
444
-	    if ($action == 'evaluate')
445
-	    {
446
-	        try
447
-	        {
448
-	            require_once($this->Module()->getBaseDir() .'/bin/trap_class.php');
449
-	            $icingaweb2_etc=$this->Config()->get('config', 'icingaweb2_etc');
450
-	            $Trap = new Trap($icingaweb2_etc);
451
-	            // Cleanup spaces before eval
452
-	            $rule=$Trap->ruleClass->eval_cleanup($rule);
453
-	            // Eval
454
-	            $item=0;
455
-	            $rule=$Trap->ruleClass->evaluation($rule,$item);
456
-	        }
457
-	        catch (Exception $e)
458
-	        {
459
-	            $this->_helper->json(array('status'=>'Evaluation error : '.$e->getMessage() ));
460
-	            return;
461
-	        }
462
-	        $return=($rule==true)?'true':'false';
463
-	        $this->_helper->json(array('status'=>'OK', 'message' => $return));
464
-	    }
421
+		$postData=$this->getRequest()->getPost();
422
+		if (isset($postData['rule']))
423
+		{
424
+			$rule=$postData['rule'];
425
+		}
426
+		else
427
+		{
428
+			$this->_helper->json(array('status'=>'No Rule'));
429
+		}
430
+		if (isset($postData['action']))
431
+		{
432
+			$action=$postData['action'];
433
+			if ($action != 'evaluate')
434
+			{
435
+				$this->_helper->json(array('status'=>'unknown action '.$action));
436
+				return;
437
+			}
438
+		}
439
+		else
440
+		{
441
+			$this->_helper->json(array('status'=>'No action'));
442
+			return;
443
+		}
444
+		if ($action == 'evaluate')
445
+		{
446
+			try
447
+			{
448
+				require_once($this->Module()->getBaseDir() .'/bin/trap_class.php');
449
+				$icingaweb2_etc=$this->Config()->get('config', 'icingaweb2_etc');
450
+				$Trap = new Trap($icingaweb2_etc);
451
+				// Cleanup spaces before eval
452
+				$rule=$Trap->ruleClass->eval_cleanup($rule);
453
+				// Eval
454
+				$item=0;
455
+				$rule=$Trap->ruleClass->evaluation($rule,$item);
456
+			}
457
+			catch (Exception $e)
458
+			{
459
+				$this->_helper->json(array('status'=>'Evaluation error : '.$e->getMessage() ));
460
+				return;
461
+			}
462
+			$return=($rule==true)?'true':'false';
463
+			$this->_helper->json(array('status'=>'OK', 'message' => $return));
464
+		}
465 465
 	    
466 466
 	}	
467 467
 	
Please login to merge, or discard this patch.
Spacing   +35 added lines, -35 removed lines patch added patch discarded remove patch
@@ -27,12 +27,12 @@  discard block
 block discarded – undo
27 27
 			return;
28 28
 		}
29 29
 
30
-		$retHosts=array('status'=>'OK','hosts' => array());
30
+		$retHosts=array('status'=>'OK', 'hosts' => array());
31 31
 
32 32
 		$hosts=$this->getHostByIP($hostFilter);
33 33
 		foreach ($hosts as $val)
34 34
 		{
35
-			array_push($retHosts['hosts'],$val->name);
35
+			array_push($retHosts['hosts'], $val->name);
36 36
 		}
37 37
 		
38 38
 		$this->_helper->json($retHosts);
@@ -55,12 +55,12 @@  discard block
 block discarded – undo
55 55
 			return;
56 56
 		}
57 57
 
58
-		$retHosts=array('status'=>'OK','hosts' => array());
58
+		$retHosts=array('status'=>'OK', 'hosts' => array());
59 59
 
60 60
 		$hosts=$this->getHostGroupByName($hostFilter);
61 61
 		foreach ($hosts as $val)
62 62
 		{
63
-			array_push($retHosts['hosts'],$val->name);
63
+			array_push($retHosts['hosts'], $val->name);
64 64
 		}
65 65
 		
66 66
 		$this->_helper->json($retHosts);
@@ -82,31 +82,31 @@  discard block
 block discarded – undo
82 82
 		}
83 83
 		else
84 84
 		{
85
-			$this->_helper->json(array('status'=>'No Hosts','hostid' => -1));
85
+			$this->_helper->json(array('status'=>'No Hosts', 'hostid' => -1));
86 86
 			return;
87 87
 		}
88 88
 		
89 89
 		$hostArray=$this->getHostByName($host);
90 90
 		if (count($hostArray) > 1)
91 91
 		{	
92
-			$this->_helper->json(array('status'=>'More than one host matches','hostid' => -1));
92
+			$this->_helper->json(array('status'=>'More than one host matches', 'hostid' => -1));
93 93
 			return;
94 94
 		}
95 95
 		else if (count($hostArray) == 0)
96 96
 		{
97
-			$this->_helper->json(array('status'=>'No host matches','hostid' => -1));
97
+			$this->_helper->json(array('status'=>'No host matches', 'hostid' => -1));
98 98
 			return;
99 99
 		}
100 100
 		$services=$this->getServicesByHostid($hostArray[0]->id);
101 101
 		if (count($services) < 1)
102 102
 		{
103
-			$this->_helper->json(array('status'=>'No services found for host','hostid' => $hostArray[0]->id));
103
+			$this->_helper->json(array('status'=>'No services found for host', 'hostid' => $hostArray[0]->id));
104 104
 			return;
105 105
 		}
106
-		$retServices=array('status'=>'OK','services' => array(),'hostid' => $hostArray[0]->id);
106
+		$retServices=array('status'=>'OK', 'services' => array(), 'hostid' => $hostArray[0]->id);
107 107
 		foreach ($services as $val)
108 108
 		{
109
-			array_push($retServices['services'],array($val->id , $val->name));
109
+			array_push($retServices['services'], array($val->id, $val->name));
110 110
 		}
111 111
 		$this->_helper->json($retServices);
112 112
 	}
@@ -126,28 +126,28 @@  discard block
 block discarded – undo
126 126
 		}
127 127
 		else
128 128
 		{
129
-			$this->_helper->json(array('status'=>'No Hosts','hostid' => -1));
129
+			$this->_helper->json(array('status'=>'No Hosts', 'hostid' => -1));
130 130
 			return;
131 131
 		}
132 132
 		
133 133
 		$hostArray=$this->getHostGroupByName($host);
134 134
 		if (count($hostArray) > 1)
135 135
 		{	
136
-			$this->_helper->json(array('status'=>'More than one hostgroup matches','hostid' => -1));
136
+			$this->_helper->json(array('status'=>'More than one hostgroup matches', 'hostid' => -1));
137 137
 			return;
138 138
 		}
139 139
 		else if (count($hostArray) == 0)
140 140
 		{
141
-			$this->_helper->json(array('status'=>'No hostgroup matches','hostid' => -1));
141
+			$this->_helper->json(array('status'=>'No hostgroup matches', 'hostid' => -1));
142 142
 			return;
143 143
 		}
144 144
 		$services=$this->getServicesByHostGroupid($hostArray[0]->id);
145 145
 		if (count($services) < 1)
146 146
 		{
147
-			$this->_helper->json(array('status'=>'No services found for hostgroup','hostid' => $hostArray[0]->id));
147
+			$this->_helper->json(array('status'=>'No services found for hostgroup', 'hostid' => $hostArray[0]->id));
148 148
 			return;
149 149
 		}
150
-		$retServices=array('status'=>'OK','services' => $services,'hostid' => $hostArray[0]->id);
150
+		$retServices=array('status'=>'OK', 'services' => $services, 'hostid' => $hostArray[0]->id);
151 151
 		
152 152
 		$this->_helper->json($retServices);
153 153
 	}
@@ -172,7 +172,7 @@  discard block
 block discarded – undo
172 172
 		try
173 173
 		{
174 174
 			$traplist=$this->getMIB()->getTrapList($mib);
175
-			$retTraps=array('status'=>'OK','traps' => $traplist);
175
+			$retTraps=array('status'=>'OK', 'traps' => $traplist);
176 176
 		} 
177 177
 		catch (Exception $e) 
178 178
 		{ 
@@ -201,7 +201,7 @@  discard block
 block discarded – undo
201 201
 		try
202 202
 		{
203 203
 			$objectlist=$this->getMIB()->getObjectList($trap);
204
-			$retObjects=array('status'=>'OK','objects' => $objectlist);
204
+			$retObjects=array('status'=>'OK', 'objects' => $objectlist);
205 205
 		} 
206 206
 		catch (Exception $e) 
207 207
 		{ 
@@ -278,7 +278,7 @@  discard block
 block discarded – undo
278 278
 		if (isset($postData['days']))
279 279
 		{
280 280
 			$days=$postData['days'];
281
-			if (!preg_match('/^[0-9]+$/',$days))
281
+			if (!preg_match('/^[0-9]+$/', $days))
282 282
 			{
283 283
 				$this->_helper->json(array('status'=>'invalid days : '.$days));
284 284
 				return;
@@ -292,7 +292,7 @@  discard block
 block discarded – undo
292 292
 		if (isset($postData['action']))
293 293
 		{
294 294
 			$action=$postData['action'];
295
-			if ($action != 'save' && $action !='execute')
295
+			if ($action != 'save' && $action != 'execute')
296 296
 			{
297 297
 				$this->_helper->json(array('status'=>'unknown action '.$action));
298 298
 				return;
@@ -307,11 +307,11 @@  discard block
 block discarded – undo
307 307
 		{
308 308
 			try
309 309
 			{
310
-				$this->setDBConfigValue('db_remove_days',$days);
310
+				$this->setDBConfigValue('db_remove_days', $days);
311 311
 			}
312 312
 			catch (Exception $e)
313 313
 			{
314
-				$this->_helper->json(array('status'=>'Save error : '.$e->getMessage() ));
314
+				$this->_helper->json(array('status'=>'Save error : '.$e->getMessage()));
315 315
 				return;
316 316
 			}
317 317
 			$this->_helper->json(array('status'=>'OK'));
@@ -321,16 +321,16 @@  discard block
 block discarded – undo
321 321
 		{
322 322
 			try
323 323
 			{
324
-				require_once($this->Module()->getBaseDir() .'/bin/trap_class.php');
324
+				require_once($this->Module()->getBaseDir().'/bin/trap_class.php');
325 325
 				$icingaweb2_etc=$this->Config()->get('config', 'icingaweb2_etc');
326 326
 				$debug_level=4;
327
-				$Trap = new Trap($icingaweb2_etc);
328
-				$Trap->setLogging($debug_level,'syslog');
327
+				$Trap=new Trap($icingaweb2_etc);
328
+				$Trap->setLogging($debug_level, 'syslog');
329 329
 				$Trap->eraseOldTraps($days);
330 330
 			}
331 331
 			catch (Exception $e)
332 332
 			{
333
-				$this->_helper->json(array('status'=>'execute error : '.$e->getMessage() ));
333
+				$this->_helper->json(array('status'=>'execute error : '.$e->getMessage()));
334 334
 				return;
335 335
 			}			
336 336
 			$this->_helper->json(array('status'=>'OK'));
@@ -364,7 +364,7 @@  discard block
 block discarded – undo
364 364
 		if (isset($postData['file']))
365 365
 		{ 
366 366
 			$file=$postData['file'];
367
-			$fileHandler=@fopen($file,'w');
367
+			$fileHandler=@fopen($file, 'w');
368 368
 			if ($fileHandler == false)
369 369
 			{   // File os note writabe / cannot create
370 370
 			    $this->_helper->json(array('status'=>'File not writable :  '.$file));
@@ -396,13 +396,13 @@  discard block
 block discarded – undo
396 396
 		
397 397
 		try
398 398
 		{
399
-			$this->setDBConfigValue('log_destination',$destination);
400
-			$this->setDBConfigValue('log_file',$file);
401
-			$this->setDBConfigValue('log_level',$level);
399
+			$this->setDBConfigValue('log_destination', $destination);
400
+			$this->setDBConfigValue('log_file', $file);
401
+			$this->setDBConfigValue('log_level', $level);
402 402
 		}
403 403
 		catch (Exception $e)
404 404
 		{
405
-			$this->_helper->json(array('status'=>'Save error : '.$e->getMessage() ));
405
+			$this->_helper->json(array('status'=>'Save error : '.$e->getMessage()));
406 406
 			return;
407 407
 		}
408 408
 		$this->_helper->json(array('status'=>'OK'));
@@ -445,21 +445,21 @@  discard block
 block discarded – undo
445 445
 	    {
446 446
 	        try
447 447
 	        {
448
-	            require_once($this->Module()->getBaseDir() .'/bin/trap_class.php');
448
+	            require_once($this->Module()->getBaseDir().'/bin/trap_class.php');
449 449
 	            $icingaweb2_etc=$this->Config()->get('config', 'icingaweb2_etc');
450
-	            $Trap = new Trap($icingaweb2_etc);
450
+	            $Trap=new Trap($icingaweb2_etc);
451 451
 	            // Cleanup spaces before eval
452 452
 	            $rule=$Trap->ruleClass->eval_cleanup($rule);
453 453
 	            // Eval
454 454
 	            $item=0;
455
-	            $rule=$Trap->ruleClass->evaluation($rule,$item);
455
+	            $rule=$Trap->ruleClass->evaluation($rule, $item);
456 456
 	        }
457 457
 	        catch (Exception $e)
458 458
 	        {
459
-	            $this->_helper->json(array('status'=>'Evaluation error : '.$e->getMessage() ));
459
+	            $this->_helper->json(array('status'=>'Evaluation error : '.$e->getMessage()));
460 460
 	            return;
461 461
 	        }
462
-	        $return=($rule==true)?'true':'false';
462
+	        $return=($rule == true) ? 'true' : 'false';
463 463
 	        $this->_helper->json(array('status'=>'OK', 'message' => $return));
464 464
 	    }
465 465
 	    
Please login to merge, or discard this patch.
Braces   +25 added lines, -50 removed lines patch added patch discarded remove patch
@@ -20,8 +20,7 @@  discard block
 block discarded – undo
20 20
 		if (isset($postData['hostFilter']))
21 21
 		{
22 22
 			$hostFilter=$postData['hostFilter'];
23
-		}
24
-		else
23
+		} else
25 24
 		{
26 25
 			$this->_helper->json(array('status'=>'KO'));
27 26
 			return;
@@ -48,8 +47,7 @@  discard block
 block discarded – undo
48 47
 		if (isset($postData['hostFilter']))
49 48
 		{
50 49
 			$hostFilter=$postData['hostFilter'];
51
-		}
52
-		else
50
+		} else
53 51
 		{
54 52
 			$this->_helper->json(array('status'=>'Error : no filter'));
55 53
 			return;
@@ -79,8 +77,7 @@  discard block
 block discarded – undo
79 77
 		if (isset($postData['host']))
80 78
 		{
81 79
 			$host=$postData['host'];
82
-		}
83
-		else
80
+		} else
84 81
 		{
85 82
 			$this->_helper->json(array('status'=>'No Hosts','hostid' => -1));
86 83
 			return;
@@ -91,8 +88,7 @@  discard block
 block discarded – undo
91 88
 		{	
92 89
 			$this->_helper->json(array('status'=>'More than one host matches','hostid' => -1));
93 90
 			return;
94
-		}
95
-		else if (count($hostArray) == 0)
91
+		} else if (count($hostArray) == 0)
96 92
 		{
97 93
 			$this->_helper->json(array('status'=>'No host matches','hostid' => -1));
98 94
 			return;
@@ -123,8 +119,7 @@  discard block
 block discarded – undo
123 119
 		if (isset($postData['host']))
124 120
 		{
125 121
 			$host=$postData['host'];
126
-		}
127
-		else
122
+		} else
128 123
 		{
129 124
 			$this->_helper->json(array('status'=>'No Hosts','hostid' => -1));
130 125
 			return;
@@ -135,8 +130,7 @@  discard block
 block discarded – undo
135 130
 		{	
136 131
 			$this->_helper->json(array('status'=>'More than one hostgroup matches','hostid' => -1));
137 132
 			return;
138
-		}
139
-		else if (count($hostArray) == 0)
133
+		} else if (count($hostArray) == 0)
140 134
 		{
141 135
 			$this->_helper->json(array('status'=>'No hostgroup matches','hostid' => -1));
142 136
 			return;
@@ -163,8 +157,7 @@  discard block
 block discarded – undo
163 157
 		if (isset($postData['mib']))
164 158
 		{
165 159
 			$mib=$postData['mib'];
166
-		}
167
-		else
160
+		} else
168 161
 		{
169 162
 			$this->_helper->json(array('status'=>'No mib'));
170 163
 			return;
@@ -173,8 +166,7 @@  discard block
 block discarded – undo
173 166
 		{
174 167
 			$traplist=$this->getMIB()->getTrapList($mib);
175 168
 			$retTraps=array('status'=>'OK','traps' => $traplist);
176
-		} 
177
-		catch (Exception $e) 
169
+		} catch (Exception $e) 
178 170
 		{ 
179 171
 			$retTraps=array('status' => 'Error getting mibs');
180 172
 		}
@@ -192,8 +184,7 @@  discard block
 block discarded – undo
192 184
 		if (isset($postData['trap']))
193 185
 		{
194 186
 			$trap=$postData['trap'];
195
-		}
196
-		else
187
+		} else
197 188
 		{
198 189
 			$this->_helper->json(array('status'=>'No trap'));
199 190
 			return;
@@ -202,8 +193,7 @@  discard block
 block discarded – undo
202 193
 		{
203 194
 			$objectlist=$this->getMIB()->getObjectList($trap);
204 195
 			$retObjects=array('status'=>'OK','objects' => $objectlist);
205
-		} 
206
-		catch (Exception $e) 
196
+		} catch (Exception $e) 
207 197
 		{ 
208 198
 			$retObjects=array('status' => 'not found');
209 199
 		}
@@ -218,8 +208,7 @@  discard block
 block discarded – undo
218 208
 		try
219 209
 		{
220 210
 			$miblist=$this->getMIB()->getMIBList();
221
-		} 
222
-		catch (Exception $e) 
211
+		} catch (Exception $e) 
223 212
 		{ 
224 213
 			$miblist=array('Error getting mibs');
225 214
 		}
@@ -237,8 +226,7 @@  discard block
 block discarded – undo
237 226
 		if (isset($postData['oid']))
238 227
 		{
239 228
 			$oid=$postData['oid'];
240
-		}
241
-		else
229
+		} else
242 230
 		{
243 231
 			$this->_helper->json(array('status'=>'No oid'));
244 232
 			return;
@@ -249,8 +237,7 @@  discard block
 block discarded – undo
249 237
 		{
250 238
 			$this->_helper->json(array('status'=>'Not found'));
251 239
 			return;
252
-		}
253
-		else
240
+		} else
254 241
 		{
255 242
 			$this->_helper->json(
256 243
 				array('status'=>'OK',
@@ -283,8 +270,7 @@  discard block
 block discarded – undo
283 270
 				$this->_helper->json(array('status'=>'invalid days : '.$days));
284 271
 				return;
285 272
 			}
286
-		}
287
-		else
273
+		} else
288 274
 		{
289 275
 			$this->_helper->json(array('status'=>'No days'));
290 276
 			return;
@@ -297,8 +283,7 @@  discard block
 block discarded – undo
297 283
 				$this->_helper->json(array('status'=>'unknown action '.$action));
298 284
 				return;
299 285
 			}
300
-		}
301
-		else
286
+		} else
302 287
 		{
303 288
 			$this->_helper->json(array('status'=>'No action'));
304 289
 			return;
@@ -308,8 +293,7 @@  discard block
 block discarded – undo
308 293
 			try
309 294
 			{
310 295
 				$this->setDBConfigValue('db_remove_days',$days);
311
-			}
312
-			catch (Exception $e)
296
+			} catch (Exception $e)
313 297
 			{
314 298
 				$this->_helper->json(array('status'=>'Save error : '.$e->getMessage() ));
315 299
 				return;
@@ -327,8 +311,7 @@  discard block
 block discarded – undo
327 311
 				$Trap = new Trap($icingaweb2_etc);
328 312
 				$Trap->setLogging($debug_level,'syslog');
329 313
 				$Trap->eraseOldTraps($days);
330
-			}
331
-			catch (Exception $e)
314
+			} catch (Exception $e)
332 315
 			{
333 316
 				$this->_helper->json(array('status'=>'execute error : '.$e->getMessage() ));
334 317
 				return;
@@ -356,8 +339,7 @@  discard block
 block discarded – undo
356 339
 				$this->_helper->json(array('status'=>'invalid destination : '.$destination));
357 340
 				return;
358 341
 			}
359
-		}
360
-		else
342
+		} else
361 343
 		{
362 344
 			$this->_helper->json(array('status'=>'No destination'));
363 345
 		}
@@ -370,14 +352,12 @@  discard block
 block discarded – undo
370 352
 			    $this->_helper->json(array('status'=>'File not writable :  '.$file));
371 353
 			    return;
372 354
 			}
373
-		}
374
-		else
355
+		} else
375 356
 		{
376 357
 			if ($destination != 'file')
377 358
 			{
378 359
 				$file=null;
379
-			}
380
-			else
360
+			} else
381 361
 			{
382 362
 				$this->_helper->json(array('status'=>'No file'));
383 363
 				return;
@@ -387,8 +367,7 @@  discard block
 block discarded – undo
387 367
 		if (isset($postData['level']))
388 368
 		{ 
389 369
 			$level=$postData['level'];
390
-		}
391
-		else
370
+		} else
392 371
 		{
393 372
 			$this->_helper->json(array('status'=>'No level'));
394 373
 			return;
@@ -399,8 +378,7 @@  discard block
 block discarded – undo
399 378
 			$this->setDBConfigValue('log_destination',$destination);
400 379
 			$this->setDBConfigValue('log_file',$file);
401 380
 			$this->setDBConfigValue('log_level',$level);
402
-		}
403
-		catch (Exception $e)
381
+		} catch (Exception $e)
404 382
 		{
405 383
 			$this->_helper->json(array('status'=>'Save error : '.$e->getMessage() ));
406 384
 			return;
@@ -422,8 +400,7 @@  discard block
 block discarded – undo
422 400
 	    if (isset($postData['rule']))
423 401
 	    {
424 402
 	        $rule=$postData['rule'];
425
-	    }
426
-	    else
403
+	    } else
427 404
 	    {
428 405
 	        $this->_helper->json(array('status'=>'No Rule'));
429 406
 	    }
@@ -435,8 +412,7 @@  discard block
 block discarded – undo
435 412
 	            $this->_helper->json(array('status'=>'unknown action '.$action));
436 413
 	            return;
437 414
 	        }
438
-	    }
439
-	    else
415
+	    } else
440 416
 	    {
441 417
 	        $this->_helper->json(array('status'=>'No action'));
442 418
 	        return;
@@ -453,8 +429,7 @@  discard block
 block discarded – undo
453 429
 	            // Eval
454 430
 	            $item=0;
455 431
 	            $rule=$Trap->ruleClass->evaluation($rule,$item);
456
-	        }
457
-	        catch (Exception $e)
432
+	        } catch (Exception $e)
458 433
 	        {
459 434
 	            $this->_helper->json(array('status'=>'Evaluation error : '.$e->getMessage() ));
460 435
 	            return;
Please login to merge, or discard this patch.
application/controllers/SettingsController.php 3 patches
Indentation   +165 added lines, -165 removed lines patch added patch discarded remove patch
@@ -25,16 +25,16 @@  discard block
 block discarded – undo
25 25
    */
26 26
   private function get_param()
27 27
   {
28
-      $dberrorMsg=$this->params->get('dberror');
29
-      if ($dberrorMsg != '')
30
-      {
31
-          $this->view->errorDetected=$dberrorMsg;
32
-      }
33
-      $dberrorMsg=$this->params->get('idodberror');
34
-      if ($dberrorMsg != '')
35
-      {
36
-          $this->view->errorDetected=$dberrorMsg;
37
-      }
28
+	  $dberrorMsg=$this->params->get('dberror');
29
+	  if ($dberrorMsg != '')
30
+	  {
31
+		  $this->view->errorDetected=$dberrorMsg;
32
+	  }
33
+	  $dberrorMsg=$this->params->get('idodberror');
34
+	  if ($dberrorMsg != '')
35
+	  {
36
+		  $this->view->errorDetected=$dberrorMsg;
37
+	  }
38 38
   }
39 39
   
40 40
   /**
@@ -43,22 +43,22 @@  discard block
 block discarded – undo
43 43
    */
44 44
   private function check_empty_config()
45 45
   {
46
-      $this->view->configErrorDetected == NULL; // Displayed error on various conifugration errors.
47
-      if ($this->Config()->isEmpty() == true)
48
-      {
49
-          $this->Config()->setSection('config'); // Set base config section.
50
-          try
51
-          {
52
-              $this->Config()->saveIni();
53
-              $this->view->configErrorDetected='Configuration is empty : you can run install script with parameters (see Automatic installation below)';
54
-              //$emptyConfig=1;
55
-          }
56
-          catch (Exception $e)
57
-          {
58
-              $this->view->configErrorDetected=$e->getMessage();
59
-          }
46
+	  $this->view->configErrorDetected == NULL; // Displayed error on various conifugration errors.
47
+	  if ($this->Config()->isEmpty() == true)
48
+	  {
49
+		  $this->Config()->setSection('config'); // Set base config section.
50
+		  try
51
+		  {
52
+			  $this->Config()->saveIni();
53
+			  $this->view->configErrorDetected='Configuration is empty : you can run install script with parameters (see Automatic installation below)';
54
+			  //$emptyConfig=1;
55
+		  }
56
+		  catch (Exception $e)
57
+		  {
58
+			  $this->view->configErrorDetected=$e->getMessage();
59
+		  }
60 60
           
61
-      }
61
+	  }
62 62
   }
63 63
   
64 64
   /**
@@ -71,45 +71,45 @@  discard block
 block discarded – undo
71 71
    */
72 72
   private function check_db()
73 73
   {
74
-      $db_message=array( // index => ( message OK, message NOK, optional link if NOK )
75
-          0	=>	array('Database configuration OK','',''),
76
-          1	=>	array('Database set in config.ini','No database in config.ini',''),
77
-          2	=>	array('Database exists in Icingaweb2 config','Database does not exist in Icingaweb2 : ',
78
-              Url::fromPath('config/resource')),
79
-          3	=>	array('Database credentials OK','Database does not exist/invalid credentials/no schema : ',
80
-              Url::fromPath('trapdirector/settings/createschema')),
81
-          4	=>	array('Schema is set','Schema is not set for ',
82
-              Url::fromPath('trapdirector/settings/createschema')),
83
-          5	=>	array('Schema is up to date','Schema is outdated :',
84
-              Url::fromPath('trapdirector/settings/updateschema')),
85
-      );
74
+	  $db_message=array( // index => ( message OK, message NOK, optional link if NOK )
75
+		  0	=>	array('Database configuration OK','',''),
76
+		  1	=>	array('Database set in config.ini','No database in config.ini',''),
77
+		  2	=>	array('Database exists in Icingaweb2 config','Database does not exist in Icingaweb2 : ',
78
+			  Url::fromPath('config/resource')),
79
+		  3	=>	array('Database credentials OK','Database does not exist/invalid credentials/no schema : ',
80
+			  Url::fromPath('trapdirector/settings/createschema')),
81
+		  4	=>	array('Schema is set','Schema is not set for ',
82
+			  Url::fromPath('trapdirector/settings/createschema')),
83
+		  5	=>	array('Schema is up to date','Schema is outdated :',
84
+			  Url::fromPath('trapdirector/settings/updateschema')),
85
+	  );
86 86
       
87
-      $dberror=$this->getDb(true); // Get DB in test mode
87
+	  $dberror=$this->getDb(true); // Get DB in test mode
88 88
       
89
-      $this->view->db_error=$dberror[0];
90
-      switch ($dberror[0])
91
-      {
92
-          case 2:
93
-          case 4:
94
-              $db_message[$dberror[0]][1] .= $dberror[1];
95
-              break;
96
-          case 3:
97
-              $db_message[$dberror[0]][1] .= $dberror[1] . ', Message : ' . $dberror[2];
98
-              break;
99
-          case 5:
100
-              $db_message[$dberror[0]][1] .= ' version '. $dberror[1] . ', version needed : ' .$dberror[2];
101
-              break;
102
-          case 0:
103
-          case 1:
104
-              break;
105
-          default:
106
-              new ProgrammingError('Out of bond result from database test');
107
-      }
108
-      $this->view->message=$db_message;
89
+	  $this->view->db_error=$dberror[0];
90
+	  switch ($dberror[0])
91
+	  {
92
+		  case 2:
93
+		  case 4:
94
+			  $db_message[$dberror[0]][1] .= $dberror[1];
95
+			  break;
96
+		  case 3:
97
+			  $db_message[$dberror[0]][1] .= $dberror[1] . ', Message : ' . $dberror[2];
98
+			  break;
99
+		  case 5:
100
+			  $db_message[$dberror[0]][1] .= ' version '. $dberror[1] . ', version needed : ' .$dberror[2];
101
+			  break;
102
+		  case 0:
103
+		  case 1:
104
+			  break;
105
+		  default:
106
+			  new ProgrammingError('Out of bond result from database test');
107
+	  }
108
+	  $this->view->message=$db_message;
109 109
       
110
-      $dberror=$this->getIdoDb(true); // Get IDO DB in test mode
111
-      $this->view->ido_db_error=$dberror[0];
112
-      $this->view->ido_message='IDO Database : ' . $dberror[1];
110
+	  $dberror=$this->getIdoDb(true); // Get IDO DB in test mode
111
+	  $this->view->ido_db_error=$dberror[0];
112
+	  $this->view->ido_message='IDO Database : ' . $dberror[1];
113 113
   }
114 114
   
115 115
   /**
@@ -119,23 +119,23 @@  discard block
 block discarded – undo
119 119
    */
120 120
   private function check_api()
121 121
   {
122
-      if ($this->Config()->get('config', 'icingaAPI_host') != '')
123
-      {
124
-          $apitest=new Icinga2Api($this->Config()->get('config', 'icingaAPI_host'),$this->Config()->get('config', 'icingaAPI_port'));
125
-          $apitest->setCredentials($this->Config()->get('config', 'icingaAPI_user'), $this->Config()->get('config', 'icingaAPI_password'));
126
-          try {
127
-              list($this->view->apimessageError,$this->view->apimessage)=$apitest->test($this->getModuleConfig()::getapiUserPermissions());
128
-              //$this->view->apimessageError=false;
129
-          } catch (RuntimeException $e) {
130
-              $this->view->apimessage='API config : ' . $e->getMessage();
131
-              $this->view->apimessageError=true;
132
-          }
133
-      }
134
-      else
135
-      {
136
-          $this->view->apimessage='API parameters not configured';
137
-          $this->view->apimessageError=true;
138
-      }
122
+	  if ($this->Config()->get('config', 'icingaAPI_host') != '')
123
+	  {
124
+		  $apitest=new Icinga2Api($this->Config()->get('config', 'icingaAPI_host'),$this->Config()->get('config', 'icingaAPI_port'));
125
+		  $apitest->setCredentials($this->Config()->get('config', 'icingaAPI_user'), $this->Config()->get('config', 'icingaAPI_password'));
126
+		  try {
127
+			  list($this->view->apimessageError,$this->view->apimessage)=$apitest->test($this->getModuleConfig()::getapiUserPermissions());
128
+			  //$this->view->apimessageError=false;
129
+		  } catch (RuntimeException $e) {
130
+			  $this->view->apimessage='API config : ' . $e->getMessage();
131
+			  $this->view->apimessageError=true;
132
+		  }
133
+	  }
134
+	  else
135
+	  {
136
+		  $this->view->apimessage='API parameters not configured';
137
+		  $this->view->apimessageError=true;
138
+	  }
139 139
   }
140 140
 
141 141
   /**
@@ -146,20 +146,20 @@  discard block
 block discarded – undo
146 146
    */
147 147
   private function check_icingaweb_path()
148 148
   {
149
-      $this->view->icingaEtcWarn=0;
150
-      $icingaweb2_etc=$this->Config()->get('config', 'icingaweb2_etc');
151
-      if ($icingaweb2_etc != "/etc/icingaweb2/" && $icingaweb2_etc != '')
152
-      {
153
-          $output=array();
149
+	  $this->view->icingaEtcWarn=0;
150
+	  $icingaweb2_etc=$this->Config()->get('config', 'icingaweb2_etc');
151
+	  if ($icingaweb2_etc != "/etc/icingaweb2/" && $icingaweb2_etc != '')
152
+	  {
153
+		  $output=array();
154 154
           
155
-          exec('cat ' . $this->module->getBaseDir() .'/bin/trap_in.php | grep "\$icingaweb2_etc=" ',$output);
155
+		  exec('cat ' . $this->module->getBaseDir() .'/bin/trap_in.php | grep "\$icingaweb2_etc=" ',$output);
156 156
           
157
-          if (! preg_match('#"'. $icingaweb2_etc .'"#',$output[0]))
158
-          {
159
-              $this->view->icingaEtcWarn=1;
160
-              $this->view->icingaweb2_etc=$icingaweb2_etc;
161
-          }
162
-      }
157
+		  if (! preg_match('#"'. $icingaweb2_etc .'"#',$output[0]))
158
+		  {
159
+			  $this->view->icingaEtcWarn=1;
160
+			  $this->view->icingaweb2_etc=$icingaweb2_etc;
161
+		  }
162
+	  }
163 163
       
164 164
   }
165 165
   
@@ -170,15 +170,15 @@  discard block
 block discarded – undo
170 170
    */
171 171
   private function get_db_list($allowed)
172 172
   {
173
-      $resources = array();
174
-      foreach (ResourceFactory::getResourceConfigs() as $name => $resource) 
175
-      {
176
-          if ($resource->get('type') === 'db' && in_array($resource->get('db'), $allowed)) 
177
-          {
178
-              $resources[$name] = $name;
179
-          }
180
-      }
181
-      return $resources;
173
+	  $resources = array();
174
+	  foreach (ResourceFactory::getResourceConfigs() as $name => $resource) 
175
+	  {
176
+		  if ($resource->get('type') === 'db' && in_array($resource->get('db'), $allowed)) 
177
+		  {
178
+			  $resources[$name] = $name;
179
+		  }
180
+	  }
181
+	  return $resources;
182 182
   }
183 183
   
184 184
   /**
@@ -197,7 +197,7 @@  discard block
 block discarded – undo
197 197
   public function indexAction()
198 198
   {
199 199
       
200
-    // CHeck permissions : display tests in any case, but no configuration.
200
+	// CHeck permissions : display tests in any case, but no configuration.
201 201
 	$this->view->configPermission=$this->checkModuleConfigPermission(1);
202 202
 	// But check read permission
203 203
 	$this->checkReadPermission();
@@ -205,16 +205,16 @@  discard block
 block discarded – undo
205 205
 	$this->view->tabs = $this->Module()->getConfigTabs()->activate('config');
206 206
 	
207 207
 	// Get message : sent on configuration problems detected by controllers
208
-    $this->get_param();
208
+	$this->get_param();
209 209
     
210
-    // Test if configuration exists, if not create for installer script
210
+	// Test if configuration exists, if not create for installer script
211 211
 	$this->check_empty_config();
212 212
 
213 213
 	// Test Database
214
-    $this->check_db();
214
+	$this->check_db();
215 215
 	
216 216
 	//********* Test API
217
-    $this->check_api();
217
+	$this->check_api();
218 218
 	
219 219
 	//*********** Test snmptrapd alive and options
220 220
 	list ($this->view->snmptrapdError, $this->view->snmptrapdMessage) = $this->checkSnmpTrapd();
@@ -229,11 +229,11 @@  discard block
 block discarded – undo
229 229
 	$this->view->traps_in_config= PHP_BINARY . ' ' . $this->Module()->getBaseDir() . '/bin/trap_in.php';
230 230
 	
231 231
 	$this->view->installer= $this->Module()->getBaseDir() . '/bin/installer.sh '
232
-	    . ' -c all ' 
233
-	    . ' -d ' . $this->Module()->getBaseDir()
234
-	    . ' -p ' . PHP_BINARY
235
-	    . ' -a ' . exec('whoami')
236
-	    . ' -w ' . Icinga::app()->getConfigDir();
232
+		. ' -c all ' 
233
+		. ' -d ' . $this->Module()->getBaseDir()
234
+		. ' -p ' . PHP_BINARY
235
+		. ' -a ' . exec('whoami')
236
+		. ' -w ' . Icinga::app()->getConfigDir();
237 237
 	        
238 238
 	// ******************* configuration form setup*******************
239 239
 	$this->view->form = $form = new TrapsConfigForm();
@@ -278,19 +278,19 @@  discard block
 block discarded – undo
278 278
 		  $dbResource = ResourceFactory::getResourceConfig($dbName);
279 279
 		  $dbType=$dbResource->get('db');
280 280
 		  switch ($dbType) {
281
-		      case 'mysql':
282
-		          $dbFileExt='sql';
283
-		          break;
284
-		      case 'pgsql':
285
-		          $dbFileExt='pgsql';
286
-		          break;
287
-		      default:
288
-		          throw new ConfigurationError('Unsuported database : '.$dbType);
281
+			  case 'mysql':
282
+				  $dbFileExt='sql';
283
+				  break;
284
+			  case 'pgsql':
285
+				  $dbFileExt='pgsql';
286
+				  break;
287
+			  default:
288
+				  throw new ConfigurationError('Unsuported database : '.$dbType);
289 289
 		  }
290 290
 		} catch (ConfigurationError $e )
291 291
 		{
292
-		    printf("Database configuration error : %s",$e->getMessage());
293
-		    return;
292
+			printf("Database configuration error : %s",$e->getMessage());
293
+			return;
294 294
 		}
295 295
 		printf('<pre>');
296 296
 		require_once $this->Module()->getBaseDir() .'/bin/trap_class.php';
@@ -314,11 +314,11 @@  discard block
 block discarded – undo
314 314
   public function updateschemaAction()
315 315
   {
316 316
 	  $this->checkModuleConfigPermission();
317
-    	$this->getTabs()->add('get',array(
318
-    		'active'	=> true,
319
-    		'label'		=> $this->translate('Update Schema'),
320
-    		'url'		=> Url::fromRequest()
321
-    	));
317
+		$this->getTabs()->add('get',array(
318
+			'active'	=> true,
319
+			'label'		=> $this->translate('Update Schema'),
320
+			'url'		=> Url::fromRequest()
321
+		));
322 322
 	  // check if needed
323 323
 	  
324 324
 	  $dberror=$this->getDb(true); // Get DB in test mode
@@ -327,15 +327,15 @@  discard block
 block discarded – undo
327 327
 	  
328 328
 	  if ($dberror[0] == 0)
329 329
 	  {
330
-	      echo 'Schema already exists and is up to date<br>';
331
-	      return;
330
+		  echo 'Schema already exists and is up to date<br>';
331
+		  return;
332 332
 	  }
333 333
 	  if ($dberror[0] != 5)
334 334
 	  {
335
-	      echo 'Database does not exists or is not setup correctly<br>';
336
-	      return;
335
+		  echo 'Database does not exists or is not setup correctly<br>';
336
+		  return;
337 337
 	  }
338
-      // setup
338
+	  // setup
339 339
 	  require_once($this->Module()->getBaseDir() .'/bin/trap_class.php');
340 340
 	  $icingaweb2_etc=$this->Config()->get('config', 'icingaweb2_etc');
341 341
 	  $debug_level=4;
@@ -348,20 +348,20 @@  discard block
 block discarded – undo
348 348
 	  $target_version=$dberror[2];
349 349
 	  
350 350
 	  if ($this->params->get('msgok') == null) {
351
-	      // Check for messages and display if any
352
-              echo "Upgrade databse is going to start.<br>Don't forget to backup your database before update<br>";
353
-	      $Trap->setLogging(2,'syslog');
354
-	      $message = $Trap->trapsDB->update_schema($updateSchema,$target_version,$prefix,true);
355
-	      if ($message != '')
356
-	      {
357
-	          echo 'Note :<br><pre>';
358
-	          echo $message;
359
-	          echo '</pre>';
360
-	          echo '<br>';
361
-	          echo '<a  class="link-button" style="font-size:large;font-weight:bold" href="' . Url::fromPath('trapdirector/settings/updateschema') .'?msgok=1">Click here to update</a>';
362
-	          echo '<br>';
363
-	          return;
364
-	      }
351
+		  // Check for messages and display if any
352
+			  echo "Upgrade databse is going to start.<br>Don't forget to backup your database before update<br>";
353
+		  $Trap->setLogging(2,'syslog');
354
+		  $message = $Trap->trapsDB->update_schema($updateSchema,$target_version,$prefix,true);
355
+		  if ($message != '')
356
+		  {
357
+			  echo 'Note :<br><pre>';
358
+			  echo $message;
359
+			  echo '</pre>';
360
+			  echo '<br>';
361
+			  echo '<a  class="link-button" style="font-size:large;font-weight:bold" href="' . Url::fromPath('trapdirector/settings/updateschema') .'?msgok=1">Click here to update</a>';
362
+			  echo '<br>';
363
+			  return;
364
+		  }
365 365
 	  }
366 366
 	  
367 367
 	  $Trap->setLogging($debug_level,'display');
@@ -375,28 +375,28 @@  discard block
 block discarded – undo
375 375
 
376 376
   private function checkSnmpTrapd()
377 377
   {
378
-      $psOutput=array();
379
-      // First check is someone is listening to port 162. As not root, we can't have pid... 
380
-      exec('netstat -an |grep -E "udp.*:162"',$psOutput);
381
-      if (count($psOutput) == 0)
382
-      {
383
-          return array(1,'Port UDP/162 is not open : snmptrapd must not be started');
384
-      }
385
-      $psOutput=array();
386
-      exec('ps fax |grep snmptrapd |grep -v grep',$psOutput);
387
-      if (count($psOutput) == 0)
388
-      {
389
-          return array(1,"UDP/162 : OK, but no snmptrapd process (?)");
390
-      }
391
-      // Assume there is only one line... TODO : see if there is a better way to do this
392
-      $line = preg_replace('/^.*snmptrapd /','',$psOutput[0]);
393
-      if (!preg_match('/-n/',$line))
394
-          return array(1,'snmptrapd has no -n option : '.$line);
395
-      if (!preg_match('/-O[^ ]*n/',$line))
396
-          return array(1,'snmptrapd has no -On option : '.$line);
397
-      if (!preg_match('/-O[^ ]*e/',$line))
398
-          return array(1,'snmptrapd has no -Oe option : '.$line);
378
+	  $psOutput=array();
379
+	  // First check is someone is listening to port 162. As not root, we can't have pid... 
380
+	  exec('netstat -an |grep -E "udp.*:162"',$psOutput);
381
+	  if (count($psOutput) == 0)
382
+	  {
383
+		  return array(1,'Port UDP/162 is not open : snmptrapd must not be started');
384
+	  }
385
+	  $psOutput=array();
386
+	  exec('ps fax |grep snmptrapd |grep -v grep',$psOutput);
387
+	  if (count($psOutput) == 0)
388
+	  {
389
+		  return array(1,"UDP/162 : OK, but no snmptrapd process (?)");
390
+	  }
391
+	  // Assume there is only one line... TODO : see if there is a better way to do this
392
+	  $line = preg_replace('/^.*snmptrapd /','',$psOutput[0]);
393
+	  if (!preg_match('/-n/',$line))
394
+		  return array(1,'snmptrapd has no -n option : '.$line);
395
+	  if (!preg_match('/-O[^ ]*n/',$line))
396
+		  return array(1,'snmptrapd has no -On option : '.$line);
397
+	  if (!preg_match('/-O[^ ]*e/',$line))
398
+		  return array(1,'snmptrapd has no -Oe option : '.$line);
399 399
       
400
-      return array(0,'snmptrapd listening to UDP/162, options : '.$line);
400
+	  return array(0,'snmptrapd listening to UDP/162, options : '.$line);
401 401
   }
402 402
 }
Please login to merge, or discard this patch.
Spacing   +63 added lines, -63 removed lines patch added patch discarded remove patch
@@ -72,15 +72,15 @@  discard block
 block discarded – undo
72 72
   private function check_db()
73 73
   {
74 74
       $db_message=array( // index => ( message OK, message NOK, optional link if NOK )
75
-          0	=>	array('Database configuration OK','',''),
76
-          1	=>	array('Database set in config.ini','No database in config.ini',''),
77
-          2	=>	array('Database exists in Icingaweb2 config','Database does not exist in Icingaweb2 : ',
75
+          0	=>	array('Database configuration OK', '', ''),
76
+          1	=>	array('Database set in config.ini', 'No database in config.ini', ''),
77
+          2	=>	array('Database exists in Icingaweb2 config', 'Database does not exist in Icingaweb2 : ',
78 78
               Url::fromPath('config/resource')),
79
-          3	=>	array('Database credentials OK','Database does not exist/invalid credentials/no schema : ',
79
+          3	=>	array('Database credentials OK', 'Database does not exist/invalid credentials/no schema : ',
80 80
               Url::fromPath('trapdirector/settings/createschema')),
81
-          4	=>	array('Schema is set','Schema is not set for ',
81
+          4	=>	array('Schema is set', 'Schema is not set for ',
82 82
               Url::fromPath('trapdirector/settings/createschema')),
83
-          5	=>	array('Schema is up to date','Schema is outdated :',
83
+          5	=>	array('Schema is up to date', 'Schema is outdated :',
84 84
               Url::fromPath('trapdirector/settings/updateschema')),
85 85
       );
86 86
       
@@ -91,13 +91,13 @@  discard block
 block discarded – undo
91 91
       {
92 92
           case 2:
93 93
           case 4:
94
-              $db_message[$dberror[0]][1] .= $dberror[1];
94
+              $db_message[$dberror[0]][1].=$dberror[1];
95 95
               break;
96 96
           case 3:
97
-              $db_message[$dberror[0]][1] .= $dberror[1] . ', Message : ' . $dberror[2];
97
+              $db_message[$dberror[0]][1].=$dberror[1].', Message : '.$dberror[2];
98 98
               break;
99 99
           case 5:
100
-              $db_message[$dberror[0]][1] .= ' version '. $dberror[1] . ', version needed : ' .$dberror[2];
100
+              $db_message[$dberror[0]][1].=' version '.$dberror[1].', version needed : '.$dberror[2];
101 101
               break;
102 102
           case 0:
103 103
           case 1:
@@ -109,7 +109,7 @@  discard block
 block discarded – undo
109 109
       
110 110
       $dberror=$this->getIdoDb(true); // Get IDO DB in test mode
111 111
       $this->view->ido_db_error=$dberror[0];
112
-      $this->view->ido_message='IDO Database : ' . $dberror[1];
112
+      $this->view->ido_message='IDO Database : '.$dberror[1];
113 113
   }
114 114
   
115 115
   /**
@@ -121,13 +121,13 @@  discard block
 block discarded – undo
121 121
   {
122 122
       if ($this->Config()->get('config', 'icingaAPI_host') != '')
123 123
       {
124
-          $apitest=new Icinga2Api($this->Config()->get('config', 'icingaAPI_host'),$this->Config()->get('config', 'icingaAPI_port'));
124
+          $apitest=new Icinga2Api($this->Config()->get('config', 'icingaAPI_host'), $this->Config()->get('config', 'icingaAPI_port'));
125 125
           $apitest->setCredentials($this->Config()->get('config', 'icingaAPI_user'), $this->Config()->get('config', 'icingaAPI_password'));
126 126
           try {
127
-              list($this->view->apimessageError,$this->view->apimessage)=$apitest->test($this->getModuleConfig()::getapiUserPermissions());
127
+              list($this->view->apimessageError, $this->view->apimessage)=$apitest->test($this->getModuleConfig()::getapiUserPermissions());
128 128
               //$this->view->apimessageError=false;
129 129
           } catch (RuntimeException $e) {
130
-              $this->view->apimessage='API config : ' . $e->getMessage();
130
+              $this->view->apimessage='API config : '.$e->getMessage();
131 131
               $this->view->apimessageError=true;
132 132
           }
133 133
       }
@@ -152,9 +152,9 @@  discard block
 block discarded – undo
152 152
       {
153 153
           $output=array();
154 154
           
155
-          exec('cat ' . $this->module->getBaseDir() .'/bin/trap_in.php | grep "\$icingaweb2_etc=" ',$output);
155
+          exec('cat '.$this->module->getBaseDir().'/bin/trap_in.php | grep "\$icingaweb2_etc=" ', $output);
156 156
           
157
-          if (! preg_match('#"'. $icingaweb2_etc .'"#',$output[0]))
157
+          if (!preg_match('#"'.$icingaweb2_etc.'"#', $output[0]))
158 158
           {
159 159
               $this->view->icingaEtcWarn=1;
160 160
               $this->view->icingaweb2_etc=$icingaweb2_etc;
@@ -170,12 +170,12 @@  discard block
 block discarded – undo
170 170
    */
171 171
   private function get_db_list($allowed)
172 172
   {
173
-      $resources = array();
173
+      $resources=array();
174 174
       foreach (ResourceFactory::getResourceConfigs() as $name => $resource) 
175 175
       {
176 176
           if ($resource->get('type') === 'db' && in_array($resource->get('db'), $allowed)) 
177 177
           {
178
-              $resources[$name] = $name;
178
+              $resources[$name]=$name;
179 179
           }
180 180
       }
181 181
       return $resources;
@@ -202,7 +202,7 @@  discard block
 block discarded – undo
202 202
 	// But check read permission
203 203
 	$this->checkReadPermission();
204 204
 	
205
-	$this->view->tabs = $this->Module()->getConfigTabs()->activate('config');
205
+	$this->view->tabs=$this->Module()->getConfigTabs()->activate('config');
206 206
 	
207 207
 	// Get message : sent on configuration problems detected by controllers
208 208
     $this->get_param();
@@ -217,32 +217,32 @@  discard block
 block discarded – undo
217 217
     $this->check_api();
218 218
 	
219 219
 	//*********** Test snmptrapd alive and options
220
-	list ($this->view->snmptrapdError, $this->view->snmptrapdMessage) = $this->checkSnmpTrapd();
220
+	list ($this->view->snmptrapdError, $this->view->snmptrapdMessage)=$this->checkSnmpTrapd();
221 221
 
222 222
 	// List DB in $ressources
223
-	$resources = $this->get_db_list(array('mysql', 'pgsql')); 
223
+	$resources=$this->get_db_list(array('mysql', 'pgsql')); 
224 224
 
225 225
 	// Check standard Icingaweb2 path
226 226
 	$this->check_icingaweb_path();
227 227
 	
228 228
 	// Setup path for mini documentation
229
-	$this->view->traps_in_config= PHP_BINARY . ' ' . $this->Module()->getBaseDir() . '/bin/trap_in.php';
229
+	$this->view->traps_in_config=PHP_BINARY.' '.$this->Module()->getBaseDir().'/bin/trap_in.php';
230 230
 	
231
-	$this->view->installer= $this->Module()->getBaseDir() . '/bin/installer.sh '
231
+	$this->view->installer=$this->Module()->getBaseDir().'/bin/installer.sh '
232 232
 	    . ' -c all ' 
233
-	    . ' -d ' . $this->Module()->getBaseDir()
234
-	    . ' -p ' . PHP_BINARY
235
-	    . ' -a ' . exec('whoami')
236
-	    . ' -w ' . Icinga::app()->getConfigDir();
233
+	    . ' -d '.$this->Module()->getBaseDir()
234
+	    . ' -p '.PHP_BINARY
235
+	    . ' -a '.exec('whoami')
236
+	    . ' -w '.Icinga::app()->getConfigDir();
237 237
 	        
238 238
 	// ******************* configuration form setup*******************
239
-	$this->view->form = $form = new TrapsConfigForm();
239
+	$this->view->form=$form=new TrapsConfigForm();
240 240
 	
241 241
 	// set default paths;
242
-	$this->view->form->setPaths($this->Module()->getBaseDir(),Icinga::app()->getConfigDir());
242
+	$this->view->form->setPaths($this->Module()->getBaseDir(), Icinga::app()->getConfigDir());
243 243
 	
244 244
 	// set default ido database
245
-	$this->view->form->setDefaultIDODB($this->Config()->module('monitoring','backends')->get('icinga','resource'));
245
+	$this->view->form->setDefaultIDODB($this->Config()->module('monitoring', 'backends')->get('icinga', 'resource'));
246 246
 	
247 247
 	// Make form handle request.
248 248
 	$form->setIniConfig($this->Config())
@@ -254,7 +254,7 @@  discard block
 block discarded – undo
254 254
   public function createschemaAction()
255 255
   {
256 256
 	$this->checkModuleConfigPermission();
257
-	$this->getTabs()->add('create_schema',array(
257
+	$this->getTabs()->add('create_schema', array(
258 258
 		'active'	=> true,
259 259
 		'label'		=> $this->translate('Create Schema'),
260 260
 		'url'		=> Url::fromRequest()
@@ -275,7 +275,7 @@  discard block
 block discarded – undo
275 275
 		$dbName=$this->Config()->get('config', 'database');
276 276
 
277 277
 		try {
278
-		  $dbResource = ResourceFactory::getResourceConfig($dbName);
278
+		  $dbResource=ResourceFactory::getResourceConfig($dbName);
279 279
 		  $dbType=$dbResource->get('db');
280 280
 		  switch ($dbType) {
281 281
 		      case 'mysql':
@@ -287,34 +287,34 @@  discard block
 block discarded – undo
287 287
 		      default:
288 288
 		          throw new ConfigurationError('Unsuported database : '.$dbType);
289 289
 		  }
290
-		} catch (ConfigurationError $e )
290
+		} catch (ConfigurationError $e)
291 291
 		{
292
-		    printf("Database configuration error : %s",$e->getMessage());
292
+		    printf("Database configuration error : %s", $e->getMessage());
293 293
 		    return;
294 294
 		}
295 295
 		printf('<pre>');
296
-		require_once $this->Module()->getBaseDir() .'/bin/trap_class.php';
296
+		require_once $this->Module()->getBaseDir().'/bin/trap_class.php';
297 297
 		
298 298
 		$icingaweb2_etc=$this->Config()->get('config', 'icingaweb2_etc');
299 299
 		$debug_level=4;
300
-		$Trap = new Trap($icingaweb2_etc);
301
-		$Trap->setLogging($debug_level,'display');
300
+		$Trap=new Trap($icingaweb2_etc);
301
+		$Trap->setLogging($debug_level, 'display');
302 302
 		
303 303
 		$prefix=$this->Config()->get('config', 'database_prefix');
304 304
 		// schema file : <path>/SQL/schema_v<verion>.<dbtype>
305
-		$schema=$this->Module()->getBaseDir() . 
306
-		'/SQL/schema_v'. $this->getModuleConfig()->getDbCurVersion() . '.' . $dbFileExt;
305
+		$schema=$this->Module()->getBaseDir(). 
306
+		'/SQL/schema_v'.$this->getModuleConfig()->getDbCurVersion().'.'.$dbFileExt;
307 307
 		
308
-		$Trap->trapsDB->create_schema($schema,$prefix);
308
+		$Trap->trapsDB->create_schema($schema, $prefix);
309 309
 		echo '</pre>';
310 310
 	}
311
-	echo '<br><br>Return to <a href="' . Url::fromPath('trapdirector/settings') .'" class="link-button icon-wrench"> settings page </a>';
311
+	echo '<br><br>Return to <a href="'.Url::fromPath('trapdirector/settings').'" class="link-button icon-wrench"> settings page </a>';
312 312
   }
313 313
 
314 314
   public function updateschemaAction()
315 315
   {
316 316
 	  $this->checkModuleConfigPermission();
317
-    	$this->getTabs()->add('get',array(
317
+    	$this->getTabs()->add('get', array(
318 318
     		'active'	=> true,
319 319
     		'label'		=> $this->translate('Update Schema'),
320 320
     		'url'		=> Url::fromRequest()
@@ -323,7 +323,7 @@  discard block
 block discarded – undo
323 323
 	  
324 324
 	  $dberror=$this->getDb(true); // Get DB in test mode
325 325
 	  
326
-	  echo 'Return to <a href="' . Url::fromPath('trapdirector/settings') .'" class="link-button icon-wrench"> settings page </a><br><br>';
326
+	  echo 'Return to <a href="'.Url::fromPath('trapdirector/settings').'" class="link-button icon-wrench"> settings page </a><br><br>';
327 327
 	  
328 328
 	  if ($dberror[0] == 0)
329 329
 	  {
@@ -336,40 +336,40 @@  discard block
 block discarded – undo
336 336
 	      return;
337 337
 	  }
338 338
       // setup
339
-	  require_once($this->Module()->getBaseDir() .'/bin/trap_class.php');
339
+	  require_once($this->Module()->getBaseDir().'/bin/trap_class.php');
340 340
 	  $icingaweb2_etc=$this->Config()->get('config', 'icingaweb2_etc');
341 341
 	  $debug_level=4;
342
-	  $Trap = new Trap($icingaweb2_etc);
342
+	  $Trap=new Trap($icingaweb2_etc);
343 343
 	  
344 344
 	  
345 345
 	  $prefix=$this->Config()->get('config', 'database_prefix');
346
-	  $updateSchema=$this->Module()->getBaseDir() . '/SQL/';
346
+	  $updateSchema=$this->Module()->getBaseDir().'/SQL/';
347 347
 	  
348 348
 	  $target_version=$dberror[2];
349 349
 	  
350 350
 	  if ($this->params->get('msgok') == null) {
351 351
 	      // Check for messages and display if any
352 352
               echo "Upgrade databse is going to start.<br>Don't forget to backup your database before update<br>";
353
-	      $Trap->setLogging(2,'syslog');
354
-	      $message = $Trap->trapsDB->update_schema($updateSchema,$target_version,$prefix,true);
353
+	      $Trap->setLogging(2, 'syslog');
354
+	      $message=$Trap->trapsDB->update_schema($updateSchema, $target_version, $prefix, true);
355 355
 	      if ($message != '')
356 356
 	      {
357 357
 	          echo 'Note :<br><pre>';
358 358
 	          echo $message;
359 359
 	          echo '</pre>';
360 360
 	          echo '<br>';
361
-	          echo '<a  class="link-button" style="font-size:large;font-weight:bold" href="' . Url::fromPath('trapdirector/settings/updateschema') .'?msgok=1">Click here to update</a>';
361
+	          echo '<a  class="link-button" style="font-size:large;font-weight:bold" href="'.Url::fromPath('trapdirector/settings/updateschema').'?msgok=1">Click here to update</a>';
362 362
 	          echo '<br>';
363 363
 	          return;
364 364
 	      }
365 365
 	  }
366 366
 	  
367
-	  $Trap->setLogging($debug_level,'display');
367
+	  $Trap->setLogging($debug_level, 'display');
368 368
 	  
369
-	  echo 'Updating schema to '. $target_version . ': <br>';
369
+	  echo 'Updating schema to '.$target_version.': <br>';
370 370
 	  echo '<pre>';
371 371
 	  	  
372
-	  $Trap->trapsDB->update_schema($updateSchema,$target_version,$prefix);
372
+	  $Trap->trapsDB->update_schema($updateSchema, $target_version, $prefix);
373 373
 	  echo '</pre>';
374 374
   }  
375 375
 
@@ -377,26 +377,26 @@  discard block
 block discarded – undo
377 377
   {
378 378
       $psOutput=array();
379 379
       // First check is someone is listening to port 162. As not root, we can't have pid... 
380
-      exec('netstat -an |grep -E "udp.*:162"',$psOutput);
380
+      exec('netstat -an |grep -E "udp.*:162"', $psOutput);
381 381
       if (count($psOutput) == 0)
382 382
       {
383
-          return array(1,'Port UDP/162 is not open : snmptrapd must not be started');
383
+          return array(1, 'Port UDP/162 is not open : snmptrapd must not be started');
384 384
       }
385 385
       $psOutput=array();
386
-      exec('ps fax |grep snmptrapd |grep -v grep',$psOutput);
386
+      exec('ps fax |grep snmptrapd |grep -v grep', $psOutput);
387 387
       if (count($psOutput) == 0)
388 388
       {
389
-          return array(1,"UDP/162 : OK, but no snmptrapd process (?)");
389
+          return array(1, "UDP/162 : OK, but no snmptrapd process (?)");
390 390
       }
391 391
       // Assume there is only one line... TODO : see if there is a better way to do this
392
-      $line = preg_replace('/^.*snmptrapd /','',$psOutput[0]);
393
-      if (!preg_match('/-n/',$line))
394
-          return array(1,'snmptrapd has no -n option : '.$line);
395
-      if (!preg_match('/-O[^ ]*n/',$line))
396
-          return array(1,'snmptrapd has no -On option : '.$line);
397
-      if (!preg_match('/-O[^ ]*e/',$line))
398
-          return array(1,'snmptrapd has no -Oe option : '.$line);
392
+      $line=preg_replace('/^.*snmptrapd /', '', $psOutput[0]);
393
+      if (!preg_match('/-n/', $line))
394
+          return array(1, 'snmptrapd has no -n option : '.$line);
395
+      if (!preg_match('/-O[^ ]*n/', $line))
396
+          return array(1, 'snmptrapd has no -On option : '.$line);
397
+      if (!preg_match('/-O[^ ]*e/', $line))
398
+          return array(1, 'snmptrapd has no -Oe option : '.$line);
399 399
       
400
-      return array(0,'snmptrapd listening to UDP/162, options : '.$line);
400
+      return array(0, 'snmptrapd listening to UDP/162, options : '.$line);
401 401
   }
402 402
 }
Please login to merge, or discard this patch.
Braces   +12 added lines, -12 removed lines patch added patch discarded remove patch
@@ -52,8 +52,7 @@  discard block
 block discarded – undo
52 52
               $this->Config()->saveIni();
53 53
               $this->view->configErrorDetected='Configuration is empty : you can run install script with parameters (see Automatic installation below)';
54 54
               //$emptyConfig=1;
55
-          }
56
-          catch (Exception $e)
55
+          } catch (Exception $e)
57 56
           {
58 57
               $this->view->configErrorDetected=$e->getMessage();
59 58
           }
@@ -130,8 +129,7 @@  discard block
 block discarded – undo
130 129
               $this->view->apimessage='API config : ' . $e->getMessage();
131 130
               $this->view->apimessageError=true;
132 131
           }
133
-      }
134
-      else
132
+      } else
135 133
       {
136 134
           $this->view->apimessage='API parameters not configured';
137 135
           $this->view->apimessageError=true;
@@ -266,8 +264,7 @@  discard block
 block discarded – undo
266 264
 	if ($dberror[0] == 0)
267 265
 	{
268 266
 		printf('Schema already exists');
269
-	}
270
-	else
267
+	} else
271 268
 	{
272 269
 		printf('Creating schema : <br>');
273 270
 
@@ -390,12 +387,15 @@  discard block
 block discarded – undo
390 387
       }
391 388
       // Assume there is only one line... TODO : see if there is a better way to do this
392 389
       $line = preg_replace('/^.*snmptrapd /','',$psOutput[0]);
393
-      if (!preg_match('/-n/',$line))
394
-          return array(1,'snmptrapd has no -n option : '.$line);
395
-      if (!preg_match('/-O[^ ]*n/',$line))
396
-          return array(1,'snmptrapd has no -On option : '.$line);
397
-      if (!preg_match('/-O[^ ]*e/',$line))
398
-          return array(1,'snmptrapd has no -Oe option : '.$line);
390
+      if (!preg_match('/-n/',$line)) {
391
+                return array(1,'snmptrapd has no -n option : '.$line);
392
+      }
393
+      if (!preg_match('/-O[^ ]*n/',$line)) {
394
+                return array(1,'snmptrapd has no -On option : '.$line);
395
+      }
396
+      if (!preg_match('/-O[^ ]*e/',$line)) {
397
+                return array(1,'snmptrapd has no -Oe option : '.$line);
398
+      }
399 399
       
400 400
       return array(0,'snmptrapd listening to UDP/162, options : '.$line);
401 401
   }
Please login to merge, or discard this patch.
library/Trapdirector/TrapsProcess/Rule.php 3 patches
Indentation   +289 added lines, -289 removed lines patch added patch discarded remove patch
@@ -11,331 +11,331 @@
 block discarded – undo
11 11
 class Rule
12 12
 {
13 13
     
14
-    protected $logging; //< logging class
14
+	protected $logging; //< logging class
15 15
     
16
-    /**
17
-     * Setup Rule Class
18
-     * @param Logging $logClass : where to log
19
-     */
20
-    function __construct($logClass)
21
-    {
22
-        $this->logging=$logClass;
16
+	/**
17
+	 * Setup Rule Class
18
+	 * @param Logging $logClass : where to log
19
+	 */
20
+	function __construct($logClass)
21
+	{
22
+		$this->logging=$logClass;
23 23
 
24
-    }
24
+	}
25 25
 
26 26
 /**
27 27
  * Get full number 
28 28
  * @return array<number,string>
29 29
  */
30
-    private function get_number($rule,&$item)
31
-    {
32
-        $item2=$item+1;
33
-        while (
34
-            ($item2!=strlen($rule)) 
35
-            && (preg_match('/[0-9\.]/',$rule[$item2]))) 
36
-        { 
37
-            $item2++ ;
38
-        }
39
-        $val=substr($rule,$item,$item2-$item);
40
-        $item=$item2;
41
-        //echo "number ".$val."\n";
30
+	private function get_number($rule,&$item)
31
+	{
32
+		$item2=$item+1;
33
+		while (
34
+			($item2!=strlen($rule)) 
35
+			&& (preg_match('/[0-9\.]/',$rule[$item2]))) 
36
+		{ 
37
+			$item2++ ;
38
+		}
39
+		$val=substr($rule,$item,$item2-$item);
40
+		$item=$item2;
41
+		//echo "number ".$val."\n";
42 42
         
43
-        return array(0,$val);
44
-    }
43
+		return array(0,$val);
44
+	}
45 45
 
46
-    private function get_string($rule,&$item)
47
-    {
48
-        $item++;
49
-        $item2=$this->eval_getNext($rule,$item,'"');
50
-        $val=substr($rule,$item,$item2-$item-1);
51
-        $item=$item2;
52
-        //echo "string : ".$val."\n";
53
-        return array(1,$val);
46
+	private function get_string($rule,&$item)
47
+	{
48
+		$item++;
49
+		$item2=$this->eval_getNext($rule,$item,'"');
50
+		$val=substr($rule,$item,$item2-$item-1);
51
+		$item=$item2;
52
+		//echo "string : ".$val."\n";
53
+		return array(1,$val);
54 54
         
55
-    }
55
+	}
56 56
     
57
-    private function get_group($rule,&$item)
58
-    {
59
-        $item++;
60
-        $start=$item;
61
-        $parenthesis_count=0;
62
-        while (($item < strlen($rule)) // Not end of string AND
63
-            && ( ($rule[$item] != ')' ) || $parenthesis_count > 0) ) // Closing ')' or embeded ()
64
-        {
65
-            if ($rule[$item] == '"' )
66
-            { // pass through string
67
-                $item++;
68
-                $item=$this->eval_getNext($rule,$item,'"');
69
-            }
70
-            else{
71
-                if ($rule[$item] == '(')
72
-                {
73
-                    $parenthesis_count++;
74
-                }
75
-                if ($rule[$item] == ')')
76
-                {
77
-                    $parenthesis_count--;
78
-                }
79
-                $item++;
80
-            }
81
-        }
57
+	private function get_group($rule,&$item)
58
+	{
59
+		$item++;
60
+		$start=$item;
61
+		$parenthesis_count=0;
62
+		while (($item < strlen($rule)) // Not end of string AND
63
+			&& ( ($rule[$item] != ')' ) || $parenthesis_count > 0) ) // Closing ')' or embeded ()
64
+		{
65
+			if ($rule[$item] == '"' )
66
+			{ // pass through string
67
+				$item++;
68
+				$item=$this->eval_getNext($rule,$item,'"');
69
+			}
70
+			else{
71
+				if ($rule[$item] == '(')
72
+				{
73
+					$parenthesis_count++;
74
+				}
75
+				if ($rule[$item] == ')')
76
+				{
77
+					$parenthesis_count--;
78
+				}
79
+				$item++;
80
+			}
81
+		}
82 82
         
83
-        if ($item==strlen($rule)) {throw new Exception("no closing () in ".$rule ." at " .$item);}
84
-        $val=substr($rule,$start,$item-$start);
85
-        $item++;
86
-        $start=0;
87
-        //echo "group : ".$val."\n";
88
-        // returns evaluation of group as type 2 (boolean)
89
-        return array(2,$this->evaluation($val,$start));
90
-    }
83
+		if ($item==strlen($rule)) {throw new Exception("no closing () in ".$rule ." at " .$item);}
84
+		$val=substr($rule,$start,$item-$start);
85
+		$item++;
86
+		$start=0;
87
+		//echo "group : ".$val."\n";
88
+		// returns evaluation of group as type 2 (boolean)
89
+		return array(2,$this->evaluation($val,$start));
90
+	}
91 91
     
92
-    protected function eval_getElement($rule,&$item)
93
-    {
94
-        if ($item >= strlen($rule))
95
-        {
96
-            throw new Exception("Early end of string ".$rule ." at " .$item );
97
-        }
98
-        while ($rule[$item]==' ') $item++;
99
-        if (preg_match('/[0-9\.]/',$rule[$item]))
100
-        { // number
101
-            return $this->get_number($rule, $item);
102
-        }
103
-        if ($rule[$item] == '"')
104
-        { // string
105
-            return $this->get_string($rule, $item);
106
-        }
92
+	protected function eval_getElement($rule,&$item)
93
+	{
94
+		if ($item >= strlen($rule))
95
+		{
96
+			throw new Exception("Early end of string ".$rule ." at " .$item );
97
+		}
98
+		while ($rule[$item]==' ') $item++;
99
+		if (preg_match('/[0-9\.]/',$rule[$item]))
100
+		{ // number
101
+			return $this->get_number($rule, $item);
102
+		}
103
+		if ($rule[$item] == '"')
104
+		{ // string
105
+			return $this->get_string($rule, $item);
106
+		}
107 107
         
108
-        if ($rule[$item] == '(')
109
-        { // grouping
110
-            return $this->get_group($rule, $item);
111
-        }
112
-        throw new Exception("number/string not found in ".$rule ." at " .$item . ' : ' .$rule[$item]);
108
+		if ($rule[$item] == '(')
109
+		{ // grouping
110
+			return $this->get_group($rule, $item);
111
+		}
112
+		throw new Exception("number/string not found in ".$rule ." at " .$item . ' : ' .$rule[$item]);
113 113
         
114
-    }
114
+	}
115 115
     
116
-    protected function eval_getNext($rule,$item,$tok)
117
-    {
118
-        while (
119
-            ($rule[$item] != $tok ) 
120
-            && ($item < strlen($rule))) 
121
-        { 
122
-            $item++;
123
-        }
124
-        if ($item==strlen($rule)) {
125
-            throw new Exception("closing '".$tok."' not found in ".$rule ." at " .$item);
126
-        }
127
-        return $item+1;
128
-    }
116
+	protected function eval_getNext($rule,$item,$tok)
117
+	{
118
+		while (
119
+			($rule[$item] != $tok ) 
120
+			&& ($item < strlen($rule))) 
121
+		{ 
122
+			$item++;
123
+		}
124
+		if ($item==strlen($rule)) {
125
+			throw new Exception("closing '".$tok."' not found in ".$rule ." at " .$item);
126
+		}
127
+		return $item+1;
128
+	}
129 129
     
130
-    protected function eval_getOper($rule,&$item)
131
-    {
132
-        while ($rule[$item]==' ') $item++;
133
-        switch ($rule[$item])
134
-        {
135
-            case '<':
136
-                if ($rule[$item+1]=='=') { $item+=2; return array(0,"<=");}
137
-                $item++; return array(0,"<");
138
-            case '>':
139
-                if ($rule[$item+1]=='=') { $item+=2; return array(0,">=");}
140
-                $item++; return array(0,">");
141
-            case '=':
142
-                $item++; return array(0,"=");
143
-            case '!':
144
-                if ($rule[$item+1]=='=') { $item+=2; return array(0,"!=");}
145
-                throw new Exception("Erreur in expr - incorrect operator '!'  found in ".$rule ." at " .$item);
146
-            case '~':
147
-                $item++; return array(0,"~");
148
-            case '|':
149
-                $item++; return array(1,"|");
150
-            case '&':
151
-                $item++; return array(1,"&");
152
-            default	:
153
-                throw new Exception("Erreur in expr - operator not found in ".$rule ." at " .$item);
154
-        }
155
-    }
130
+	protected function eval_getOper($rule,&$item)
131
+	{
132
+		while ($rule[$item]==' ') $item++;
133
+		switch ($rule[$item])
134
+		{
135
+			case '<':
136
+				if ($rule[$item+1]=='=') { $item+=2; return array(0,"<=");}
137
+				$item++; return array(0,"<");
138
+			case '>':
139
+				if ($rule[$item+1]=='=') { $item+=2; return array(0,">=");}
140
+				$item++; return array(0,">");
141
+			case '=':
142
+				$item++; return array(0,"=");
143
+			case '!':
144
+				if ($rule[$item+1]=='=') { $item+=2; return array(0,"!=");}
145
+				throw new Exception("Erreur in expr - incorrect operator '!'  found in ".$rule ." at " .$item);
146
+			case '~':
147
+				$item++; return array(0,"~");
148
+			case '|':
149
+				$item++; return array(1,"|");
150
+			case '&':
151
+				$item++; return array(1,"&");
152
+			default	:
153
+				throw new Exception("Erreur in expr - operator not found in ".$rule ." at " .$item);
154
+		}
155
+	}
156 156
     
157
-    private function check_negate_first($rule,&$item)
158
-    {
159
-        if ( $rule[$item] == '!') // If '!' found, negate next expression.
160
-        {
161
-            $item++;
162
-            return true;
163
-        }
164
-        else
165
-        {
166
-            return false;
167
-        }
168
-    }
157
+	private function check_negate_first($rule,&$item)
158
+	{
159
+		if ( $rule[$item] == '!') // If '!' found, negate next expression.
160
+		{
161
+			$item++;
162
+			return true;
163
+		}
164
+		else
165
+		{
166
+			return false;
167
+		}
168
+	}
169 169
 
170
-    private function do_compare($val1,$val2,$comp,$negate)
171
-    {
172
-        switch ($comp){
173
-            case '<':	$retVal= ($val1 < $val2); break;
174
-            case '<=':	$retVal= ($val1 <= $val2); break;
175
-            case '>':	$retVal= ($val1 > $val2); break;
176
-            case '>=':	$retVal= ($val1 >= $val2); break;
177
-            case '=':	$retVal= ($val1 == $val2); break;
178
-            case '!=':	$retVal= ($val1 != $val2); break;
179
-            case '~':	$retVal= (preg_match('/'.preg_replace('/"/','',$val2).'/',$val1)); break;
180
-            case '|':	$retVal= ($val1 || $val2); break;
181
-            case '&':	$retVal= ($val1 && $val2); break;
182
-            default:  throw new Exception("Error in expression - unknown comp : ".$comp);
183
-        }
184
-        if ($negate === true) $retVal = ! $retVal; // Inverse result if negate before expression
170
+	private function do_compare($val1,$val2,$comp,$negate)
171
+	{
172
+		switch ($comp){
173
+			case '<':	$retVal= ($val1 < $val2); break;
174
+			case '<=':	$retVal= ($val1 <= $val2); break;
175
+			case '>':	$retVal= ($val1 > $val2); break;
176
+			case '>=':	$retVal= ($val1 >= $val2); break;
177
+			case '=':	$retVal= ($val1 == $val2); break;
178
+			case '!=':	$retVal= ($val1 != $val2); break;
179
+			case '~':	$retVal= (preg_match('/'.preg_replace('/"/','',$val2).'/',$val1)); break;
180
+			case '|':	$retVal= ($val1 || $val2); break;
181
+			case '&':	$retVal= ($val1 && $val2); break;
182
+			default:  throw new Exception("Error in expression - unknown comp : ".$comp);
183
+		}
184
+		if ($negate === true) $retVal = ! $retVal; // Inverse result if negate before expression
185 185
         
186
-        return $retVal;
187
-    }
186
+		return $retVal;
187
+	}
188 188
     
189
-    /** Evaluation : makes token and evaluate.
190
-     *	Public function for expressions testing
191
-     *	accepts : < > = <= >= !=  (typec = 0)
192
-     *	operators : & | (typec=1)
193
-     *	with : integers/float  (type 0) or strings "" (type 1) or results (type 2)
194
-     *   comparison int vs strings will return null (error)
195
-     *	return : bool or null on error
196
-     */
197
-    public function evaluation($rule,&$item)
198
-    {
199
-        //echo "Evaluation of ".substr($rule,$item)."\n";
200
-        $negate=$this->check_negate_first($rule, $item);
201
-        // First element : number, string or ()
202
-        list($type1,$val1) = $this->eval_getElement($rule,$item);
203
-        //echo "Elmt1: ".$val1."/".$type1." : ".substr($rule,$item)."\n";
189
+	/** Evaluation : makes token and evaluate.
190
+	 *	Public function for expressions testing
191
+	 *	accepts : < > = <= >= !=  (typec = 0)
192
+	 *	operators : & | (typec=1)
193
+	 *	with : integers/float  (type 0) or strings "" (type 1) or results (type 2)
194
+	 *   comparison int vs strings will return null (error)
195
+	 *	return : bool or null on error
196
+	 */
197
+	public function evaluation($rule,&$item)
198
+	{
199
+		//echo "Evaluation of ".substr($rule,$item)."\n";
200
+		$negate=$this->check_negate_first($rule, $item);
201
+		// First element : number, string or ()
202
+		list($type1,$val1) = $this->eval_getElement($rule,$item);
203
+		//echo "Elmt1: ".$val1."/".$type1." : ".substr($rule,$item)."\n";
204 204
         
205
-        if ($item==strlen($rule)) // If only element, return value, but only boolean
206
-        {
207
-            if ($type1 != 2) throw new Exception("Cannot use num/string as boolean : ".$rule);
208
-            if ($negate === true) $val1= ! $val1;
209
-            return $val1;
210
-        }
205
+		if ($item==strlen($rule)) // If only element, return value, but only boolean
206
+		{
207
+			if ($type1 != 2) throw new Exception("Cannot use num/string as boolean : ".$rule);
208
+			if ($negate === true) $val1= ! $val1;
209
+			return $val1;
210
+		}
211 211
         
212
-        // Second element : operator
213
-        list($typec,$comp) = $this->eval_getOper($rule,$item);
214
-        //echo "Comp : ".$comp." : ".substr($rule,$item)."\n";
212
+		// Second element : operator
213
+		list($typec,$comp) = $this->eval_getOper($rule,$item);
214
+		//echo "Comp : ".$comp." : ".substr($rule,$item)."\n";
215 215
         
216
-        // Third element : number, string or ()
217
-        if ( $rule[$item] == '!') // starts with a ! so evaluate whats next
218
-        {
219
-            $item++;
220
-            if ($typec != 1) throw new Exception("Mixing boolean and comparison : ".$rule);
221
-            $val2= ! $this->evaluation($rule,$item);
222
-            $type2=2; // result is a boolean
223
-        }
224
-        else
225
-        {
226
-            list($type2,$val2) = $this->eval_getElement($rule,$item);
227
-        }
228
-        //echo "Elmt2: ".$val2."/".$type2." : ".substr($rule,$item)."\n";
216
+		// Third element : number, string or ()
217
+		if ( $rule[$item] == '!') // starts with a ! so evaluate whats next
218
+		{
219
+			$item++;
220
+			if ($typec != 1) throw new Exception("Mixing boolean and comparison : ".$rule);
221
+			$val2= ! $this->evaluation($rule,$item);
222
+			$type2=2; // result is a boolean
223
+		}
224
+		else
225
+		{
226
+			list($type2,$val2) = $this->eval_getElement($rule,$item);
227
+		}
228
+		//echo "Elmt2: ".$val2."/".$type2." : ".substr($rule,$item)."\n";
229 229
         
230
-        if ($type1!=$type2)  // cannot compare different types
231
-        {
232
-            throw new Exception("Cannot compare string & number : ".$rule);
233
-        }
234
-        if ($typec==1 && $type1 !=2) // cannot use & or | with string/number
235
-        {
236
-            throw new Exception("Cannot use boolean operators with string & number : ".$rule);
237
-        }
230
+		if ($type1!=$type2)  // cannot compare different types
231
+		{
232
+			throw new Exception("Cannot compare string & number : ".$rule);
233
+		}
234
+		if ($typec==1 && $type1 !=2) // cannot use & or | with string/number
235
+		{
236
+			throw new Exception("Cannot use boolean operators with string & number : ".$rule);
237
+		}
238 238
         
239
-        $retVal = $this->do_compare($val1, $val2, $comp, $negate);
239
+		$retVal = $this->do_compare($val1, $val2, $comp, $negate);
240 240
         
241
-        if ($item==strlen($rule)) return $retVal; // End of string : return evaluation
242
-        // check for logical operator :
243
-        switch ($rule[$item])
244
-        {
245
-            case '|':	$item++; return ($retVal || $this->evaluation($rule,$item) );
246
-            case '&':	$item++; return ($retVal && $this->evaluation($rule,$item) );
241
+		if ($item==strlen($rule)) return $retVal; // End of string : return evaluation
242
+		// check for logical operator :
243
+		switch ($rule[$item])
244
+		{
245
+			case '|':	$item++; return ($retVal || $this->evaluation($rule,$item) );
246
+			case '&':	$item++; return ($retVal && $this->evaluation($rule,$item) );
247 247
             
248
-            default:  throw new Exception("Erreur in expr - garbadge at end of expression : ".$rule[$item]);
249
-        }
250
-    }
248
+			default:  throw new Exception("Erreur in expr - garbadge at end of expression : ".$rule[$item]);
249
+		}
250
+	}
251 251
     
252
-    // Remove all whitespaces (when not quoted)
253
-    public function eval_cleanup($rule)
254
-    {
255
-        $item=0;
256
-        $rule2='';
257
-        while ($item < strlen($rule))
258
-        {
259
-            if ($rule[$item]==' ') { $item++; continue; }
260
-            if ($rule[$item]=='"')
261
-            {
262
-                $rule2.=$rule[$item];
263
-                $item++;
264
-                while (($item < strlen($rule)) && ($rule[$item]!='"') )
265
-                {
266
-                    $rule2.=$rule[$item];
267
-                    $item++;
268
-                }
269
-                if ($item == strlen ($rule)) throw new Exception("closing '\"' not found in ".$rule ." at " .$item);
270
-                $rule2.=$rule[$item];
271
-                $item++;
272
-                continue;
273
-            }
252
+	// Remove all whitespaces (when not quoted)
253
+	public function eval_cleanup($rule)
254
+	{
255
+		$item=0;
256
+		$rule2='';
257
+		while ($item < strlen($rule))
258
+		{
259
+			if ($rule[$item]==' ') { $item++; continue; }
260
+			if ($rule[$item]=='"')
261
+			{
262
+				$rule2.=$rule[$item];
263
+				$item++;
264
+				while (($item < strlen($rule)) && ($rule[$item]!='"') )
265
+				{
266
+					$rule2.=$rule[$item];
267
+					$item++;
268
+				}
269
+				if ($item == strlen ($rule)) throw new Exception("closing '\"' not found in ".$rule ." at " .$item);
270
+				$rule2.=$rule[$item];
271
+				$item++;
272
+				continue;
273
+			}
274 274
             
275
-            $rule2.=$rule[$item];
276
-            $item++;
277
-        }
275
+			$rule2.=$rule[$item];
276
+			$item++;
277
+		}
278 278
         
279
-        return $rule2;
280
-    }
279
+		return $rule2;
280
+	}
281 281
     
282
-    /** Evaluation rule (uses eval_* functions recursively)
283
-     *	@param string $rule : rule ( _OID(.1.3.6.1.4.1.8072.2.3.2.1)=_OID(.1.3.6.1.2.1.1.3.0) )
284
-     *  @param array $oidList : OIDs values to sustitute.
285
-     *	@return bool : true : rule match, false : rule don't match , throw exception on error.
286
-     */
282
+	/** Evaluation rule (uses eval_* functions recursively)
283
+	 *	@param string $rule : rule ( _OID(.1.3.6.1.4.1.8072.2.3.2.1)=_OID(.1.3.6.1.2.1.1.3.0) )
284
+	 *  @param array $oidList : OIDs values to sustitute.
285
+	 *	@return bool : true : rule match, false : rule don't match , throw exception on error.
286
+	 */
287 287
     
288
-    public function eval_rule($rule,$oidList)
289
-    {
290
-        if ($rule==null || $rule == '') // Empty rule is always true
291
-        {
292
-            return true;
293
-        }
294
-        $matches=array();
295
-        while (preg_match('/_OID\(([0-9\.\*]+)\)/',$rule,$matches) == 1)
296
-        {
297
-            $oid=$matches[1];
298
-            $found=0;
299
-            // ** replaced by .*
300
-            $oidR=preg_replace('/\*\*/', '.*', $oid);
301
-            // * replaced by [^.]*
302
-            $oidR=preg_replace('/\*/', '[0-9]+', $oidR);
288
+	public function eval_rule($rule,$oidList)
289
+	{
290
+		if ($rule==null || $rule == '') // Empty rule is always true
291
+		{
292
+			return true;
293
+		}
294
+		$matches=array();
295
+		while (preg_match('/_OID\(([0-9\.\*]+)\)/',$rule,$matches) == 1)
296
+		{
297
+			$oid=$matches[1];
298
+			$found=0;
299
+			// ** replaced by .*
300
+			$oidR=preg_replace('/\*\*/', '.*', $oid);
301
+			// * replaced by [^.]*
302
+			$oidR=preg_replace('/\*/', '[0-9]+', $oidR);
303 303
             
304
-            // replace * with \* in oid for preg_replace
305
-            $oid=preg_replace('/\*/', '\*', $oid);
304
+			// replace * with \* in oid for preg_replace
305
+			$oid=preg_replace('/\*/', '\*', $oid);
306 306
             
307
-            $this->logging->log('OID in rule : '.$oid.' / '.$oidR,DEBUG );
307
+			$this->logging->log('OID in rule : '.$oid.' / '.$oidR,DEBUG );
308 308
             
309
-            foreach($oidList as $val)
310
-            {
311
-                if (preg_match("/^$oidR$/",$val->oid) == 1)
312
-                {
313
-                    if (!preg_match('/^[0-9]*\.?[0-9]+$/',$val->value))
314
-                    { // If not a number, change " to ' and put " around it
315
-                        $val->value=preg_replace('/"/',"'",$val->value);
316
-                        $val->value='"'.$val->value.'"';
317
-                    }
318
-                    $rep=0;
319
-                    $rule=preg_replace('/_OID\('.$oid.'\)/',$val->value,$rule,-1,$rep);
320
-                    if ($rep==0)
321
-                    {
322
-                        $this->logging->log("Error in rule_eval",WARN,'');
323
-                        return false;
324
-                    }
325
-                    $found=1;
326
-                    break;
327
-                }
328
-            }
329
-            if ($found==0)
330
-            {	// OID not found : throw error
331
-                throw new Exception('OID '.$oid.' not found in trap');
332
-            }
333
-        }
334
-        $item=0;
335
-        $rule=$this->eval_cleanup($rule);
336
-        $this->logging->log('Rule after clenup: '.$rule,INFO );
309
+			foreach($oidList as $val)
310
+			{
311
+				if (preg_match("/^$oidR$/",$val->oid) == 1)
312
+				{
313
+					if (!preg_match('/^[0-9]*\.?[0-9]+$/',$val->value))
314
+					{ // If not a number, change " to ' and put " around it
315
+						$val->value=preg_replace('/"/',"'",$val->value);
316
+						$val->value='"'.$val->value.'"';
317
+					}
318
+					$rep=0;
319
+					$rule=preg_replace('/_OID\('.$oid.'\)/',$val->value,$rule,-1,$rep);
320
+					if ($rep==0)
321
+					{
322
+						$this->logging->log("Error in rule_eval",WARN,'');
323
+						return false;
324
+					}
325
+					$found=1;
326
+					break;
327
+				}
328
+			}
329
+			if ($found==0)
330
+			{	// OID not found : throw error
331
+				throw new Exception('OID '.$oid.' not found in trap');
332
+			}
333
+		}
334
+		$item=0;
335
+		$rule=$this->eval_cleanup($rule);
336
+		$this->logging->log('Rule after clenup: '.$rule,INFO );
337 337
         
338
-        return  $this->evaluation($rule,$item);
339
-    }
338
+		return  $this->evaluation($rule,$item);
339
+	}
340 340
     
341 341
 }
342 342
\ No newline at end of file
Please login to merge, or discard this patch.
Spacing   +88 added lines, -88 removed lines patch added patch discarded remove patch
@@ -27,47 +27,47 @@  discard block
 block discarded – undo
27 27
  * Get full number 
28 28
  * @return array<number,string>
29 29
  */
30
-    private function get_number($rule,&$item)
30
+    private function get_number($rule, &$item)
31 31
     {
32
-        $item2=$item+1;
32
+        $item2=$item + 1;
33 33
         while (
34
-            ($item2!=strlen($rule)) 
35
-            && (preg_match('/[0-9\.]/',$rule[$item2]))) 
34
+            ($item2 != strlen($rule)) 
35
+            && (preg_match('/[0-9\.]/', $rule[$item2]))) 
36 36
         { 
37
-            $item2++ ;
37
+            $item2++;
38 38
         }
39
-        $val=substr($rule,$item,$item2-$item);
39
+        $val=substr($rule, $item, $item2 - $item);
40 40
         $item=$item2;
41 41
         //echo "number ".$val."\n";
42 42
         
43
-        return array(0,$val);
43
+        return array(0, $val);
44 44
     }
45 45
 
46
-    private function get_string($rule,&$item)
46
+    private function get_string($rule, &$item)
47 47
     {
48 48
         $item++;
49
-        $item2=$this->eval_getNext($rule,$item,'"');
50
-        $val=substr($rule,$item,$item2-$item-1);
49
+        $item2=$this->eval_getNext($rule, $item, '"');
50
+        $val=substr($rule, $item, $item2 - $item - 1);
51 51
         $item=$item2;
52 52
         //echo "string : ".$val."\n";
53
-        return array(1,$val);
53
+        return array(1, $val);
54 54
         
55 55
     }
56 56
     
57
-    private function get_group($rule,&$item)
57
+    private function get_group($rule, &$item)
58 58
     {
59 59
         $item++;
60 60
         $start=$item;
61 61
         $parenthesis_count=0;
62 62
         while (($item < strlen($rule)) // Not end of string AND
63
-            && ( ($rule[$item] != ')' ) || $parenthesis_count > 0) ) // Closing ')' or embeded ()
63
+            && (($rule[$item] != ')') || $parenthesis_count > 0)) // Closing ')' or embeded ()
64 64
         {
65
-            if ($rule[$item] == '"' )
65
+            if ($rule[$item] == '"')
66 66
             { // pass through string
67 67
                 $item++;
68
-                $item=$this->eval_getNext($rule,$item,'"');
68
+                $item=$this->eval_getNext($rule, $item, '"');
69 69
             }
70
-            else{
70
+            else {
71 71
                 if ($rule[$item] == '(')
72 72
                 {
73 73
                     $parenthesis_count++;
@@ -80,23 +80,23 @@  discard block
 block discarded – undo
80 80
             }
81 81
         }
82 82
         
83
-        if ($item==strlen($rule)) {throw new Exception("no closing () in ".$rule ." at " .$item);}
84
-        $val=substr($rule,$start,$item-$start);
83
+        if ($item == strlen($rule)) {throw new Exception("no closing () in ".$rule." at ".$item); }
84
+        $val=substr($rule, $start, $item - $start);
85 85
         $item++;
86 86
         $start=0;
87 87
         //echo "group : ".$val."\n";
88 88
         // returns evaluation of group as type 2 (boolean)
89
-        return array(2,$this->evaluation($val,$start));
89
+        return array(2, $this->evaluation($val, $start));
90 90
     }
91 91
     
92
-    protected function eval_getElement($rule,&$item)
92
+    protected function eval_getElement($rule, &$item)
93 93
     {
94 94
         if ($item >= strlen($rule))
95 95
         {
96
-            throw new Exception("Early end of string ".$rule ." at " .$item );
96
+            throw new Exception("Early end of string ".$rule." at ".$item);
97 97
         }
98
-        while ($rule[$item]==' ') $item++;
99
-        if (preg_match('/[0-9\.]/',$rule[$item]))
98
+        while ($rule[$item] == ' ') $item++;
99
+        if (preg_match('/[0-9\.]/', $rule[$item]))
100 100
         { // number
101 101
             return $this->get_number($rule, $item);
102 102
         }
@@ -109,54 +109,54 @@  discard block
 block discarded – undo
109 109
         { // grouping
110 110
             return $this->get_group($rule, $item);
111 111
         }
112
-        throw new Exception("number/string not found in ".$rule ." at " .$item . ' : ' .$rule[$item]);
112
+        throw new Exception("number/string not found in ".$rule." at ".$item.' : '.$rule[$item]);
113 113
         
114 114
     }
115 115
     
116
-    protected function eval_getNext($rule,$item,$tok)
116
+    protected function eval_getNext($rule, $item, $tok)
117 117
     {
118 118
         while (
119
-            ($rule[$item] != $tok ) 
119
+            ($rule[$item] != $tok) 
120 120
             && ($item < strlen($rule))) 
121 121
         { 
122 122
             $item++;
123 123
         }
124
-        if ($item==strlen($rule)) {
125
-            throw new Exception("closing '".$tok."' not found in ".$rule ." at " .$item);
124
+        if ($item == strlen($rule)) {
125
+            throw new Exception("closing '".$tok."' not found in ".$rule." at ".$item);
126 126
         }
127
-        return $item+1;
127
+        return $item + 1;
128 128
     }
129 129
     
130
-    protected function eval_getOper($rule,&$item)
130
+    protected function eval_getOper($rule, &$item)
131 131
     {
132
-        while ($rule[$item]==' ') $item++;
132
+        while ($rule[$item] == ' ') $item++;
133 133
         switch ($rule[$item])
134 134
         {
135 135
             case '<':
136
-                if ($rule[$item+1]=='=') { $item+=2; return array(0,"<=");}
137
-                $item++; return array(0,"<");
136
+                if ($rule[$item + 1] == '=') { $item+=2; return array(0, "<="); }
137
+                $item++; return array(0, "<");
138 138
             case '>':
139
-                if ($rule[$item+1]=='=') { $item+=2; return array(0,">=");}
140
-                $item++; return array(0,">");
139
+                if ($rule[$item + 1] == '=') { $item+=2; return array(0, ">="); }
140
+                $item++; return array(0, ">");
141 141
             case '=':
142
-                $item++; return array(0,"=");
142
+                $item++; return array(0, "=");
143 143
             case '!':
144
-                if ($rule[$item+1]=='=') { $item+=2; return array(0,"!=");}
145
-                throw new Exception("Erreur in expr - incorrect operator '!'  found in ".$rule ." at " .$item);
144
+                if ($rule[$item + 1] == '=') { $item+=2; return array(0, "!="); }
145
+                throw new Exception("Erreur in expr - incorrect operator '!'  found in ".$rule." at ".$item);
146 146
             case '~':
147
-                $item++; return array(0,"~");
147
+                $item++; return array(0, "~");
148 148
             case '|':
149
-                $item++; return array(1,"|");
149
+                $item++; return array(1, "|");
150 150
             case '&':
151
-                $item++; return array(1,"&");
151
+                $item++; return array(1, "&");
152 152
             default	:
153
-                throw new Exception("Erreur in expr - operator not found in ".$rule ." at " .$item);
153
+                throw new Exception("Erreur in expr - operator not found in ".$rule." at ".$item);
154 154
         }
155 155
     }
156 156
     
157
-    private function check_negate_first($rule,&$item)
157
+    private function check_negate_first($rule, &$item)
158 158
     {
159
-        if ( $rule[$item] == '!') // If '!' found, negate next expression.
159
+        if ($rule[$item] == '!') // If '!' found, negate next expression.
160 160
         {
161 161
             $item++;
162 162
             return true;
@@ -167,21 +167,21 @@  discard block
 block discarded – undo
167 167
         }
168 168
     }
169 169
 
170
-    private function do_compare($val1,$val2,$comp,$negate)
170
+    private function do_compare($val1, $val2, $comp, $negate)
171 171
     {
172
-        switch ($comp){
173
-            case '<':	$retVal= ($val1 < $val2); break;
174
-            case '<=':	$retVal= ($val1 <= $val2); break;
175
-            case '>':	$retVal= ($val1 > $val2); break;
176
-            case '>=':	$retVal= ($val1 >= $val2); break;
177
-            case '=':	$retVal= ($val1 == $val2); break;
178
-            case '!=':	$retVal= ($val1 != $val2); break;
179
-            case '~':	$retVal= (preg_match('/'.preg_replace('/"/','',$val2).'/',$val1)); break;
180
-            case '|':	$retVal= ($val1 || $val2); break;
181
-            case '&':	$retVal= ($val1 && $val2); break;
172
+        switch ($comp) {
173
+            case '<':	$retVal=($val1 < $val2); break;
174
+            case '<=':	$retVal=($val1 <= $val2); break;
175
+            case '>':	$retVal=($val1 > $val2); break;
176
+            case '>=':	$retVal=($val1 >= $val2); break;
177
+            case '=':	$retVal=($val1 == $val2); break;
178
+            case '!=':	$retVal=($val1 != $val2); break;
179
+            case '~':	$retVal=(preg_match('/'.preg_replace('/"/', '', $val2).'/', $val1)); break;
180
+            case '|':	$retVal=($val1 || $val2); break;
181
+            case '&':	$retVal=($val1 && $val2); break;
182 182
             default:  throw new Exception("Error in expression - unknown comp : ".$comp);
183 183
         }
184
-        if ($negate === true) $retVal = ! $retVal; // Inverse result if negate before expression
184
+        if ($negate === true) $retVal=!$retVal; // Inverse result if negate before expression
185 185
         
186 186
         return $retVal;
187 187
     }
@@ -194,56 +194,56 @@  discard block
 block discarded – undo
194 194
      *   comparison int vs strings will return null (error)
195 195
      *	return : bool or null on error
196 196
      */
197
-    public function evaluation($rule,&$item)
197
+    public function evaluation($rule, &$item)
198 198
     {
199 199
         //echo "Evaluation of ".substr($rule,$item)."\n";
200 200
         $negate=$this->check_negate_first($rule, $item);
201 201
         // First element : number, string or ()
202
-        list($type1,$val1) = $this->eval_getElement($rule,$item);
202
+        list($type1, $val1)=$this->eval_getElement($rule, $item);
203 203
         //echo "Elmt1: ".$val1."/".$type1." : ".substr($rule,$item)."\n";
204 204
         
205
-        if ($item==strlen($rule)) // If only element, return value, but only boolean
205
+        if ($item == strlen($rule)) // If only element, return value, but only boolean
206 206
         {
207 207
             if ($type1 != 2) throw new Exception("Cannot use num/string as boolean : ".$rule);
208
-            if ($negate === true) $val1= ! $val1;
208
+            if ($negate === true) $val1=!$val1;
209 209
             return $val1;
210 210
         }
211 211
         
212 212
         // Second element : operator
213
-        list($typec,$comp) = $this->eval_getOper($rule,$item);
213
+        list($typec, $comp)=$this->eval_getOper($rule, $item);
214 214
         //echo "Comp : ".$comp." : ".substr($rule,$item)."\n";
215 215
         
216 216
         // Third element : number, string or ()
217
-        if ( $rule[$item] == '!') // starts with a ! so evaluate whats next
217
+        if ($rule[$item] == '!') // starts with a ! so evaluate whats next
218 218
         {
219 219
             $item++;
220 220
             if ($typec != 1) throw new Exception("Mixing boolean and comparison : ".$rule);
221
-            $val2= ! $this->evaluation($rule,$item);
221
+            $val2=!$this->evaluation($rule, $item);
222 222
             $type2=2; // result is a boolean
223 223
         }
224 224
         else
225 225
         {
226
-            list($type2,$val2) = $this->eval_getElement($rule,$item);
226
+            list($type2, $val2)=$this->eval_getElement($rule, $item);
227 227
         }
228 228
         //echo "Elmt2: ".$val2."/".$type2." : ".substr($rule,$item)."\n";
229 229
         
230
-        if ($type1!=$type2)  // cannot compare different types
230
+        if ($type1 != $type2)  // cannot compare different types
231 231
         {
232 232
             throw new Exception("Cannot compare string & number : ".$rule);
233 233
         }
234
-        if ($typec==1 && $type1 !=2) // cannot use & or | with string/number
234
+        if ($typec == 1 && $type1 != 2) // cannot use & or | with string/number
235 235
         {
236 236
             throw new Exception("Cannot use boolean operators with string & number : ".$rule);
237 237
         }
238 238
         
239
-        $retVal = $this->do_compare($val1, $val2, $comp, $negate);
239
+        $retVal=$this->do_compare($val1, $val2, $comp, $negate);
240 240
         
241
-        if ($item==strlen($rule)) return $retVal; // End of string : return evaluation
241
+        if ($item == strlen($rule)) return $retVal; // End of string : return evaluation
242 242
         // check for logical operator :
243 243
         switch ($rule[$item])
244 244
         {
245
-            case '|':	$item++; return ($retVal || $this->evaluation($rule,$item) );
246
-            case '&':	$item++; return ($retVal && $this->evaluation($rule,$item) );
245
+            case '|':	$item++; return ($retVal || $this->evaluation($rule, $item));
246
+            case '&':	$item++; return ($retVal && $this->evaluation($rule, $item));
247 247
             
248 248
             default:  throw new Exception("Erreur in expr - garbadge at end of expression : ".$rule[$item]);
249 249
         }
@@ -256,17 +256,17 @@  discard block
 block discarded – undo
256 256
         $rule2='';
257 257
         while ($item < strlen($rule))
258 258
         {
259
-            if ($rule[$item]==' ') { $item++; continue; }
260
-            if ($rule[$item]=='"')
259
+            if ($rule[$item] == ' ') { $item++; continue; }
260
+            if ($rule[$item] == '"')
261 261
             {
262 262
                 $rule2.=$rule[$item];
263 263
                 $item++;
264
-                while (($item < strlen($rule)) && ($rule[$item]!='"') )
264
+                while (($item < strlen($rule)) && ($rule[$item] != '"'))
265 265
                 {
266 266
                     $rule2.=$rule[$item];
267 267
                     $item++;
268 268
                 }
269
-                if ($item == strlen ($rule)) throw new Exception("closing '\"' not found in ".$rule ." at " .$item);
269
+                if ($item == strlen($rule)) throw new Exception("closing '\"' not found in ".$rule." at ".$item);
270 270
                 $rule2.=$rule[$item];
271 271
                 $item++;
272 272
                 continue;
@@ -285,14 +285,14 @@  discard block
 block discarded – undo
285 285
      *	@return bool : true : rule match, false : rule don't match , throw exception on error.
286 286
      */
287 287
     
288
-    public function eval_rule($rule,$oidList)
288
+    public function eval_rule($rule, $oidList)
289 289
     {
290
-        if ($rule==null || $rule == '') // Empty rule is always true
290
+        if ($rule == null || $rule == '') // Empty rule is always true
291 291
         {
292 292
             return true;
293 293
         }
294 294
         $matches=array();
295
-        while (preg_match('/_OID\(([0-9\.\*]+)\)/',$rule,$matches) == 1)
295
+        while (preg_match('/_OID\(([0-9\.\*]+)\)/', $rule, $matches) == 1)
296 296
         {
297 297
             $oid=$matches[1];
298 298
             $found=0;
@@ -304,38 +304,38 @@  discard block
 block discarded – undo
304 304
             // replace * with \* in oid for preg_replace
305 305
             $oid=preg_replace('/\*/', '\*', $oid);
306 306
             
307
-            $this->logging->log('OID in rule : '.$oid.' / '.$oidR,DEBUG );
307
+            $this->logging->log('OID in rule : '.$oid.' / '.$oidR, DEBUG);
308 308
             
309
-            foreach($oidList as $val)
309
+            foreach ($oidList as $val)
310 310
             {
311
-                if (preg_match("/^$oidR$/",$val->oid) == 1)
311
+                if (preg_match("/^$oidR$/", $val->oid) == 1)
312 312
                 {
313
-                    if (!preg_match('/^[0-9]*\.?[0-9]+$/',$val->value))
313
+                    if (!preg_match('/^[0-9]*\.?[0-9]+$/', $val->value))
314 314
                     { // If not a number, change " to ' and put " around it
315
-                        $val->value=preg_replace('/"/',"'",$val->value);
315
+                        $val->value=preg_replace('/"/', "'", $val->value);
316 316
                         $val->value='"'.$val->value.'"';
317 317
                     }
318 318
                     $rep=0;
319
-                    $rule=preg_replace('/_OID\('.$oid.'\)/',$val->value,$rule,-1,$rep);
320
-                    if ($rep==0)
319
+                    $rule=preg_replace('/_OID\('.$oid.'\)/', $val->value, $rule, -1, $rep);
320
+                    if ($rep == 0)
321 321
                     {
322
-                        $this->logging->log("Error in rule_eval",WARN,'');
322
+                        $this->logging->log("Error in rule_eval", WARN, '');
323 323
                         return false;
324 324
                     }
325 325
                     $found=1;
326 326
                     break;
327 327
                 }
328 328
             }
329
-            if ($found==0)
329
+            if ($found == 0)
330 330
             {	// OID not found : throw error
331 331
                 throw new Exception('OID '.$oid.' not found in trap');
332 332
             }
333 333
         }
334 334
         $item=0;
335 335
         $rule=$this->eval_cleanup($rule);
336
-        $this->logging->log('Rule after clenup: '.$rule,INFO );
336
+        $this->logging->log('Rule after clenup: '.$rule, INFO);
337 337
         
338
-        return  $this->evaluation($rule,$item);
338
+        return  $this->evaluation($rule, $item);
339 339
     }
340 340
     
341 341
 }
342 342
\ No newline at end of file
Please login to merge, or discard this patch.
Braces   +47 added lines, -20 removed lines patch added patch discarded remove patch
@@ -60,14 +60,15 @@  discard block
 block discarded – undo
60 60
         $start=$item;
61 61
         $parenthesis_count=0;
62 62
         while (($item < strlen($rule)) // Not end of string AND
63
-            && ( ($rule[$item] != ')' ) || $parenthesis_count > 0) ) // Closing ')' or embeded ()
63
+            && ( ($rule[$item] != ')' ) || $parenthesis_count > 0) ) {
64
+        	// Closing ')' or embeded ()
64 65
         {
65 66
             if ($rule[$item] == '"' )
66 67
             { // pass through string
67 68
                 $item++;
69
+        }
68 70
                 $item=$this->eval_getNext($rule,$item,'"');
69
-            }
70
-            else{
71
+            } else{
71 72
                 if ($rule[$item] == '(')
72 73
                 {
73 74
                     $parenthesis_count++;
@@ -95,7 +96,9 @@  discard block
 block discarded – undo
95 96
         {
96 97
             throw new Exception("Early end of string ".$rule ." at " .$item );
97 98
         }
98
-        while ($rule[$item]==' ') $item++;
99
+        while ($rule[$item]==' ') {
100
+        	$item++;
101
+        }
99 102
         if (preg_match('/[0-9\.]/',$rule[$item]))
100 103
         { // number
101 104
             return $this->get_number($rule, $item);
@@ -129,7 +132,9 @@  discard block
 block discarded – undo
129 132
     
130 133
     protected function eval_getOper($rule,&$item)
131 134
     {
132
-        while ($rule[$item]==' ') $item++;
135
+        while ($rule[$item]==' ') {
136
+        	$item++;
137
+        }
133 138
         switch ($rule[$item])
134 139
         {
135 140
             case '<':
@@ -156,12 +161,13 @@  discard block
 block discarded – undo
156 161
     
157 162
     private function check_negate_first($rule,&$item)
158 163
     {
159
-        if ( $rule[$item] == '!') // If '!' found, negate next expression.
164
+        if ( $rule[$item] == '!') {
165
+        	// If '!' found, negate next expression.
160 166
         {
161 167
             $item++;
162
-            return true;
163 168
         }
164
-        else
169
+            return true;
170
+        } else
165 171
         {
166 172
             return false;
167 173
         }
@@ -181,7 +187,10 @@  discard block
 block discarded – undo
181 187
             case '&':	$retVal= ($val1 && $val2); break;
182 188
             default:  throw new Exception("Error in expression - unknown comp : ".$comp);
183 189
         }
184
-        if ($negate === true) $retVal = ! $retVal; // Inverse result if negate before expression
190
+        if ($negate === true) {
191
+        	$retVal = ! $retVal;
192
+        }
193
+        // Inverse result if negate before expression
185 194
         
186 195
         return $retVal;
187 196
     }
@@ -202,10 +211,14 @@  discard block
 block discarded – undo
202 211
         list($type1,$val1) = $this->eval_getElement($rule,$item);
203 212
         //echo "Elmt1: ".$val1."/".$type1." : ".substr($rule,$item)."\n";
204 213
         
205
-        if ($item==strlen($rule)) // If only element, return value, but only boolean
214
+        if ($item==strlen($rule)) {
215
+        	// If only element, return value, but only boolean
206 216
         {
207 217
             if ($type1 != 2) throw new Exception("Cannot use num/string as boolean : ".$rule);
208
-            if ($negate === true) $val1= ! $val1;
218
+        }
219
+            if ($negate === true) {
220
+            	$val1= ! $val1;
221
+            }
209 222
             return $val1;
210 223
         }
211 224
         
@@ -214,31 +227,41 @@  discard block
 block discarded – undo
214 227
         //echo "Comp : ".$comp." : ".substr($rule,$item)."\n";
215 228
         
216 229
         // Third element : number, string or ()
217
-        if ( $rule[$item] == '!') // starts with a ! so evaluate whats next
230
+        if ( $rule[$item] == '!') {
231
+        	// starts with a ! so evaluate whats next
218 232
         {
219 233
             $item++;
220
-            if ($typec != 1) throw new Exception("Mixing boolean and comparison : ".$rule);
234
+        }
235
+            if ($typec != 1) {
236
+            	throw new Exception("Mixing boolean and comparison : ".$rule);
237
+            }
221 238
             $val2= ! $this->evaluation($rule,$item);
222 239
             $type2=2; // result is a boolean
223
-        }
224
-        else
240
+        } else
225 241
         {
226 242
             list($type2,$val2) = $this->eval_getElement($rule,$item);
227 243
         }
228 244
         //echo "Elmt2: ".$val2."/".$type2." : ".substr($rule,$item)."\n";
229 245
         
230
-        if ($type1!=$type2)  // cannot compare different types
246
+        if ($type1!=$type2) {
247
+        	// cannot compare different types
231 248
         {
232 249
             throw new Exception("Cannot compare string & number : ".$rule);
233 250
         }
234
-        if ($typec==1 && $type1 !=2) // cannot use & or | with string/number
251
+        }
252
+        if ($typec==1 && $type1 !=2) {
253
+        	// cannot use & or | with string/number
235 254
         {
236 255
             throw new Exception("Cannot use boolean operators with string & number : ".$rule);
237 256
         }
257
+        }
238 258
         
239 259
         $retVal = $this->do_compare($val1, $val2, $comp, $negate);
240 260
         
241
-        if ($item==strlen($rule)) return $retVal; // End of string : return evaluation
261
+        if ($item==strlen($rule)) {
262
+        	return $retVal;
263
+        }
264
+        // End of string : return evaluation
242 265
         // check for logical operator :
243 266
         switch ($rule[$item])
244 267
         {
@@ -266,7 +289,9 @@  discard block
 block discarded – undo
266 289
                     $rule2.=$rule[$item];
267 290
                     $item++;
268 291
                 }
269
-                if ($item == strlen ($rule)) throw new Exception("closing '\"' not found in ".$rule ." at " .$item);
292
+                if ($item == strlen ($rule)) {
293
+                	throw new Exception("closing '\"' not found in ".$rule ." at " .$item);
294
+                }
270 295
                 $rule2.=$rule[$item];
271 296
                 $item++;
272 297
                 continue;
@@ -287,10 +312,12 @@  discard block
 block discarded – undo
287 312
     
288 313
     public function eval_rule($rule,$oidList)
289 314
     {
290
-        if ($rule==null || $rule == '') // Empty rule is always true
315
+        if ($rule==null || $rule == '') {
316
+        	// Empty rule is always true
291 317
         {
292 318
             return true;
293 319
         }
320
+        }
294 321
         $matches=array();
295 322
         while (preg_match('/_OID\(([0-9\.\*]+)\)/',$rule,$matches) == 1)
296 323
         {
Please login to merge, or discard this patch.