Completed
Push — master ( bbeb50...6a1f5a )
by Patrick
02:23 queued 10s
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->logging->log('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->logging->log('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->logging->log('Error in updating : ' . $e->getMessage(),2);
91
+                    $trap->logging->log('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->logging->log('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.
application/controllers/SettingsController.php 3 patches
Braces   +17 added lines, -17 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
           }
@@ -141,8 +140,7 @@  discard block
 block discarded – undo
141 140
               $this->view->apimessage='API config : ' . $e->getMessage();
142 141
               $this->view->apimessageError=true;
143 142
           }
144
-      }
145
-      else
143
+      } else
146 144
       {
147 145
           $this->view->apimessage='API parameters not configured';
148 146
           $this->view->apimessageError=true;
@@ -208,7 +206,9 @@  discard block
 block discarded – undo
208 206
           $input="154865134987aaaa";
209 207
           exec("$phpBin -r \"echo '$input';\"",$output,$retCode);
210 208
           
211
-          if (! isset($output[0])) $output[0]="NO OUT";
209
+          if (! isset($output[0])) {
210
+          	$output[0]="NO OUT";
211
+          }
212 212
           
213 213
           if ($retCode == 0 && preg_match("/$input/",$output[0]) == 1)
214 214
           {
@@ -310,8 +310,7 @@  discard block
 block discarded – undo
310 310
 	    $this->getUIDatabase()->testGetDb(); // Get DB in test mode
311 311
 	    printf('Schema already exists');
312 312
 	    
313
-	} 
314
-	catch (DBException $e) 
313
+	} catch (DBException $e) 
315 314
 	{
316 315
 
317 316
 		printf('Creating schema : <br>');
@@ -367,8 +366,7 @@  discard block
 block discarded – undo
367 366
           $this->getUIDatabase()->testGetDb(); // Get DB in test mode
368 367
           echo 'Schema already exists and is up to date<br>';
369 368
           return;
370
-      }
371
-      catch (DBException $e)
369
+      } catch (DBException $e)
372 370
       {
373 371
           $dberror=$e->getArray(); 
374 372
       }
@@ -452,16 +450,18 @@  discard block
 block discarded – undo
452 450
           }
453 451
           // Assume there is only one line... TODO : see if there is a better way to do this
454 452
           $line = preg_replace('/^.*snmptrapd /','',$psOutput[0]);
455
-          if (!preg_match('/-n/',$line))
456
-              return array(1,'snmptrapd has no -n option : '.$line);
457
-          if (!preg_match('/-O[^ ]*n/',$line))
458
-              return array(1,'snmptrapd has no -On option : '.$line);
459
-          if (!preg_match('/-O[^ ]*e/',$line))
460
-              return array(1,'snmptrapd has no -Oe option : '.$line);
453
+          if (!preg_match('/-n/',$line)) {
454
+                        return array(1,'snmptrapd has no -n option : '.$line);
455
+          }
456
+          if (!preg_match('/-O[^ ]*n/',$line)) {
457
+                        return array(1,'snmptrapd has no -On option : '.$line);
458
+          }
459
+          if (!preg_match('/-O[^ ]*e/',$line)) {
460
+                        return array(1,'snmptrapd has no -Oe option : '.$line);
461
+          }
461 462
 
462 463
           return array(0,'snmptrapd listening to UDP/162, options : '.$line);
463
-      }
464
-      else
464
+      } else
465 465
       {
466 466
           return array(0,'A daemon (hidden by SELinux) is listening on UDP/162');
467 467
       }
Please login to merge, or discard this patch.
Indentation   +231 added lines, -231 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,56 +71,56 @@  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
-      try {
88
-          $this->getUIDatabase()->testGetDb(); // Get DB in test mode
89
-          $dberror=array(0,'');
90
-      } catch (DBException $e) {
91
-          $dberror = $e->getArray();
92
-      }
87
+	  try {
88
+		  $this->getUIDatabase()->testGetDb(); // Get DB in test mode
89
+		  $dberror=array(0,'');
90
+	  } catch (DBException $e) {
91
+		  $dberror = $e->getArray();
92
+	  }
93 93
       
94
-      $this->view->db_error=$dberror[0];
95
-      switch ($dberror[0])
96
-      {
97
-          case 2:
98
-          case 4:
99
-              $db_message[$dberror[0]][1] .= $dberror[1];
100
-              break;
101
-          case 3:
102
-              $db_message[$dberror[0]][1] .= $dberror[1] . ', Message : ' . $dberror[2];
103
-              break;
104
-          case 5:
105
-              $db_message[$dberror[0]][1] .= ' version '. $dberror[1] . ', version needed : ' .$dberror[2];
106
-              break;
107
-          case 0:
108
-          case 1:
109
-              break;
110
-          default:
111
-              new ProgrammingError('Out of bond result from database test');
112
-      }
113
-      $this->view->message=$db_message;
94
+	  $this->view->db_error=$dberror[0];
95
+	  switch ($dberror[0])
96
+	  {
97
+		  case 2:
98
+		  case 4:
99
+			  $db_message[$dberror[0]][1] .= $dberror[1];
100
+			  break;
101
+		  case 3:
102
+			  $db_message[$dberror[0]][1] .= $dberror[1] . ', Message : ' . $dberror[2];
103
+			  break;
104
+		  case 5:
105
+			  $db_message[$dberror[0]][1] .= ' version '. $dberror[1] . ', version needed : ' .$dberror[2];
106
+			  break;
107
+		  case 0:
108
+		  case 1:
109
+			  break;
110
+		  default:
111
+			  new ProgrammingError('Out of bond result from database test');
112
+	  }
113
+	  $this->view->message=$db_message;
114 114
       
115
-      try {
116
-          $this->getUIDatabase()->testGetIdoDb(); // Get DB in test mode
117
-          $dberror=array(0,'');
118
-      } catch (DBException $e) {
119
-          $dberror = $e->getArray();
120
-      }
115
+	  try {
116
+		  $this->getUIDatabase()->testGetIdoDb(); // Get DB in test mode
117
+		  $dberror=array(0,'');
118
+	  } catch (DBException $e) {
119
+		  $dberror = $e->getArray();
120
+	  }
121 121
       
122
-      $this->view->ido_db_error=$dberror[0];
123
-      $this->view->ido_message='IDO Database : ' . $dberror[1];
122
+	  $this->view->ido_db_error=$dberror[0];
123
+	  $this->view->ido_message='IDO Database : ' . $dberror[1];
124 124
   }
125 125
   
126 126
   /**
@@ -130,23 +130,23 @@  discard block
 block discarded – undo
130 130
    */
131 131
   private function check_api()
132 132
   {
133
-      if ($this->Config()->get('config', 'icingaAPI_host') != '')
134
-      {
135
-          $apitest=new Icinga2Api($this->Config()->get('config', 'icingaAPI_host'),$this->Config()->get('config', 'icingaAPI_port'));
136
-          $apitest->setCredentials($this->Config()->get('config', 'icingaAPI_user'), $this->Config()->get('config', 'icingaAPI_password'));
137
-          try {
138
-              list($this->view->apimessageError,$this->view->apimessage)=$apitest->test($this->getModuleConfig()::getapiUserPermissions());
139
-              //$this->view->apimessageError=false;
140
-          } catch (RuntimeException $e) {
141
-              $this->view->apimessage='API config : ' . $e->getMessage();
142
-              $this->view->apimessageError=true;
143
-          }
144
-      }
145
-      else
146
-      {
147
-          $this->view->apimessage='API parameters not configured';
148
-          $this->view->apimessageError=true;
149
-      }
133
+	  if ($this->Config()->get('config', 'icingaAPI_host') != '')
134
+	  {
135
+		  $apitest=new Icinga2Api($this->Config()->get('config', 'icingaAPI_host'),$this->Config()->get('config', 'icingaAPI_port'));
136
+		  $apitest->setCredentials($this->Config()->get('config', 'icingaAPI_user'), $this->Config()->get('config', 'icingaAPI_password'));
137
+		  try {
138
+			  list($this->view->apimessageError,$this->view->apimessage)=$apitest->test($this->getModuleConfig()::getapiUserPermissions());
139
+			  //$this->view->apimessageError=false;
140
+		  } catch (RuntimeException $e) {
141
+			  $this->view->apimessage='API config : ' . $e->getMessage();
142
+			  $this->view->apimessageError=true;
143
+		  }
144
+	  }
145
+	  else
146
+	  {
147
+		  $this->view->apimessage='API parameters not configured';
148
+		  $this->view->apimessageError=true;
149
+	  }
150 150
   }
151 151
 
152 152
   /**
@@ -157,21 +157,21 @@  discard block
 block discarded – undo
157 157
    */
158 158
   private function check_icingaweb_path()
159 159
   {
160
-      $this->view->icingaEtcWarn=0;
161
-      $icingaweb2_etc=$this->Config()->get('config', 'icingaweb2_etc');
162
-      if ($icingaweb2_etc != "/etc/icingaweb2/" && $icingaweb2_etc != '')
163
-      {
164
-          $output=array();
160
+	  $this->view->icingaEtcWarn=0;
161
+	  $icingaweb2_etc=$this->Config()->get('config', 'icingaweb2_etc');
162
+	  if ($icingaweb2_etc != "/etc/icingaweb2/" && $icingaweb2_etc != '')
163
+	  {
164
+		  $output=array();
165 165
           
166
-          exec('cat ' . $this->module->getBaseDir() .'/bin/trap_in.php | grep "\$icingaweb2Etc=" ',$output);
166
+		  exec('cat ' . $this->module->getBaseDir() .'/bin/trap_in.php | grep "\$icingaweb2Etc=" ',$output);
167 167
           
168 168
           
169
-          if (! isset($output[0]) || ! preg_match('#"'. $icingaweb2_etc .'"#',$output[0]))
170
-          {
171
-              $this->view->icingaEtcWarn=1;
172
-              $this->view->icingaweb2_etc=$icingaweb2_etc;
173
-          }
174
-      }
169
+		  if (! isset($output[0]) || ! preg_match('#"'. $icingaweb2_etc .'"#',$output[0]))
170
+		  {
171
+			  $this->view->icingaEtcWarn=1;
172
+			  $this->view->icingaweb2_etc=$icingaweb2_etc;
173
+		  }
174
+	  }
175 175
       
176 176
   }
177 177
   
@@ -182,15 +182,15 @@  discard block
 block discarded – undo
182 182
    */
183 183
   private function get_db_list($allowed)
184 184
   {
185
-      $resources = array();
186
-      foreach (ResourceFactory::getResourceConfigs() as $name => $resource) 
187
-      {
188
-          if ($resource->get('type') === 'db' && in_array($resource->get('db'), $allowed)) 
189
-          {
190
-              $resources[$name] = $name;
191
-          }
192
-      }
193
-      return $resources;
185
+	  $resources = array();
186
+	  foreach (ResourceFactory::getResourceConfigs() as $name => $resource) 
187
+	  {
188
+		  if ($resource->get('type') === 'db' && in_array($resource->get('db'), $allowed)) 
189
+		  {
190
+			  $resources[$name] = $name;
191
+		  }
192
+	  }
193
+	  return $resources;
194 194
   }
195 195
   
196 196
   /**
@@ -199,23 +199,23 @@  discard block
 block discarded – undo
199 199
    */
200 200
   private function get_php_binary()
201 201
   {
202
-      $phpBinary= array( PHP_BINARY, PHP_BINDIR . "/php", '/usr/bin/php');
202
+	  $phpBinary= array( PHP_BINARY, PHP_BINDIR . "/php", '/usr/bin/php');
203 203
 
204
-      foreach ($phpBinary as $phpBin )
205
-      {
206
-          $output=array();
207
-          $retCode=255;
208
-          $input="154865134987aaaa";
209
-          exec("$phpBin -r \"echo '$input';\"",$output,$retCode);
204
+	  foreach ($phpBinary as $phpBin )
205
+	  {
206
+		  $output=array();
207
+		  $retCode=255;
208
+		  $input="154865134987aaaa";
209
+		  exec("$phpBin -r \"echo '$input';\"",$output,$retCode);
210 210
           
211
-          if (! isset($output[0])) $output[0]="NO OUT";
211
+		  if (! isset($output[0])) $output[0]="NO OUT";
212 212
           
213
-          if ($retCode == 0 && preg_match("/$input/",$output[0]) == 1)
214
-          {
215
-              return $phpBin;
216
-          }          
217
-      }
218
-      return NULL;
213
+		  if ($retCode == 0 && preg_match("/$input/",$output[0]) == 1)
214
+		  {
215
+			  return $phpBin;
216
+		  }          
217
+	  }
218
+	  return NULL;
219 219
   }
220 220
   
221 221
   /**
@@ -234,7 +234,7 @@  discard block
 block discarded – undo
234 234
   public function indexAction()
235 235
   {
236 236
       
237
-    // CHeck permissions : display tests in any case, but no configuration.
237
+	// CHeck permissions : display tests in any case, but no configuration.
238 238
 	$this->view->configPermission=$this->checkModuleConfigPermission(1);
239 239
 	// But check read permission
240 240
 	$this->checkReadPermission();
@@ -242,16 +242,16 @@  discard block
 block discarded – undo
242 242
 	$this->view->tabs = $this->Module()->getConfigTabs()->activate('config');	
243 243
 	
244 244
 	// Get message : sent on configuration problems detected by controllers
245
-    $this->get_param();
245
+	$this->get_param();
246 246
     
247
-    // Test if configuration exists, if not create for installer script
247
+	// Test if configuration exists, if not create for installer script
248 248
 	$this->check_empty_config();
249 249
 
250 250
 	// Test Database
251
-    $this->check_db();
251
+	$this->check_db();
252 252
 	
253 253
 	//********* Test API
254
-    $this->check_api();
254
+	$this->check_api();
255 255
 	
256 256
 	//*********** Test snmptrapd alive and options
257 257
 	list ($this->view->snmptrapdError, $this->view->snmptrapdMessage) = $this->checkSnmpTrapd();
@@ -265,7 +265,7 @@  discard block
 block discarded – undo
265 265
 	$phpBinary = $this->get_php_binary();
266 266
 	if ($phpBinary == null)
267 267
 	{
268
-	    $phpBinary = ' PHP BINARY NOT FOUND ';
268
+		$phpBinary = ' PHP BINARY NOT FOUND ';
269 269
 	    
270 270
 	}
271 271
 	
@@ -273,11 +273,11 @@  discard block
 block discarded – undo
273 273
 	$this->view->traps_in_config= $phpBinary . ' ' . $this->Module()->getBaseDir() . '/bin/trap_in.php';
274 274
 	
275 275
 	$this->view->installer= $this->Module()->getBaseDir() . '/bin/installer.sh '
276
-	    . ' -c all ' 
277
-	    . ' -d ' . $this->Module()->getBaseDir()
278
-	    . ' -p ' . $phpBinary
279
-	    . ' -a ' . exec('whoami')
280
-	    . ' -w ' . Icinga::app()->getConfigDir();
276
+		. ' -c all ' 
277
+		. ' -d ' . $this->Module()->getBaseDir()
278
+		. ' -p ' . $phpBinary
279
+		. ' -a ' . exec('whoami')
280
+		. ' -w ' . Icinga::app()->getConfigDir();
281 281
 	        
282 282
 	// ******************* configuration form setup*******************
283 283
 	$this->view->form = $form = new TrapsConfigForm();
@@ -311,15 +311,15 @@  discard block
 block discarded – undo
311 311
   public function satelliteAction()
312 312
   {
313 313
       
314
-      // CHeck permissions
315
-      $this->view->configPermission=$this->checkModuleConfigPermission();
314
+	  // CHeck permissions
315
+	  $this->view->configPermission=$this->checkModuleConfigPermission();
316 316
       
317
-      // Setup tabs
318
-      $this->view->tabs = $this->Module()->getConfigTabs()->activate('satellite');	
317
+	  // Setup tabs
318
+	  $this->view->tabs = $this->Module()->getConfigTabs()->activate('satellite');	
319 319
       
320
-      $this->view->masterHASet = FALSE;
320
+	  $this->view->masterHASet = FALSE;
321 321
       
322
-      $this->view->masterHAConf = array ('name' => 'masterHA1', 'icingaweb2 user'=>'User1');
322
+	  $this->view->masterHAConf = array ('name' => 'masterHA1', 'icingaweb2 user'=>'User1');
323 323
   }
324 324
   
325 325
   
@@ -335,8 +335,8 @@  discard block
 block discarded – undo
335 335
 	
336 336
 	try 
337 337
 	{
338
-	    $this->getUIDatabase()->testGetDb(); // Get DB in test mode
339
-	    printf('Schema already exists');
338
+		$this->getUIDatabase()->testGetDb(); // Get DB in test mode
339
+		printf('Schema already exists');
340 340
 	    
341 341
 	} 
342 342
 	catch (DBException $e) 
@@ -347,19 +347,19 @@  discard block
 block discarded – undo
347 347
 		// Get module database name
348 348
 		$dbName=$this->Config()->get('config', 'database');
349 349
 
350
-        $dbResource = ResourceFactory::getResourceConfig($dbName);
351
-        $dbType=$dbResource->get('db');
352
-        switch ($dbType) {
353
-          case 'mysql':
354
-              $dbFileExt='sql';
355
-              break;
356
-          case 'pgsql':
357
-              $dbFileExt='pgsql';
358
-              break;
359
-          default:
360
-              printf("Database configuration error : Unsuported DB");
361
-              return;
362
-        } 
350
+		$dbResource = ResourceFactory::getResourceConfig($dbName);
351
+		$dbType=$dbResource->get('db');
352
+		switch ($dbType) {
353
+		  case 'mysql':
354
+			  $dbFileExt='sql';
355
+			  break;
356
+		  case 'pgsql':
357
+			  $dbFileExt='pgsql';
358
+			  break;
359
+		  default:
360
+			  printf("Database configuration error : Unsuported DB");
361
+			  return;
362
+		} 
363 363
 
364 364
 		printf('<pre>');
365 365
 		require_once $this->Module()->getBaseDir() .'/bin/trap_class.php';
@@ -383,32 +383,32 @@  discard block
 block discarded – undo
383 383
   public function updateschemaAction()
384 384
   {
385 385
 	  $this->checkModuleConfigPermission();
386
-      $this->getTabs()->add('get',array(
387
-    		'active'	=> true,
388
-    		'label'		=> $this->translate('Update Schema'),
389
-    		'url'		=> Url::fromRequest()
390
-    	));
386
+	  $this->getTabs()->add('get',array(
387
+			'active'	=> true,
388
+			'label'		=> $this->translate('Update Schema'),
389
+			'url'		=> Url::fromRequest()
390
+		));
391 391
 	  // check if needed
392 392
 	  $dberror=array();
393
-      try
394
-      {
395
-          $this->getUIDatabase()->testGetDb(); // Get DB in test mode
396
-          echo 'Schema already exists and is up to date<br>';
397
-          return;
398
-      }
399
-      catch (DBException $e)
400
-      {
401
-          $dberror=$e->getArray(); 
402
-      }
393
+	  try
394
+	  {
395
+		  $this->getUIDatabase()->testGetDb(); // Get DB in test mode
396
+		  echo 'Schema already exists and is up to date<br>';
397
+		  return;
398
+	  }
399
+	  catch (DBException $e)
400
+	  {
401
+		  $dberror=$e->getArray(); 
402
+	  }
403 403
 	  
404 404
 	  echo 'Return to <a href="' . Url::fromPath('trapdirector/settings') .'" class="link-button icon-wrench"> settings page </a><br><br>';
405 405
 	  
406 406
 	  if ($dberror[0] != 5)
407 407
 	  {
408
-	      echo 'Database does not exists or is not setup correctly<br>';
409
-	      return;
408
+		  echo 'Database does not exists or is not setup correctly<br>';
409
+		  return;
410 410
 	  }
411
-      // setup
411
+	  // setup
412 412
 	  require_once($this->Module()->getBaseDir() .'/bin/trap_class.php');
413 413
 	  $icingaweb2_etc=$this->Config()->get('config', 'icingaweb2_etc');
414 414
 	  $debug_level=4;
@@ -421,20 +421,20 @@  discard block
 block discarded – undo
421 421
 	  $target_version=$dberror[2];
422 422
 	  
423 423
 	  if ($this->params->get('msgok') == null) {
424
-	      // Check for messages and display if any
425
-              echo "Upgrade databse is going to start.<br>Don't forget to backup your database before update<br>";
426
-	      $Trap->setLogging(2,'syslog');
427
-	      $message = $Trap->trapsDB->update_schema($updateSchema,$target_version,$prefix,true);
428
-	      if ($message != '')
429
-	      {
430
-	          echo 'Note :<br><pre>';
431
-	          echo $message;
432
-	          echo '</pre>';
433
-	          echo '<br>';
434
-	          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>';
435
-	          echo '<br>';
436
-	          return;
437
-	      }
424
+		  // Check for messages and display if any
425
+			  echo "Upgrade databse is going to start.<br>Don't forget to backup your database before update<br>";
426
+		  $Trap->setLogging(2,'syslog');
427
+		  $message = $Trap->trapsDB->update_schema($updateSchema,$target_version,$prefix,true);
428
+		  if ($message != '')
429
+		  {
430
+			  echo 'Note :<br><pre>';
431
+			  echo $message;
432
+			  echo '</pre>';
433
+			  echo '<br>';
434
+			  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>';
435
+			  echo '<br>';
436
+			  return;
437
+		  }
438 438
 	  }
439 439
 	  
440 440
 	  $Trap->setLogging($debug_level,'display');
@@ -449,50 +449,50 @@  discard block
 block discarded – undo
449 449
   
450 450
   private function checkSnmpTrapd()
451 451
   {
452
-      $psOutput=array();
453
-      // First check is someone is listening to port 162. As not root, we can't have pid... 
454
-      $sspath = exec('which ss 2>/dev/null');
455
-      if(empty($sspath))
456
-      {
457
-          // RHEL based systems
458
-          $sspath = '/usr/sbin/ss';
459
-      }
460
-      if(!is_executable("$sspath"))
461
-      {
462
-          return array(1,"Can not execute $sspath");
463
-      }
464
-      exec("$sspath -lun | grep ':162 '",$psOutput);
465
-      if (count($psOutput) == 0)
466
-      {
467
-          return array(1,'Port UDP/162 is not open : is snmptrapd running?');
468
-      }
469
-      $psOutput=array();
470
-      $selinux_state = '';
471
-      if(is_executable('/usr/sbin/getenforce'))
472
-      {
473
-          $selinux_state = exec('/usr/sbin/getenforce 2>/dev/null');
474
-      }
475
-      if($selinux_state !== 'Enforcing')
476
-      {
477
-          exec('ps --no-headers -o command -C snmptrapd',$psOutput);
478
-          if (count($psOutput) == 0)
479
-          {
480
-              return array(1,"UDP/162 : OK, but no snmptrapd process (?)");
481
-          }
482
-          // Assume there is only one line... TODO : see if there is a better way to do this
483
-          $line = preg_replace('/^.*snmptrapd /','',$psOutput[0]);
484
-          if (!preg_match('/-n/',$line))
485
-              return array(1,'snmptrapd has no -n option : '.$line);
486
-          if (!preg_match('/-O[^ ]*n/',$line))
487
-              return array(1,'snmptrapd has no -On option : '.$line);
488
-          if (!preg_match('/-O[^ ]*e/',$line))
489
-              return array(1,'snmptrapd has no -Oe option : '.$line);
452
+	  $psOutput=array();
453
+	  // First check is someone is listening to port 162. As not root, we can't have pid... 
454
+	  $sspath = exec('which ss 2>/dev/null');
455
+	  if(empty($sspath))
456
+	  {
457
+		  // RHEL based systems
458
+		  $sspath = '/usr/sbin/ss';
459
+	  }
460
+	  if(!is_executable("$sspath"))
461
+	  {
462
+		  return array(1,"Can not execute $sspath");
463
+	  }
464
+	  exec("$sspath -lun | grep ':162 '",$psOutput);
465
+	  if (count($psOutput) == 0)
466
+	  {
467
+		  return array(1,'Port UDP/162 is not open : is snmptrapd running?');
468
+	  }
469
+	  $psOutput=array();
470
+	  $selinux_state = '';
471
+	  if(is_executable('/usr/sbin/getenforce'))
472
+	  {
473
+		  $selinux_state = exec('/usr/sbin/getenforce 2>/dev/null');
474
+	  }
475
+	  if($selinux_state !== 'Enforcing')
476
+	  {
477
+		  exec('ps --no-headers -o command -C snmptrapd',$psOutput);
478
+		  if (count($psOutput) == 0)
479
+		  {
480
+			  return array(1,"UDP/162 : OK, but no snmptrapd process (?)");
481
+		  }
482
+		  // Assume there is only one line... TODO : see if there is a better way to do this
483
+		  $line = preg_replace('/^.*snmptrapd /','',$psOutput[0]);
484
+		  if (!preg_match('/-n/',$line))
485
+			  return array(1,'snmptrapd has no -n option : '.$line);
486
+		  if (!preg_match('/-O[^ ]*n/',$line))
487
+			  return array(1,'snmptrapd has no -On option : '.$line);
488
+		  if (!preg_match('/-O[^ ]*e/',$line))
489
+			  return array(1,'snmptrapd has no -Oe option : '.$line);
490 490
 
491
-          return array(0,'snmptrapd listening to UDP/162, options : '.$line);
492
-      }
493
-      else
494
-      {
495
-          return array(0,'A daemon (hidden by SELinux) is listening on UDP/162');
496
-      }
491
+		  return array(0,'snmptrapd listening to UDP/162, options : '.$line);
492
+	  }
493
+	  else
494
+	  {
495
+		  return array(0,'A daemon (hidden by SELinux) is listening on UDP/162');
496
+	  }
497 497
   }
498 498
 }
Please login to merge, or discard this patch.
Spacing   +85 added lines, -85 removed lines patch added patch discarded remove patch
@@ -72,23 +72,23 @@  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
       
87 87
       try {
88 88
           $this->getUIDatabase()->testGetDb(); // Get DB in test mode
89
-          $dberror=array(0,'');
89
+          $dberror=array(0, '');
90 90
       } catch (DBException $e) {
91
-          $dberror = $e->getArray();
91
+          $dberror=$e->getArray();
92 92
       }
93 93
       
94 94
       $this->view->db_error=$dberror[0];
@@ -96,13 +96,13 @@  discard block
 block discarded – undo
96 96
       {
97 97
           case 2:
98 98
           case 4:
99
-              $db_message[$dberror[0]][1] .= $dberror[1];
99
+              $db_message[$dberror[0]][1].=$dberror[1];
100 100
               break;
101 101
           case 3:
102
-              $db_message[$dberror[0]][1] .= $dberror[1] . ', Message : ' . $dberror[2];
102
+              $db_message[$dberror[0]][1].=$dberror[1].', Message : '.$dberror[2];
103 103
               break;
104 104
           case 5:
105
-              $db_message[$dberror[0]][1] .= ' version '. $dberror[1] . ', version needed : ' .$dberror[2];
105
+              $db_message[$dberror[0]][1].=' version '.$dberror[1].', version needed : '.$dberror[2];
106 106
               break;
107 107
           case 0:
108 108
           case 1:
@@ -114,13 +114,13 @@  discard block
 block discarded – undo
114 114
       
115 115
       try {
116 116
           $this->getUIDatabase()->testGetIdoDb(); // Get DB in test mode
117
-          $dberror=array(0,'');
117
+          $dberror=array(0, '');
118 118
       } catch (DBException $e) {
119
-          $dberror = $e->getArray();
119
+          $dberror=$e->getArray();
120 120
       }
121 121
       
122 122
       $this->view->ido_db_error=$dberror[0];
123
-      $this->view->ido_message='IDO Database : ' . $dberror[1];
123
+      $this->view->ido_message='IDO Database : '.$dberror[1];
124 124
   }
125 125
   
126 126
   /**
@@ -132,13 +132,13 @@  discard block
 block discarded – undo
132 132
   {
133 133
       if ($this->Config()->get('config', 'icingaAPI_host') != '')
134 134
       {
135
-          $apitest=new Icinga2Api($this->Config()->get('config', 'icingaAPI_host'),$this->Config()->get('config', 'icingaAPI_port'));
135
+          $apitest=new Icinga2Api($this->Config()->get('config', 'icingaAPI_host'), $this->Config()->get('config', 'icingaAPI_port'));
136 136
           $apitest->setCredentials($this->Config()->get('config', 'icingaAPI_user'), $this->Config()->get('config', 'icingaAPI_password'));
137 137
           try {
138
-              list($this->view->apimessageError,$this->view->apimessage)=$apitest->test($this->getModuleConfig()::getapiUserPermissions());
138
+              list($this->view->apimessageError, $this->view->apimessage)=$apitest->test($this->getModuleConfig()::getapiUserPermissions());
139 139
               //$this->view->apimessageError=false;
140 140
           } catch (RuntimeException $e) {
141
-              $this->view->apimessage='API config : ' . $e->getMessage();
141
+              $this->view->apimessage='API config : '.$e->getMessage();
142 142
               $this->view->apimessageError=true;
143 143
           }
144 144
       }
@@ -163,10 +163,10 @@  discard block
 block discarded – undo
163 163
       {
164 164
           $output=array();
165 165
           
166
-          exec('cat ' . $this->module->getBaseDir() .'/bin/trap_in.php | grep "\$icingaweb2Etc=" ',$output);
166
+          exec('cat '.$this->module->getBaseDir().'/bin/trap_in.php | grep "\$icingaweb2Etc=" ', $output);
167 167
           
168 168
           
169
-          if (! isset($output[0]) || ! preg_match('#"'. $icingaweb2_etc .'"#',$output[0]))
169
+          if (!isset($output[0]) || !preg_match('#"'.$icingaweb2_etc.'"#', $output[0]))
170 170
           {
171 171
               $this->view->icingaEtcWarn=1;
172 172
               $this->view->icingaweb2_etc=$icingaweb2_etc;
@@ -182,12 +182,12 @@  discard block
 block discarded – undo
182 182
    */
183 183
   private function get_db_list($allowed)
184 184
   {
185
-      $resources = array();
185
+      $resources=array();
186 186
       foreach (ResourceFactory::getResourceConfigs() as $name => $resource) 
187 187
       {
188 188
           if ($resource->get('type') === 'db' && in_array($resource->get('db'), $allowed)) 
189 189
           {
190
-              $resources[$name] = $name;
190
+              $resources[$name]=$name;
191 191
           }
192 192
       }
193 193
       return $resources;
@@ -199,18 +199,18 @@  discard block
 block discarded – undo
199 199
    */
200 200
   private function get_php_binary()
201 201
   {
202
-      $phpBinary= array( PHP_BINARY, PHP_BINDIR . "/php", '/usr/bin/php');
202
+      $phpBinary=array(PHP_BINARY, PHP_BINDIR."/php", '/usr/bin/php');
203 203
 
204
-      foreach ($phpBinary as $phpBin )
204
+      foreach ($phpBinary as $phpBin)
205 205
       {
206 206
           $output=array();
207 207
           $retCode=255;
208 208
           $input="154865134987aaaa";
209
-          exec("$phpBin -r \"echo '$input';\"",$output,$retCode);
209
+          exec("$phpBin -r \"echo '$input';\"", $output, $retCode);
210 210
           
211
-          if (! isset($output[0])) $output[0]="NO OUT";
211
+          if (!isset($output[0])) $output[0]="NO OUT";
212 212
           
213
-          if ($retCode == 0 && preg_match("/$input/",$output[0]) == 1)
213
+          if ($retCode == 0 && preg_match("/$input/", $output[0]) == 1)
214 214
           {
215 215
               return $phpBin;
216 216
           }          
@@ -239,7 +239,7 @@  discard block
 block discarded – undo
239 239
 	// But check read permission
240 240
 	$this->checkReadPermission();
241 241
 	
242
-	$this->view->tabs = $this->Module()->getConfigTabs()->activate('config');	
242
+	$this->view->tabs=$this->Module()->getConfigTabs()->activate('config');	
243 243
 	
244 244
 	// Get message : sent on configuration problems detected by controllers
245 245
     $this->get_param();
@@ -254,39 +254,39 @@  discard block
 block discarded – undo
254 254
     $this->check_api();
255 255
 	
256 256
 	//*********** Test snmptrapd alive and options
257
-	list ($this->view->snmptrapdError, $this->view->snmptrapdMessage) = $this->checkSnmpTrapd();
257
+	list ($this->view->snmptrapdError, $this->view->snmptrapdMessage)=$this->checkSnmpTrapd();
258 258
 
259 259
 	// List DB in $ressources
260
-	$resources = $this->get_db_list(array('mysql', 'pgsql')); 
260
+	$resources=$this->get_db_list(array('mysql', 'pgsql')); 
261 261
 
262 262
 	// Check standard Icingaweb2 path
263 263
 	$this->check_icingaweb_path();
264 264
 
265
-	$phpBinary = $this->get_php_binary();
265
+	$phpBinary=$this->get_php_binary();
266 266
 	if ($phpBinary == null)
267 267
 	{
268
-	    $phpBinary = ' PHP BINARY NOT FOUND ';
268
+	    $phpBinary=' PHP BINARY NOT FOUND ';
269 269
 	    
270 270
 	}
271 271
 	
272 272
 	// Setup path for mini documentation
273
-	$this->view->traps_in_config= $phpBinary . ' ' . $this->Module()->getBaseDir() . '/bin/trap_in.php';
273
+	$this->view->traps_in_config=$phpBinary.' '.$this->Module()->getBaseDir().'/bin/trap_in.php';
274 274
 	
275
-	$this->view->installer= $this->Module()->getBaseDir() . '/bin/installer.sh '
275
+	$this->view->installer=$this->Module()->getBaseDir().'/bin/installer.sh '
276 276
 	    . ' -c all ' 
277
-	    . ' -d ' . $this->Module()->getBaseDir()
278
-	    . ' -p ' . $phpBinary
279
-	    . ' -a ' . exec('whoami')
280
-	    . ' -w ' . Icinga::app()->getConfigDir();
277
+	    . ' -d '.$this->Module()->getBaseDir()
278
+	    . ' -p '.$phpBinary
279
+	    . ' -a '.exec('whoami')
280
+	    . ' -w '.Icinga::app()->getConfigDir();
281 281
 	        
282 282
 	// ******************* configuration form setup*******************
283
-	$this->view->form = $form = new TrapsConfigForm();
283
+	$this->view->form=$form=new TrapsConfigForm();
284 284
 	
285 285
 	// set default paths;
286
-	$this->view->form->setPaths($this->Module()->getBaseDir(),Icinga::app()->getConfigDir());
286
+	$this->view->form->setPaths($this->Module()->getBaseDir(), Icinga::app()->getConfigDir());
287 287
 	
288 288
 	// set default ido database
289
-	$this->view->form->setDefaultIDODB($this->Config()->module('monitoring','backends')->get('icinga','resource'));
289
+	$this->view->form->setDefaultIDODB($this->Config()->module('monitoring', 'backends')->get('icinga', 'resource'));
290 290
 	
291 291
 	// Make form handle request.
292 292
 	$form->setIniConfig($this->Config())
@@ -315,18 +315,18 @@  discard block
 block discarded – undo
315 315
       $this->view->configPermission=$this->checkModuleConfigPermission();
316 316
       
317 317
       // Setup tabs
318
-      $this->view->tabs = $this->Module()->getConfigTabs()->activate('satellite');	
318
+      $this->view->tabs=$this->Module()->getConfigTabs()->activate('satellite');	
319 319
       
320
-      $this->view->masterHASet = FALSE;
320
+      $this->view->masterHASet=FALSE;
321 321
       
322
-      $this->view->masterHAConf = array ('name' => 'masterHA1', 'icingaweb2 user'=>'User1');
322
+      $this->view->masterHAConf=array('name' => 'masterHA1', 'icingaweb2 user'=>'User1');
323 323
   }
324 324
   
325 325
   
326 326
   public function createschemaAction()
327 327
   {
328 328
 	$this->checkModuleConfigPermission();
329
-	$this->getTabs()->add('create_schema',array(
329
+	$this->getTabs()->add('create_schema', array(
330 330
 		'active'	=> true,
331 331
 		'label'		=> $this->translate('Create Schema'),
332 332
 		'url'		=> Url::fromRequest()
@@ -347,7 +347,7 @@  discard block
 block discarded – undo
347 347
 		// Get module database name
348 348
 		$dbName=$this->Config()->get('config', 'database');
349 349
 
350
-        $dbResource = ResourceFactory::getResourceConfig($dbName);
350
+        $dbResource=ResourceFactory::getResourceConfig($dbName);
351 351
         $dbType=$dbResource->get('db');
352 352
         switch ($dbType) {
353 353
           case 'mysql':
@@ -362,28 +362,28 @@  discard block
 block discarded – undo
362 362
         } 
363 363
 
364 364
 		printf('<pre>');
365
-		require_once $this->Module()->getBaseDir() .'/bin/trap_class.php';
365
+		require_once $this->Module()->getBaseDir().'/bin/trap_class.php';
366 366
 		
367 367
 		$icingaweb2_etc=$this->Config()->get('config', 'icingaweb2_etc');
368 368
 		$debug_level=4;
369
-		$Trap = new Trap($icingaweb2_etc);
370
-		$Trap->setLogging($debug_level,'display');
369
+		$Trap=new Trap($icingaweb2_etc);
370
+		$Trap->setLogging($debug_level, 'display');
371 371
 		
372 372
 		$prefix=$this->Config()->get('config', 'database_prefix');
373 373
 		// schema file : <path>/SQL/schema_v<verion>.<dbtype>
374
-		$schema=$this->Module()->getBaseDir() . 
375
-		'/SQL/schema_v'. $this->getModuleConfig()->getDbCurVersion() . '.' . $dbFileExt;
374
+		$schema=$this->Module()->getBaseDir(). 
375
+		'/SQL/schema_v'.$this->getModuleConfig()->getDbCurVersion().'.'.$dbFileExt;
376 376
 		
377
-		$Trap->trapsDB->create_schema($schema,$prefix);
377
+		$Trap->trapsDB->create_schema($schema, $prefix);
378 378
 		echo '</pre>';
379 379
 	}
380
-	echo '<br><br>Return to <a href="' . Url::fromPath('trapdirector/settings') .'" class="link-button icon-wrench"> settings page </a>';
380
+	echo '<br><br>Return to <a href="'.Url::fromPath('trapdirector/settings').'" class="link-button icon-wrench"> settings page </a>';
381 381
   }
382 382
 
383 383
   public function updateschemaAction()
384 384
   {
385 385
 	  $this->checkModuleConfigPermission();
386
-      $this->getTabs()->add('get',array(
386
+      $this->getTabs()->add('get', array(
387 387
     		'active'	=> true,
388 388
     		'label'		=> $this->translate('Update Schema'),
389 389
     		'url'		=> Url::fromRequest()
@@ -401,7 +401,7 @@  discard block
 block discarded – undo
401 401
           $dberror=$e->getArray(); 
402 402
       }
403 403
 	  
404
-	  echo 'Return to <a href="' . Url::fromPath('trapdirector/settings') .'" class="link-button icon-wrench"> settings page </a><br><br>';
404
+	  echo 'Return to <a href="'.Url::fromPath('trapdirector/settings').'" class="link-button icon-wrench"> settings page </a><br><br>';
405 405
 	  
406 406
 	  if ($dberror[0] != 5)
407 407
 	  {
@@ -409,40 +409,40 @@  discard block
 block discarded – undo
409 409
 	      return;
410 410
 	  }
411 411
       // setup
412
-	  require_once($this->Module()->getBaseDir() .'/bin/trap_class.php');
412
+	  require_once($this->Module()->getBaseDir().'/bin/trap_class.php');
413 413
 	  $icingaweb2_etc=$this->Config()->get('config', 'icingaweb2_etc');
414 414
 	  $debug_level=4;
415
-	  $Trap = new Trap($icingaweb2_etc);
415
+	  $Trap=new Trap($icingaweb2_etc);
416 416
 	  
417 417
 	  
418 418
 	  $prefix=$this->Config()->get('config', 'database_prefix');
419
-	  $updateSchema=$this->Module()->getBaseDir() . '/SQL/';
419
+	  $updateSchema=$this->Module()->getBaseDir().'/SQL/';
420 420
 	  
421 421
 	  $target_version=$dberror[2];
422 422
 	  
423 423
 	  if ($this->params->get('msgok') == null) {
424 424
 	      // Check for messages and display if any
425 425
               echo "Upgrade databse is going to start.<br>Don't forget to backup your database before update<br>";
426
-	      $Trap->setLogging(2,'syslog');
427
-	      $message = $Trap->trapsDB->update_schema($updateSchema,$target_version,$prefix,true);
426
+	      $Trap->setLogging(2, 'syslog');
427
+	      $message=$Trap->trapsDB->update_schema($updateSchema, $target_version, $prefix, true);
428 428
 	      if ($message != '')
429 429
 	      {
430 430
 	          echo 'Note :<br><pre>';
431 431
 	          echo $message;
432 432
 	          echo '</pre>';
433 433
 	          echo '<br>';
434
-	          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>';
434
+	          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>';
435 435
 	          echo '<br>';
436 436
 	          return;
437 437
 	      }
438 438
 	  }
439 439
 	  
440
-	  $Trap->setLogging($debug_level,'display');
440
+	  $Trap->setLogging($debug_level, 'display');
441 441
 	  
442
-	  echo 'Updating schema to '. $target_version . ': <br>';
442
+	  echo 'Updating schema to '.$target_version.': <br>';
443 443
 	  echo '<pre>';
444 444
 	  	  
445
-	  $Trap->trapsDB->update_schema($updateSchema,$target_version,$prefix);
445
+	  $Trap->trapsDB->update_schema($updateSchema, $target_version, $prefix);
446 446
 	  echo '</pre>';
447 447
   }  
448 448
 
@@ -451,48 +451,48 @@  discard block
 block discarded – undo
451 451
   {
452 452
       $psOutput=array();
453 453
       // First check is someone is listening to port 162. As not root, we can't have pid... 
454
-      $sspath = exec('which ss 2>/dev/null');
455
-      if(empty($sspath))
454
+      $sspath=exec('which ss 2>/dev/null');
455
+      if (empty($sspath))
456 456
       {
457 457
           // RHEL based systems
458
-          $sspath = '/usr/sbin/ss';
458
+          $sspath='/usr/sbin/ss';
459 459
       }
460
-      if(!is_executable("$sspath"))
460
+      if (!is_executable("$sspath"))
461 461
       {
462
-          return array(1,"Can not execute $sspath");
462
+          return array(1, "Can not execute $sspath");
463 463
       }
464
-      exec("$sspath -lun | grep ':162 '",$psOutput);
464
+      exec("$sspath -lun | grep ':162 '", $psOutput);
465 465
       if (count($psOutput) == 0)
466 466
       {
467
-          return array(1,'Port UDP/162 is not open : is snmptrapd running?');
467
+          return array(1, 'Port UDP/162 is not open : is snmptrapd running?');
468 468
       }
469 469
       $psOutput=array();
470
-      $selinux_state = '';
471
-      if(is_executable('/usr/sbin/getenforce'))
470
+      $selinux_state='';
471
+      if (is_executable('/usr/sbin/getenforce'))
472 472
       {
473
-          $selinux_state = exec('/usr/sbin/getenforce 2>/dev/null');
473
+          $selinux_state=exec('/usr/sbin/getenforce 2>/dev/null');
474 474
       }
475
-      if($selinux_state !== 'Enforcing')
475
+      if ($selinux_state !== 'Enforcing')
476 476
       {
477
-          exec('ps --no-headers -o command -C snmptrapd',$psOutput);
477
+          exec('ps --no-headers -o command -C snmptrapd', $psOutput);
478 478
           if (count($psOutput) == 0)
479 479
           {
480
-              return array(1,"UDP/162 : OK, but no snmptrapd process (?)");
480
+              return array(1, "UDP/162 : OK, but no snmptrapd process (?)");
481 481
           }
482 482
           // Assume there is only one line... TODO : see if there is a better way to do this
483
-          $line = preg_replace('/^.*snmptrapd /','',$psOutput[0]);
484
-          if (!preg_match('/-n/',$line))
485
-              return array(1,'snmptrapd has no -n option : '.$line);
486
-          if (!preg_match('/-O[^ ]*n/',$line))
487
-              return array(1,'snmptrapd has no -On option : '.$line);
488
-          if (!preg_match('/-O[^ ]*e/',$line))
489
-              return array(1,'snmptrapd has no -Oe option : '.$line);
483
+          $line=preg_replace('/^.*snmptrapd /', '', $psOutput[0]);
484
+          if (!preg_match('/-n/', $line))
485
+              return array(1, 'snmptrapd has no -n option : '.$line);
486
+          if (!preg_match('/-O[^ ]*n/', $line))
487
+              return array(1, 'snmptrapd has no -On option : '.$line);
488
+          if (!preg_match('/-O[^ ]*e/', $line))
489
+              return array(1, 'snmptrapd has no -Oe option : '.$line);
490 490
 
491
-          return array(0,'snmptrapd listening to UDP/162, options : '.$line);
491
+          return array(0, 'snmptrapd listening to UDP/162, options : '.$line);
492 492
       }
493 493
       else
494 494
       {
495
-          return array(0,'A daemon (hidden by SELinux) is listening on UDP/162');
495
+          return array(0, 'A daemon (hidden by SELinux) is listening on UDP/162');
496 496
       }
497 497
   }
498 498
 }
Please login to merge, or discard this patch.
application/controllers/ApiController.php 3 patches
Indentation   +29 added lines, -29 removed lines patch added patch discarded remove patch
@@ -11,28 +11,28 @@  discard block
 block discarded – undo
11 11
 class ApiController extends TrapsController
12 12
 {
13 13
 	
14
-    private $json_options=JSON_PRETTY_PRINT;
14
+	private $json_options=JSON_PRETTY_PRINT;
15 15
     
16
-    protected function send_json($object)
17
-    {
18
-        if (isset($object['Error']))
19
-        {
20
-            $this->send_json_error($object);
21
-            return;
22
-        }
23
-        $this->_helper->layout()->disableLayout();
24
-        $this->getResponse()->setHeader('Content-Type', 'application/json', true);
25
-        $this->getResponse()->sendHeaders();
26
-        echo json_encode($object, $this->json_options) . "\n";
27
-    }
16
+	protected function send_json($object)
17
+	{
18
+		if (isset($object['Error']))
19
+		{
20
+			$this->send_json_error($object);
21
+			return;
22
+		}
23
+		$this->_helper->layout()->disableLayout();
24
+		$this->getResponse()->setHeader('Content-Type', 'application/json', true);
25
+		$this->getResponse()->sendHeaders();
26
+		echo json_encode($object, $this->json_options) . "\n";
27
+	}
28 28
 
29
-    protected function send_json_error($object)
30
-    {
31
-        $this->_helper->layout()->disableLayout();
32
-        $this->getResponse()->setHeader('Content-Type', 'application/json', true);
33
-        $this->getResponse()->sendHeaders();
34
-        echo json_encode($object, $this->json_options) . "\n";
35
-    }
29
+	protected function send_json_error($object)
30
+	{
31
+		$this->_helper->layout()->disableLayout();
32
+		$this->getResponse()->setHeader('Content-Type', 'application/json', true);
33
+		$this->getResponse()->sendHeaders();
34
+		echo json_encode($object, $this->json_options) . "\n";
35
+	}
36 36
     
37 37
 	public function indexAction()
38 38
 	{	
@@ -47,18 +47,18 @@  discard block
 block discarded – undo
47 47
 	
48 48
 	public function dboptionActions()
49 49
 	{
50
-	    $this->checkReadPermission();
51
-	    $apiObj= new RestAPI($this);
50
+		$this->checkReadPermission();
51
+		$apiObj= new RestAPI($this);
52 52
 	    
53
-	    $params = $this->getRequest()->getParams();
54
-	    if (isset($params['name']))
55
-	    {
53
+		$params = $this->getRequest()->getParams();
54
+		if (isset($params['name']))
55
+		{
56 56
 	        
57
-	    }
58
-	    else 
59
-	    {
57
+		}
58
+		else 
59
+		{
60 60
 	        
61
-	    }
61
+		}
62 62
 	}
63 63
 	
64 64
 }
65 65
\ No newline at end of file
Please login to merge, or discard this patch.
Spacing   +6 added lines, -6 removed lines patch added patch discarded remove patch
@@ -23,7 +23,7 @@  discard block
 block discarded – undo
23 23
         $this->_helper->layout()->disableLayout();
24 24
         $this->getResponse()->setHeader('Content-Type', 'application/json', true);
25 25
         $this->getResponse()->sendHeaders();
26
-        echo json_encode($object, $this->json_options) . "\n";
26
+        echo json_encode($object, $this->json_options)."\n";
27 27
     }
28 28
 
29 29
     protected function send_json_error($object)
@@ -31,15 +31,15 @@  discard block
 block discarded – undo
31 31
         $this->_helper->layout()->disableLayout();
32 32
         $this->getResponse()->setHeader('Content-Type', 'application/json', true);
33 33
         $this->getResponse()->sendHeaders();
34
-        echo json_encode($object, $this->json_options) . "\n";
34
+        echo json_encode($object, $this->json_options)."\n";
35 35
     }
36 36
     
37 37
 	public function indexAction()
38 38
 	{	
39 39
 		$this->checkReadPermission();
40
-		$apiObj= new RestAPI($this);
40
+		$apiObj=new RestAPI($this);
41 41
 
42
-		$modif = $apiObj->last_modified();
42
+		$modif=$apiObj->last_modified();
43 43
 		$this->send_json($modif);
44 44
 		//print_r($modif);
45 45
 		return;
@@ -48,9 +48,9 @@  discard block
 block discarded – undo
48 48
 	public function dboptionActions()
49 49
 	{
50 50
 	    $this->checkReadPermission();
51
-	    $apiObj= new RestAPI($this);
51
+	    $apiObj=new RestAPI($this);
52 52
 	    
53
-	    $params = $this->getRequest()->getParams();
53
+	    $params=$this->getRequest()->getParams();
54 54
 	    if (isset($params['name']))
55 55
 	    {
56 56
 	        
Please login to merge, or discard this patch.
Braces   +1 added lines, -2 removed lines patch added patch discarded remove patch
@@ -54,8 +54,7 @@
 block discarded – undo
54 54
 	    if (isset($params['name']))
55 55
 	    {
56 56
 	        
57
-	    }
58
-	    else 
57
+	    } else 
59 58
 	    {
60 59
 	        
61 60
 	    }
Please login to merge, or discard this patch.
library/Trapdirector/TrapsActions/TrapDBQuery.php 3 patches
Indentation   +191 added lines, -191 removed lines patch added patch discarded remove patch
@@ -20,225 +20,225 @@
 block discarded – undo
20 20
 trait TrapDBQuery
21 21
 {
22 22
     
23
-    /** @return TrapsController */
24
-    abstract protected function getTrapCtrl();
23
+	/** @return TrapsController */
24
+	abstract protected function getTrapCtrl();
25 25
 
26
-    /** @return Zend_Db_Adapter_Abstract : returns DB connexion or null on error */
27
-    abstract public function getDbConn();
26
+	/** @return Zend_Db_Adapter_Abstract : returns DB connexion or null on error */
27
+	abstract public function getDbConn();
28 28
     
29
-    /** Add handler rule in traps DB
30
-     *	@param array $params : array(<db item>=><value>)
31
-     *	@return int inserted id
32
-     */
33
-    public function addHandlerRule($params)
34
-    {
35
-        // TODO Check for rule consistency
29
+	/** Add handler rule in traps DB
30
+	 *	@param array $params : array(<db item>=><value>)
31
+	 *	@return int inserted id
32
+	 */
33
+	public function addHandlerRule($params)
34
+	{
35
+		// TODO Check for rule consistency
36 36
         
37
-        $dbConn = $this->getDbConn();
38
-        if ($dbConn === null) throw new \ErrorException('uncatched db error');
39
-        // Add last modified date = creation date and username
40
-        $params['created'] = new Zend_Db_Expr('NOW()');
41
-        $params['modified'] = new 	Zend_Db_Expr('NOW()');
42
-        $params['modifier'] = $this->getTrapCtrl()->Auth()->getUser()->getUsername();
37
+		$dbConn = $this->getDbConn();
38
+		if ($dbConn === null) throw new \ErrorException('uncatched db error');
39
+		// Add last modified date = creation date and username
40
+		$params['created'] = new Zend_Db_Expr('NOW()');
41
+		$params['modified'] = new 	Zend_Db_Expr('NOW()');
42
+		$params['modifier'] = $this->getTrapCtrl()->Auth()->getUser()->getUsername();
43 43
         
44
-        $query=$dbConn->insert(
45
-            $this->getTrapCtrl()->getModuleConfig()->getTrapRuleName(),
46
-            $params
47
-            );
48
-        if($query==false)
49
-        {
50
-            return null;
51
-        }
52
-        return $dbConn->lastInsertId();
53
-    }
44
+		$query=$dbConn->insert(
45
+			$this->getTrapCtrl()->getModuleConfig()->getTrapRuleName(),
46
+			$params
47
+			);
48
+		if($query==false)
49
+		{
50
+			return null;
51
+		}
52
+		return $dbConn->lastInsertId();
53
+	}
54 54
     
55
-    /** Update handler rule in traps DB
56
-     *	@param array $params : (<db item>=><value>)
57
-     *   @param integer $ruleID : rule id in db
58
-     *	@return array affected rows
59
-     */
60
-    public function updateHandlerRule($params,$ruleID)
61
-    {
62
-        // TODO Check for rule consistency
63
-        $dbConn = $this->getDbConn();
64
-        if ($dbConn === null) throw new \ErrorException('uncatched db error');
65
-        // Add last modified date = creation date and username
66
-        $params['modified'] = new 	Zend_Db_Expr('NOW()');
67
-        $params['modifier'] = $this->getTrapCtrl()->Auth()->getUser()->getUsername();
55
+	/** Update handler rule in traps DB
56
+	 *	@param array $params : (<db item>=><value>)
57
+	 *   @param integer $ruleID : rule id in db
58
+	 *	@return array affected rows
59
+	 */
60
+	public function updateHandlerRule($params,$ruleID)
61
+	{
62
+		// TODO Check for rule consistency
63
+		$dbConn = $this->getDbConn();
64
+		if ($dbConn === null) throw new \ErrorException('uncatched db error');
65
+		// Add last modified date = creation date and username
66
+		$params['modified'] = new 	Zend_Db_Expr('NOW()');
67
+		$params['modifier'] = $this->getTrapCtrl()->Auth()->getUser()->getUsername();
68 68
         
69
-        $numRows=$dbConn->update(
70
-            $this->getTrapCtrl()->getModuleConfig()->getTrapRuleName(),
71
-            $params,
72
-            'id='.$ruleID
73
-            );
74
-        return $numRows;
75
-    }
69
+		$numRows=$dbConn->update(
70
+			$this->getTrapCtrl()->getModuleConfig()->getTrapRuleName(),
71
+			$params,
72
+			'id='.$ruleID
73
+			);
74
+		return $numRows;
75
+	}
76 76
     
77
-    /** Delete rule by id
78
-     *	@param int $ruleID rule id
79
-     */
80
-    public function deleteRule($ruleID)
81
-    {
82
-        if (!preg_match('/^[0-9]+$/',$ruleID)) { throw new Exception('Invalid id');  }
77
+	/** Delete rule by id
78
+	 *	@param int $ruleID rule id
79
+	 */
80
+	public function deleteRule($ruleID)
81
+	{
82
+		if (!preg_match('/^[0-9]+$/',$ruleID)) { throw new Exception('Invalid id');  }
83 83
         
84
-        $dbConn = $this->getDbConn();
85
-        if ($dbConn === null) throw new \ErrorException('uncatched db error');
84
+		$dbConn = $this->getDbConn();
85
+		if ($dbConn === null) throw new \ErrorException('uncatched db error');
86 86
         
87
-        $query=$dbConn->delete(
88
-            $this->getTrapCtrl()->getModuleConfig()->getTrapRuleName(),
89
-            'id='.$ruleID
90
-            );
91
-        return $query;
92
-    }
87
+		$query=$dbConn->delete(
88
+			$this->getTrapCtrl()->getModuleConfig()->getTrapRuleName(),
89
+			'id='.$ruleID
90
+			);
91
+		return $query;
92
+	}
93 93
 
94
-    /**
95
-     * Get last trap rule table modification
96
-     * @throws \ErrorException
97
-     * @return Zend_Db_Select
98
-     */
99
-    public function lastModification()
100
-    {
101
-        $dbConn = $this->getDbConn();
102
-        if ($dbConn === null) throw new \ErrorException('uncatched db error');
94
+	/**
95
+	 * Get last trap rule table modification
96
+	 * @throws \ErrorException
97
+	 * @return Zend_Db_Select
98
+	 */
99
+	public function lastModification()
100
+	{
101
+		$dbConn = $this->getDbConn();
102
+		if ($dbConn === null) throw new \ErrorException('uncatched db error');
103 103
         
104
-        $query = $dbConn->select()
105
-        ->from(
106
-            $this->getTrapCtrl()->getModuleConfig()->getTrapRuleName(),
107
-            array('lastModified'=>'UNIX_TIMESTAMP(MAX(modified))'));
108
-        $returnRow=$dbConn->fetchRow($query);
109
-        return $returnRow->lastmodified;
110
-    }
104
+		$query = $dbConn->select()
105
+		->from(
106
+			$this->getTrapCtrl()->getModuleConfig()->getTrapRuleName(),
107
+			array('lastModified'=>'UNIX_TIMESTAMP(MAX(modified))'));
108
+		$returnRow=$dbConn->fetchRow($query);
109
+		return $returnRow->lastmodified;
110
+	}
111 111
     
112
-    /** Delete trap by ip & oid
113
-     *	@param $ipAddr string source IP (v4 or v6)
114
-     *	@param $oid string oid
115
-     */
116
-    public function deleteTrap($ipAddr,$oid)
117
-    {
112
+	/** Delete trap by ip & oid
113
+	 *	@param $ipAddr string source IP (v4 or v6)
114
+	 *	@param $oid string oid
115
+	 */
116
+	public function deleteTrap($ipAddr,$oid)
117
+	{
118 118
         
119
-        $dbConn = $this->getDbConn();
120
-        if ($dbConn === null) throw new \ErrorException('uncatched db error');
121
-        $condition=null;
122
-        if ($ipAddr != null)
123
-        {
124
-            $condition="source_ip='$ipAddr'";
125
-        }
126
-        if ($oid != null)
127
-        {
128
-            $condition=($condition===null)?'':$condition.' AND ';
129
-            $condition.="trap_oid='$oid'";
130
-        }
131
-        if($condition === null) return null;
132
-        $query=$dbConn->delete(
133
-            $this->getTrapCtrl()->getModuleConfig()->getTrapTableName(),
134
-            $condition
135
-            );
136
-        // TODO test ret code etc...
137
-        return $query;
138
-    }
119
+		$dbConn = $this->getDbConn();
120
+		if ($dbConn === null) throw new \ErrorException('uncatched db error');
121
+		$condition=null;
122
+		if ($ipAddr != null)
123
+		{
124
+			$condition="source_ip='$ipAddr'";
125
+		}
126
+		if ($oid != null)
127
+		{
128
+			$condition=($condition===null)?'':$condition.' AND ';
129
+			$condition.="trap_oid='$oid'";
130
+		}
131
+		if($condition === null) return null;
132
+		$query=$dbConn->delete(
133
+			$this->getTrapCtrl()->getModuleConfig()->getTrapTableName(),
134
+			$condition
135
+			);
136
+		// TODO test ret code etc...
137
+		return $query;
138
+	}
139 139
     
140 140
     
141
-    /** count trap by ip & oid
142
-     *	@param $ipAddr string source IP (v4 or v6)
143
-     *	@param $oid string oid
144
-     */
145
-    public function countTrap($ipAddr,$oid)
146
-    {
141
+	/** count trap by ip & oid
142
+	 *	@param $ipAddr string source IP (v4 or v6)
143
+	 *	@param $oid string oid
144
+	 */
145
+	public function countTrap($ipAddr,$oid)
146
+	{
147 147
         
148
-        $dbConn = $this->getDbConn();
149
-        if ($dbConn === null) throw new \ErrorException('uncatched db error');
148
+		$dbConn = $this->getDbConn();
149
+		if ($dbConn === null) throw new \ErrorException('uncatched db error');
150 150
         
151
-        $condition=null;
152
-        if ($ipAddr != null)
153
-        {
154
-            $condition="source_ip='$ipAddr'";
155
-        }
156
-        if ($oid != null)
157
-        {
158
-            $condition=($condition===null)?'':$condition.' AND ';
159
-            $condition.="trap_oid='$oid'";
160
-        }
161
-        if($condition === null) return 0;
162
-        $query=$dbConn->select()
163
-            ->from(
164
-                $this->getTrapCtrl()->getModuleConfig()->getTrapTableName(),
165
-                array('num'=>'count(*)'))
166
-            ->where($condition);
167
-        $returnRow=$dbConn->fetchRow($query);
168
-        return $returnRow->num;
169
-    }
151
+		$condition=null;
152
+		if ($ipAddr != null)
153
+		{
154
+			$condition="source_ip='$ipAddr'";
155
+		}
156
+		if ($oid != null)
157
+		{
158
+			$condition=($condition===null)?'':$condition.' AND ';
159
+			$condition.="trap_oid='$oid'";
160
+		}
161
+		if($condition === null) return 0;
162
+		$query=$dbConn->select()
163
+			->from(
164
+				$this->getTrapCtrl()->getModuleConfig()->getTrapTableName(),
165
+				array('num'=>'count(*)'))
166
+			->where($condition);
167
+		$returnRow=$dbConn->fetchRow($query);
168
+		return $returnRow->num;
169
+	}
170 170
     
171
-    /** get configuration value
172
-     *	@param string $element : configuration name in db
173
-     */
174
-    public function getDBConfigValue($element)
175
-    {
171
+	/** get configuration value
172
+	 *	@param string $element : configuration name in db
173
+	 */
174
+	public function getDBConfigValue($element)
175
+	{
176 176
         
177
-        $dbConn = $this->getDbConn();
178
-        if ($dbConn === null) throw new \ErrorException('uncatched db error');
177
+		$dbConn = $this->getDbConn();
178
+		if ($dbConn === null) throw new \ErrorException('uncatched db error');
179 179
         
180
-        $query=$dbConn->select()
181
-        ->from(
182
-            $this->getTrapCtrl()->getModuleConfig()->getDbConfigTableName(),
183
-            array('value'=>'value'))
184
-            ->where('name=?',$element);
185
-            $returnRow=$dbConn->fetchRow($query);
186
-            if ($returnRow==null)  // value does not exists
187
-            {
188
-                $default=$this->getTrapCtrl()->getModuleConfig()->getDBConfigDefaults();
189
-                if ( ! isset($default[$element])) return null; // no default and not value
180
+		$query=$dbConn->select()
181
+		->from(
182
+			$this->getTrapCtrl()->getModuleConfig()->getDbConfigTableName(),
183
+			array('value'=>'value'))
184
+			->where('name=?',$element);
185
+			$returnRow=$dbConn->fetchRow($query);
186
+			if ($returnRow==null)  // value does not exists
187
+			{
188
+				$default=$this->getTrapCtrl()->getModuleConfig()->getDBConfigDefaults();
189
+				if ( ! isset($default[$element])) return null; // no default and not value
190 190
                 
191
-                $this->addDBConfigValue($element,$default[$element]);
192
-                return $default[$element];
193
-            }
194
-            if ($returnRow->value == null) // value id empty
195
-            {
196
-                $default=$this->getTrapCtrl()->getModuleConfig()->getDBConfigDefaults();
197
-                if ( ! isset($default[$element])) return null; // no default and not value
198
-                $this->setDBConfigValue($element,$default[$element]);
199
-                return $default[$element];
200
-            }
201
-            return $returnRow->value;
202
-    }
191
+				$this->addDBConfigValue($element,$default[$element]);
192
+				return $default[$element];
193
+			}
194
+			if ($returnRow->value == null) // value id empty
195
+			{
196
+				$default=$this->getTrapCtrl()->getModuleConfig()->getDBConfigDefaults();
197
+				if ( ! isset($default[$element])) return null; // no default and not value
198
+				$this->setDBConfigValue($element,$default[$element]);
199
+				return $default[$element];
200
+			}
201
+			return $returnRow->value;
202
+	}
203 203
     
204
-    /** add configuration value
205
-     *	@param string $element : name of config element
206
-     *   @param string $value : value
207
-     */
204
+	/** add configuration value
205
+	 *	@param string $element : name of config element
206
+	 *   @param string $value : value
207
+	 */
208 208
     
209
-    public function addDBConfigValue($element,$value)
210
-    {
209
+	public function addDBConfigValue($element,$value)
210
+	{
211 211
         
212
-        $dbConn = $this->getDbConn();
213
-        if ($dbConn === null) throw new \ErrorException('uncatched db error');
212
+		$dbConn = $this->getDbConn();
213
+		if ($dbConn === null) throw new \ErrorException('uncatched db error');
214 214
         
215
-        $query=$dbConn->insert(
216
-            $this->getTrapCtrl()->getModuleConfig()->getDbConfigTableName(),
217
-            array(
218
-                'name' => $element,
219
-                'value'=>$value
220
-            )
221
-            );
222
-        return $query;
223
-    }
215
+		$query=$dbConn->insert(
216
+			$this->getTrapCtrl()->getModuleConfig()->getDbConfigTableName(),
217
+			array(
218
+				'name' => $element,
219
+				'value'=>$value
220
+			)
221
+			);
222
+		return $query;
223
+	}
224 224
     
225
-    /** set configuration value
226
-     *	@param string $element : name of config element
227
-     *   @param string $value : value
228
-     */
229
-    public function setDBConfigValue($element,$value)
230
-    {
225
+	/** set configuration value
226
+	 *	@param string $element : name of config element
227
+	 *   @param string $value : value
228
+	 */
229
+	public function setDBConfigValue($element,$value)
230
+	{
231 231
         
232
-        $dbConn = $this->getDbConn();
233
-        if ($dbConn === null) throw new \ErrorException('uncatched db error');
232
+		$dbConn = $this->getDbConn();
233
+		if ($dbConn === null) throw new \ErrorException('uncatched db error');
234 234
         
235
-        $query=$dbConn->update(
236
-            $this->getTrapCtrl()->getModuleConfig()->getDbConfigTableName(),
237
-            array('value'=>$value),
238
-            'name=\''.$element.'\''
239
-            );
240
-        return $query;
241
-    }
235
+		$query=$dbConn->update(
236
+			$this->getTrapCtrl()->getModuleConfig()->getDbConfigTableName(),
237
+			array('value'=>$value),
238
+			'name=\''.$element.'\''
239
+			);
240
+		return $query;
241
+	}
242 242
     
243 243
     
244 244
 }
245 245
\ No newline at end of file
Please login to merge, or discard this patch.
Spacing   +32 added lines, -32 removed lines patch added patch discarded remove patch
@@ -34,18 +34,18 @@  discard block
 block discarded – undo
34 34
     {
35 35
         // TODO Check for rule consistency
36 36
         
37
-        $dbConn = $this->getDbConn();
37
+        $dbConn=$this->getDbConn();
38 38
         if ($dbConn === null) throw new \ErrorException('uncatched db error');
39 39
         // Add last modified date = creation date and username
40
-        $params['created'] = new Zend_Db_Expr('NOW()');
41
-        $params['modified'] = new 	Zend_Db_Expr('NOW()');
42
-        $params['modifier'] = $this->getTrapCtrl()->Auth()->getUser()->getUsername();
40
+        $params['created']=new Zend_Db_Expr('NOW()');
41
+        $params['modified']=new 	Zend_Db_Expr('NOW()');
42
+        $params['modifier']=$this->getTrapCtrl()->Auth()->getUser()->getUsername();
43 43
         
44 44
         $query=$dbConn->insert(
45 45
             $this->getTrapCtrl()->getModuleConfig()->getTrapRuleName(),
46 46
             $params
47 47
             );
48
-        if($query==false)
48
+        if ($query == false)
49 49
         {
50 50
             return null;
51 51
         }
@@ -57,14 +57,14 @@  discard block
 block discarded – undo
57 57
      *   @param integer $ruleID : rule id in db
58 58
      *	@return array affected rows
59 59
      */
60
-    public function updateHandlerRule($params,$ruleID)
60
+    public function updateHandlerRule($params, $ruleID)
61 61
     {
62 62
         // TODO Check for rule consistency
63
-        $dbConn = $this->getDbConn();
63
+        $dbConn=$this->getDbConn();
64 64
         if ($dbConn === null) throw new \ErrorException('uncatched db error');
65 65
         // Add last modified date = creation date and username
66
-        $params['modified'] = new 	Zend_Db_Expr('NOW()');
67
-        $params['modifier'] = $this->getTrapCtrl()->Auth()->getUser()->getUsername();
66
+        $params['modified']=new 	Zend_Db_Expr('NOW()');
67
+        $params['modifier']=$this->getTrapCtrl()->Auth()->getUser()->getUsername();
68 68
         
69 69
         $numRows=$dbConn->update(
70 70
             $this->getTrapCtrl()->getModuleConfig()->getTrapRuleName(),
@@ -79,9 +79,9 @@  discard block
 block discarded – undo
79 79
      */
80 80
     public function deleteRule($ruleID)
81 81
     {
82
-        if (!preg_match('/^[0-9]+$/',$ruleID)) { throw new Exception('Invalid id');  }
82
+        if (!preg_match('/^[0-9]+$/', $ruleID)) { throw new Exception('Invalid id'); }
83 83
         
84
-        $dbConn = $this->getDbConn();
84
+        $dbConn=$this->getDbConn();
85 85
         if ($dbConn === null) throw new \ErrorException('uncatched db error');
86 86
         
87 87
         $query=$dbConn->delete(
@@ -98,10 +98,10 @@  discard block
 block discarded – undo
98 98
      */
99 99
     public function lastModification()
100 100
     {
101
-        $dbConn = $this->getDbConn();
101
+        $dbConn=$this->getDbConn();
102 102
         if ($dbConn === null) throw new \ErrorException('uncatched db error');
103 103
         
104
-        $query = $dbConn->select()
104
+        $query=$dbConn->select()
105 105
         ->from(
106 106
             $this->getTrapCtrl()->getModuleConfig()->getTrapRuleName(),
107 107
             array('lastModified'=>'UNIX_TIMESTAMP(MAX(modified))'));
@@ -113,10 +113,10 @@  discard block
 block discarded – undo
113 113
      *	@param $ipAddr string source IP (v4 or v6)
114 114
      *	@param $oid string oid
115 115
      */
116
-    public function deleteTrap($ipAddr,$oid)
116
+    public function deleteTrap($ipAddr, $oid)
117 117
     {
118 118
         
119
-        $dbConn = $this->getDbConn();
119
+        $dbConn=$this->getDbConn();
120 120
         if ($dbConn === null) throw new \ErrorException('uncatched db error');
121 121
         $condition=null;
122 122
         if ($ipAddr != null)
@@ -125,10 +125,10 @@  discard block
 block discarded – undo
125 125
         }
126 126
         if ($oid != null)
127 127
         {
128
-            $condition=($condition===null)?'':$condition.' AND ';
128
+            $condition=($condition === null) ? '' : $condition.' AND ';
129 129
             $condition.="trap_oid='$oid'";
130 130
         }
131
-        if($condition === null) return null;
131
+        if ($condition === null) return null;
132 132
         $query=$dbConn->delete(
133 133
             $this->getTrapCtrl()->getModuleConfig()->getTrapTableName(),
134 134
             $condition
@@ -142,10 +142,10 @@  discard block
 block discarded – undo
142 142
      *	@param $ipAddr string source IP (v4 or v6)
143 143
      *	@param $oid string oid
144 144
      */
145
-    public function countTrap($ipAddr,$oid)
145
+    public function countTrap($ipAddr, $oid)
146 146
     {
147 147
         
148
-        $dbConn = $this->getDbConn();
148
+        $dbConn=$this->getDbConn();
149 149
         if ($dbConn === null) throw new \ErrorException('uncatched db error');
150 150
         
151 151
         $condition=null;
@@ -155,10 +155,10 @@  discard block
 block discarded – undo
155 155
         }
156 156
         if ($oid != null)
157 157
         {
158
-            $condition=($condition===null)?'':$condition.' AND ';
158
+            $condition=($condition === null) ? '' : $condition.' AND ';
159 159
             $condition.="trap_oid='$oid'";
160 160
         }
161
-        if($condition === null) return 0;
161
+        if ($condition === null) return 0;
162 162
         $query=$dbConn->select()
163 163
             ->from(
164 164
                 $this->getTrapCtrl()->getModuleConfig()->getTrapTableName(),
@@ -174,28 +174,28 @@  discard block
 block discarded – undo
174 174
     public function getDBConfigValue($element)
175 175
     {
176 176
         
177
-        $dbConn = $this->getDbConn();
177
+        $dbConn=$this->getDbConn();
178 178
         if ($dbConn === null) throw new \ErrorException('uncatched db error');
179 179
         
180 180
         $query=$dbConn->select()
181 181
         ->from(
182 182
             $this->getTrapCtrl()->getModuleConfig()->getDbConfigTableName(),
183 183
             array('value'=>'value'))
184
-            ->where('name=?',$element);
184
+            ->where('name=?', $element);
185 185
             $returnRow=$dbConn->fetchRow($query);
186
-            if ($returnRow==null)  // value does not exists
186
+            if ($returnRow == null)  // value does not exists
187 187
             {
188 188
                 $default=$this->getTrapCtrl()->getModuleConfig()->getDBConfigDefaults();
189
-                if ( ! isset($default[$element])) return null; // no default and not value
189
+                if (!isset($default[$element])) return null; // no default and not value
190 190
                 
191
-                $this->addDBConfigValue($element,$default[$element]);
191
+                $this->addDBConfigValue($element, $default[$element]);
192 192
                 return $default[$element];
193 193
             }
194 194
             if ($returnRow->value == null) // value id empty
195 195
             {
196 196
                 $default=$this->getTrapCtrl()->getModuleConfig()->getDBConfigDefaults();
197
-                if ( ! isset($default[$element])) return null; // no default and not value
198
-                $this->setDBConfigValue($element,$default[$element]);
197
+                if (!isset($default[$element])) return null; // no default and not value
198
+                $this->setDBConfigValue($element, $default[$element]);
199 199
                 return $default[$element];
200 200
             }
201 201
             return $returnRow->value;
@@ -206,10 +206,10 @@  discard block
 block discarded – undo
206 206
      *   @param string $value : value
207 207
      */
208 208
     
209
-    public function addDBConfigValue($element,$value)
209
+    public function addDBConfigValue($element, $value)
210 210
     {
211 211
         
212
-        $dbConn = $this->getDbConn();
212
+        $dbConn=$this->getDbConn();
213 213
         if ($dbConn === null) throw new \ErrorException('uncatched db error');
214 214
         
215 215
         $query=$dbConn->insert(
@@ -226,10 +226,10 @@  discard block
 block discarded – undo
226 226
      *	@param string $element : name of config element
227 227
      *   @param string $value : value
228 228
      */
229
-    public function setDBConfigValue($element,$value)
229
+    public function setDBConfigValue($element, $value)
230 230
     {
231 231
         
232
-        $dbConn = $this->getDbConn();
232
+        $dbConn=$this->getDbConn();
233 233
         if ($dbConn === null) throw new \ErrorException('uncatched db error');
234 234
         
235 235
         $query=$dbConn->update(
Please login to merge, or discard this patch.
Braces   +47 added lines, -15 removed lines patch added patch discarded remove patch
@@ -35,7 +35,9 @@  discard block
 block discarded – undo
35 35
         // TODO Check for rule consistency
36 36
         
37 37
         $dbConn = $this->getDbConn();
38
-        if ($dbConn === null) throw new \ErrorException('uncatched db error');
38
+        if ($dbConn === null) {
39
+        	throw new \ErrorException('uncatched db error');
40
+        }
39 41
         // Add last modified date = creation date and username
40 42
         $params['created'] = new Zend_Db_Expr('NOW()');
41 43
         $params['modified'] = new 	Zend_Db_Expr('NOW()');
@@ -61,7 +63,9 @@  discard block
 block discarded – undo
61 63
     {
62 64
         // TODO Check for rule consistency
63 65
         $dbConn = $this->getDbConn();
64
-        if ($dbConn === null) throw new \ErrorException('uncatched db error');
66
+        if ($dbConn === null) {
67
+        	throw new \ErrorException('uncatched db error');
68
+        }
65 69
         // Add last modified date = creation date and username
66 70
         $params['modified'] = new 	Zend_Db_Expr('NOW()');
67 71
         $params['modifier'] = $this->getTrapCtrl()->Auth()->getUser()->getUsername();
@@ -82,7 +86,9 @@  discard block
 block discarded – undo
82 86
         if (!preg_match('/^[0-9]+$/',$ruleID)) { throw new Exception('Invalid id');  }
83 87
         
84 88
         $dbConn = $this->getDbConn();
85
-        if ($dbConn === null) throw new \ErrorException('uncatched db error');
89
+        if ($dbConn === null) {
90
+        	throw new \ErrorException('uncatched db error');
91
+        }
86 92
         
87 93
         $query=$dbConn->delete(
88 94
             $this->getTrapCtrl()->getModuleConfig()->getTrapRuleName(),
@@ -99,7 +105,9 @@  discard block
 block discarded – undo
99 105
     public function lastModification()
100 106
     {
101 107
         $dbConn = $this->getDbConn();
102
-        if ($dbConn === null) throw new \ErrorException('uncatched db error');
108
+        if ($dbConn === null) {
109
+        	throw new \ErrorException('uncatched db error');
110
+        }
103 111
         
104 112
         $query = $dbConn->select()
105 113
         ->from(
@@ -117,7 +125,9 @@  discard block
 block discarded – undo
117 125
     {
118 126
         
119 127
         $dbConn = $this->getDbConn();
120
-        if ($dbConn === null) throw new \ErrorException('uncatched db error');
128
+        if ($dbConn === null) {
129
+        	throw new \ErrorException('uncatched db error');
130
+        }
121 131
         $condition=null;
122 132
         if ($ipAddr != null)
123 133
         {
@@ -128,7 +138,9 @@  discard block
 block discarded – undo
128 138
             $condition=($condition===null)?'':$condition.' AND ';
129 139
             $condition.="trap_oid='$oid'";
130 140
         }
131
-        if($condition === null) return null;
141
+        if($condition === null) {
142
+        	return null;
143
+        }
132 144
         $query=$dbConn->delete(
133 145
             $this->getTrapCtrl()->getModuleConfig()->getTrapTableName(),
134 146
             $condition
@@ -146,7 +158,9 @@  discard block
 block discarded – undo
146 158
     {
147 159
         
148 160
         $dbConn = $this->getDbConn();
149
-        if ($dbConn === null) throw new \ErrorException('uncatched db error');
161
+        if ($dbConn === null) {
162
+        	throw new \ErrorException('uncatched db error');
163
+        }
150 164
         
151 165
         $condition=null;
152 166
         if ($ipAddr != null)
@@ -158,7 +172,9 @@  discard block
 block discarded – undo
158 172
             $condition=($condition===null)?'':$condition.' AND ';
159 173
             $condition.="trap_oid='$oid'";
160 174
         }
161
-        if($condition === null) return 0;
175
+        if($condition === null) {
176
+        	return 0;
177
+        }
162 178
         $query=$dbConn->select()
163 179
             ->from(
164 180
                 $this->getTrapCtrl()->getModuleConfig()->getTrapTableName(),
@@ -175,7 +191,9 @@  discard block
 block discarded – undo
175 191
     {
176 192
         
177 193
         $dbConn = $this->getDbConn();
178
-        if ($dbConn === null) throw new \ErrorException('uncatched db error');
194
+        if ($dbConn === null) {
195
+        	throw new \ErrorException('uncatched db error');
196
+        }
179 197
         
180 198
         $query=$dbConn->select()
181 199
         ->from(
@@ -183,18 +201,28 @@  discard block
 block discarded – undo
183 201
             array('value'=>'value'))
184 202
             ->where('name=?',$element);
185 203
             $returnRow=$dbConn->fetchRow($query);
186
-            if ($returnRow==null)  // value does not exists
204
+            if ($returnRow==null) {
205
+            	// value does not exists
187 206
             {
188 207
                 $default=$this->getTrapCtrl()->getModuleConfig()->getDBConfigDefaults();
189
-                if ( ! isset($default[$element])) return null; // no default and not value
208
+            }
209
+                if ( ! isset($default[$element])) {
210
+                	return null;
211
+                }
212
+                // no default and not value
190 213
                 
191 214
                 $this->addDBConfigValue($element,$default[$element]);
192 215
                 return $default[$element];
193 216
             }
194
-            if ($returnRow->value == null) // value id empty
217
+            if ($returnRow->value == null) {
218
+            	// value id empty
195 219
             {
196 220
                 $default=$this->getTrapCtrl()->getModuleConfig()->getDBConfigDefaults();
197
-                if ( ! isset($default[$element])) return null; // no default and not value
221
+            }
222
+                if ( ! isset($default[$element])) {
223
+                	return null;
224
+                }
225
+                // no default and not value
198 226
                 $this->setDBConfigValue($element,$default[$element]);
199 227
                 return $default[$element];
200 228
             }
@@ -210,7 +238,9 @@  discard block
 block discarded – undo
210 238
     {
211 239
         
212 240
         $dbConn = $this->getDbConn();
213
-        if ($dbConn === null) throw new \ErrorException('uncatched db error');
241
+        if ($dbConn === null) {
242
+        	throw new \ErrorException('uncatched db error');
243
+        }
214 244
         
215 245
         $query=$dbConn->insert(
216 246
             $this->getTrapCtrl()->getModuleConfig()->getDbConfigTableName(),
@@ -230,7 +260,9 @@  discard block
 block discarded – undo
230 260
     {
231 261
         
232 262
         $dbConn = $this->getDbConn();
233
-        if ($dbConn === null) throw new \ErrorException('uncatched db error');
263
+        if ($dbConn === null) {
264
+        	throw new \ErrorException('uncatched db error');
265
+        }
234 266
         
235 267
         $query=$dbConn->update(
236 268
             $this->getTrapCtrl()->getModuleConfig()->getDbConfigTableName(),
Please login to merge, or discard this patch.
library/Trapdirector/TrapsProcess/TrapApi.php 2 patches
Indentation   +76 added lines, -76 removed lines patch added patch discarded remove patch
@@ -17,93 +17,93 @@
 block discarded – undo
17 17
 class TrapApi
18 18
 {
19 19
 
20
-    // Constants
21
-    public const MASTER=1;
22
-    public const MASTERHA=2;
23
-    public const SAT=3;
24
-    public $stateArray = array('MASTER' => TrapApi::MASTER, 'MASTERHA' => TrapApi::MASTERHA , 'SAT' => TrapApi::SAT  );
20
+	// Constants
21
+	public const MASTER=1;
22
+	public const MASTERHA=2;
23
+	public const SAT=3;
24
+	public $stateArray = array('MASTER' => TrapApi::MASTER, 'MASTERHA' => TrapApi::MASTERHA , 'SAT' => TrapApi::SAT  );
25 25
     
26
-    /** @var integer $whoami current server : MASTER MASTERHA or SAT */
27
-    public $whoami = TrapApi::MASTER;
28
-    /** @var string $masterIP ip of master if MASTERHA or SAT  */
29
-    public $masterIP='';
30
-    /** @var integer $masterPort port of master if MASTERHA or SAT  */
31
-    public $masterPort=443;
32
-    /** @var string $masterUser user to log in API  */
33
-    public $masterUser='';
34
-    /** @var string $masterPass password */
35
-    public $masterPass='';
26
+	/** @var integer $whoami current server : MASTER MASTERHA or SAT */
27
+	public $whoami = TrapApi::MASTER;
28
+	/** @var string $masterIP ip of master if MASTERHA or SAT  */
29
+	public $masterIP='';
30
+	/** @var integer $masterPort port of master if MASTERHA or SAT  */
31
+	public $masterPort=443;
32
+	/** @var string $masterUser user to log in API  */
33
+	public $masterUser='';
34
+	/** @var string $masterPass password */
35
+	public $masterPass='';
36 36
     
37
-    /** @var Logging $logging logging class */
38
-    protected $logging;
37
+	/** @var Logging $logging logging class */
38
+	protected $logging;
39 39
     
40
-    /**
41
-     * Create TrapApi class
42
-     * @param Logging $logClass
43
-     */
44
-    function __construct($logClass)
45
-    {
46
-        $this->logging=$logClass;
47
-    }
40
+	/**
41
+	 * Create TrapApi class
42
+	 * @param Logging $logClass
43
+	 */
44
+	function __construct($logClass)
45
+	{
46
+		$this->logging=$logClass;
47
+	}
48 48
 
49
-    /**
50
-     * Return true if ode is master.
51
-     * @return boolean
52
-     */
53
-    public function isMaster()
54
-    {
55
-        return ($this->whoami == MASTER);
56
-    }
49
+	/**
50
+	 * Return true if ode is master.
51
+	 * @return boolean
52
+	 */
53
+	public function isMaster()
54
+	{
55
+		return ($this->whoami == MASTER);
56
+	}
57 57
 
58
-    /**
59
-     * return status of node
60
-     * @return number
61
-     */
62
-    public function getStatus()
63
-    {
64
-        return $this->whoami;    
65
-    }
58
+	/**
59
+	 * return status of node
60
+	 * @return number
61
+	 */
62
+	public function getStatus()
63
+	{
64
+		return $this->whoami;    
65
+	}
66 66
     
67
-    /**
68
-     * Set status os node to $status
69
-     * @param string $status
70
-     * @return boolean : true if $status is correct, or false.
71
-     */
72
-    public function setStatus(string $status)
73
-    {
74
-        if (! isset($this->stateArray[$status]))
75
-        {
76
-            return FALSE;
77
-        }
67
+	/**
68
+	 * Set status os node to $status
69
+	 * @param string $status
70
+	 * @return boolean : true if $status is correct, or false.
71
+	 */
72
+	public function setStatus(string $status)
73
+	{
74
+		if (! isset($this->stateArray[$status]))
75
+		{
76
+			return FALSE;
77
+		}
78 78
         
79
-        $this->logging->log('Setting status to : ' . $status, INFO);
79
+		$this->logging->log('Setting status to : ' . $status, INFO);
80 80
         
81
-        $this->whoami = $this->stateArray[$status];
81
+		$this->whoami = $this->stateArray[$status];
82 82
         
83
-        return TRUE;
84
-    }
83
+		return TRUE;
84
+	}
85 85
  
86
-    public function setStatusMaster()
87
-    {
88
-        $this->whoami = TrapApi::MASTER;
89
-    }
86
+	public function setStatusMaster()
87
+	{
88
+		$this->whoami = TrapApi::MASTER;
89
+	}
90 90
     
91
-    /**
92
-     * Set params for API connection
93
-     * @param string $IP
94
-     * @param int $port
95
-     * @param string $user
96
-     * @param string $pass
97
-     * @return boolean true if params are OK
98
-     */
99
-    public function setParams(string $IP, int $port, string $user, string $pass)
100
-    {
101
-        $this->masterIP = $IP;
102
-        $this->masterPort = $port;
103
-        $this->masterUser = $user;
104
-        $this->masterPass = $pass;
91
+	/**
92
+	 * Set params for API connection
93
+	 * @param string $IP
94
+	 * @param int $port
95
+	 * @param string $user
96
+	 * @param string $pass
97
+	 * @return boolean true if params are OK
98
+	 */
99
+	public function setParams(string $IP, int $port, string $user, string $pass)
100
+	{
101
+		$this->masterIP = $IP;
102
+		$this->masterPort = $port;
103
+		$this->masterUser = $user;
104
+		$this->masterPass = $pass;
105 105
         
106
-        return true;
107
-    }
106
+		return true;
107
+	}
108 108
     
109 109
 }
110 110
\ No newline at end of file
Please login to merge, or discard this patch.
Spacing   +10 added lines, -10 removed lines patch added patch discarded remove patch
@@ -21,10 +21,10 @@  discard block
 block discarded – undo
21 21
     public const MASTER=1;
22 22
     public const MASTERHA=2;
23 23
     public const SAT=3;
24
-    public $stateArray = array('MASTER' => TrapApi::MASTER, 'MASTERHA' => TrapApi::MASTERHA , 'SAT' => TrapApi::SAT  );
24
+    public $stateArray=array('MASTER' => TrapApi::MASTER, 'MASTERHA' => TrapApi::MASTERHA, 'SAT' => TrapApi::SAT);
25 25
     
26 26
     /** @var integer $whoami current server : MASTER MASTERHA or SAT */
27
-    public $whoami = TrapApi::MASTER;
27
+    public $whoami=TrapApi::MASTER;
28 28
     /** @var string $masterIP ip of master if MASTERHA or SAT  */
29 29
     public $masterIP='';
30 30
     /** @var integer $masterPort port of master if MASTERHA or SAT  */
@@ -71,21 +71,21 @@  discard block
 block discarded – undo
71 71
      */
72 72
     public function setStatus(string $status)
73 73
     {
74
-        if (! isset($this->stateArray[$status]))
74
+        if (!isset($this->stateArray[$status]))
75 75
         {
76 76
             return FALSE;
77 77
         }
78 78
         
79
-        $this->logging->log('Setting status to : ' . $status, INFO);
79
+        $this->logging->log('Setting status to : '.$status, INFO);
80 80
         
81
-        $this->whoami = $this->stateArray[$status];
81
+        $this->whoami=$this->stateArray[$status];
82 82
         
83 83
         return TRUE;
84 84
     }
85 85
  
86 86
     public function setStatusMaster()
87 87
     {
88
-        $this->whoami = TrapApi::MASTER;
88
+        $this->whoami=TrapApi::MASTER;
89 89
     }
90 90
     
91 91
     /**
@@ -98,10 +98,10 @@  discard block
 block discarded – undo
98 98
      */
99 99
     public function setParams(string $IP, int $port, string $user, string $pass)
100 100
     {
101
-        $this->masterIP = $IP;
102
-        $this->masterPort = $port;
103
-        $this->masterUser = $user;
104
-        $this->masterPass = $pass;
101
+        $this->masterIP=$IP;
102
+        $this->masterPort=$port;
103
+        $this->masterUser=$user;
104
+        $this->masterPass=$pass;
105 105
         
106 106
         return true;
107 107
     }
Please login to merge, or discard this patch.
library/Trapdirector/Rest/RestAPI.php 3 patches
Indentation   +34 added lines, -34 removed lines patch added patch discarded remove patch
@@ -14,43 +14,43 @@
 block discarded – undo
14 14
 
15 15
 class RestAPI
16 16
 {
17
-    public $version=1;
17
+	public $version=1;
18 18
     
19
-    /**
20
-     * @var TrapsController $trapController
21
-     */
22
-    protected $trapController=null;
19
+	/**
20
+	 * @var TrapsController $trapController
21
+	 */
22
+	protected $trapController=null;
23 23
     
24
-    public function __construct(TrapsController $trapCtrl)
25
-    {
26
-        $this->trapController=$trapCtrl;
27
-    }
24
+	public function __construct(TrapsController $trapCtrl)
25
+	{
26
+		$this->trapController=$trapCtrl;
27
+	}
28 28
     
29
-    public function sendJson($object)
30
-    {
31
-        $this->trapController->getResponse()->setHeader('Content-Type', 'application/json', true);        
32
-        $this->trapController->getResponse()->sendHeaders();
33
-        $this->trapController->helper_ret(json_encode($object, JSON_PRETTY_PRINT));
34
-        //$this->trapController->_helper->json($object);
35
-        //echo json_encode($object, JSON_PRETTY_PRINT) . "\n";
36
-    }
29
+	public function sendJson($object)
30
+	{
31
+		$this->trapController->getResponse()->setHeader('Content-Type', 'application/json', true);        
32
+		$this->trapController->getResponse()->sendHeaders();
33
+		$this->trapController->helper_ret(json_encode($object, JSON_PRETTY_PRINT));
34
+		//$this->trapController->_helper->json($object);
35
+		//echo json_encode($object, JSON_PRETTY_PRINT) . "\n";
36
+	}
37 37
     
38
-    protected function sendJsonError(string $error, int $retCode = 200)
39
-    {
40
-        //TODO
41
-        $this->sendJson('{"Error":"'.$error.'"}');
42
-    }
38
+	protected function sendJsonError(string $error, int $retCode = 200)
39
+	{
40
+		//TODO
41
+		$this->sendJson('{"Error":"'.$error.'"}');
42
+	}
43 43
     
44
-    public function last_modified()
45
-    {
46
-        try 
47
-        {
48
-            $query = $this->trapController->getUIDatabase()->lastModification();
49
-            return array('lastModified' => $query);
50
-        } 
51
-        catch (\ErrorException $e) 
52
-        {
53
-            return array('Error' =>  $e->getMessage());
54
-        }
55
-    }
44
+	public function last_modified()
45
+	{
46
+		try 
47
+		{
48
+			$query = $this->trapController->getUIDatabase()->lastModification();
49
+			return array('lastModified' => $query);
50
+		} 
51
+		catch (\ErrorException $e) 
52
+		{
53
+			return array('Error' =>  $e->getMessage());
54
+		}
55
+	}
56 56
 }
57 57
\ No newline at end of file
Please login to merge, or discard this patch.
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -35,7 +35,7 @@  discard block
 block discarded – undo
35 35
         //echo json_encode($object, JSON_PRETTY_PRINT) . "\n";
36 36
     }
37 37
     
38
-    protected function sendJsonError(string $error, int $retCode = 200)
38
+    protected function sendJsonError(string $error, int $retCode=200)
39 39
     {
40 40
         //TODO
41 41
         $this->sendJson('{"Error":"'.$error.'"}');
@@ -45,7 +45,7 @@  discard block
 block discarded – undo
45 45
     {
46 46
         try 
47 47
         {
48
-            $query = $this->trapController->getUIDatabase()->lastModification();
48
+            $query=$this->trapController->getUIDatabase()->lastModification();
49 49
             return array('lastModified' => $query);
50 50
         } 
51 51
         catch (\ErrorException $e) 
Please login to merge, or discard this patch.
Braces   +1 added lines, -2 removed lines patch added patch discarded remove patch
@@ -47,8 +47,7 @@
 block discarded – undo
47 47
         {
48 48
             $query = $this->trapController->getUIDatabase()->lastModification();
49 49
             return array('lastModified' => $query);
50
-        } 
51
-        catch (\ErrorException $e) 
50
+        } catch (\ErrorException $e) 
52 51
         {
53 52
             return array('Error' =>  $e->getMessage());
54 53
         }
Please login to merge, or discard this patch.
library/Trapdirector/Icinga2Api.php 3 patches
Indentation   +336 added lines, -336 removed lines patch added patch discarded remove patch
@@ -8,367 +8,367 @@
 block discarded – undo
8 8
 
9 9
 class Icinga2API 
10 10
 {
11
-    protected $version = 'v1';      //< icinga2 api version
11
+	protected $version = 'v1';      //< icinga2 api version
12 12
     
13
-    protected $host;                //< icinga2 host name or IP
14
-    protected $port;                //< icinga2 api port
13
+	protected $host;                //< icinga2 host name or IP
14
+	protected $port;                //< icinga2 api port
15 15
     
16
-    protected $user;                //< user name
17
-    protected $pass;                //< user password
18
-    protected $usercert;            //< user key for certificate auth (NOT IMPLEMENTED)
19
-    protected $authmethod='pass';   //< Authentication : 'pass' or 'cert'
16
+	protected $user;                //< user name
17
+	protected $pass;                //< user password
18
+	protected $usercert;            //< user key for certificate auth (NOT IMPLEMENTED)
19
+	protected $authmethod='pass';   //< Authentication : 'pass' or 'cert'
20 20
 
21
-    protected $curl;
22
-    // http://php.net/manual/de/function.json-last-error.php#119985
23
-    protected $errorReference = [
24
-        JSON_ERROR_NONE => 'No error has occurred.',
25
-        JSON_ERROR_DEPTH => 'The maximum stack depth has been exceeded.',
26
-        JSON_ERROR_STATE_MISMATCH => 'Invalid or malformed JSON.',
27
-        JSON_ERROR_CTRL_CHAR => 'Control character error, possibly incorrectly encoded.',
28
-        JSON_ERROR_SYNTAX => 'Syntax error.',
29
-        JSON_ERROR_UTF8 => 'Malformed UTF-8 characters, possibly incorrectly encoded.',
30
-        JSON_ERROR_RECURSION => 'One or more recursive references in the value to be encoded.',
31
-        JSON_ERROR_INF_OR_NAN => 'One or more NAN or INF values in the value to be encoded.',
32
-        JSON_ERROR_UNSUPPORTED_TYPE => 'A value of a type that cannot be encoded was given.',
33
-    ];
34
-    const JSON_UNKNOWN_ERROR = 'Unknown error.';
21
+	protected $curl;
22
+	// http://php.net/manual/de/function.json-last-error.php#119985
23
+	protected $errorReference = [
24
+		JSON_ERROR_NONE => 'No error has occurred.',
25
+		JSON_ERROR_DEPTH => 'The maximum stack depth has been exceeded.',
26
+		JSON_ERROR_STATE_MISMATCH => 'Invalid or malformed JSON.',
27
+		JSON_ERROR_CTRL_CHAR => 'Control character error, possibly incorrectly encoded.',
28
+		JSON_ERROR_SYNTAX => 'Syntax error.',
29
+		JSON_ERROR_UTF8 => 'Malformed UTF-8 characters, possibly incorrectly encoded.',
30
+		JSON_ERROR_RECURSION => 'One or more recursive references in the value to be encoded.',
31
+		JSON_ERROR_INF_OR_NAN => 'One or more NAN or INF values in the value to be encoded.',
32
+		JSON_ERROR_UNSUPPORTED_TYPE => 'A value of a type that cannot be encoded was given.',
33
+	];
34
+	const JSON_UNKNOWN_ERROR = 'Unknown error.';
35 35
     
36
-    /**
37
-     * Creates Icinga2API object
38
-     * 
39
-     * @param string $host host name or IP
40
-     * @param number $port API port
41
-     */
42
-    public function __construct($host, $port = 5665)
43
-    {
44
-        $this->host=$host;
45
-        $this->port=$port;
46
-    }
47
-    /**
48
-     * Set user & pass
49
-     * @param string $user
50
-     * @param string $pass
51
-     */
52
-    public function setCredentials($user,$pass)
53
-    {
54
-        $this->user=$user;
55
-        $this->pass=$pass;
56
-        $this->authmethod='pass';
57
-    }
36
+	/**
37
+	 * Creates Icinga2API object
38
+	 * 
39
+	 * @param string $host host name or IP
40
+	 * @param number $port API port
41
+	 */
42
+	public function __construct($host, $port = 5665)
43
+	{
44
+		$this->host=$host;
45
+		$this->port=$port;
46
+	}
47
+	/**
48
+	 * Set user & pass
49
+	 * @param string $user
50
+	 * @param string $pass
51
+	 */
52
+	public function setCredentials($user,$pass)
53
+	{
54
+		$this->user=$user;
55
+		$this->pass=$pass;
56
+		$this->authmethod='pass';
57
+	}
58 58
     
59
-    /**
60
-     * Set user & certificate (NOT IMPLEMENTED @throws RuntimeException)
61
-     * @param string $user
62
-     * @param string $usercert
63
-     */
64
-    public function setCredentialskey($user,$usercert)
65
-    {
66
-        $this->user=$user;
67
-        $this->usercert=$usercert;
68
-        $this->authmethod='cert';
69
-        throw new RuntimeException('Certificate auth not implemented');
70
-    }
59
+	/**
60
+	 * Set user & certificate (NOT IMPLEMENTED @throws RuntimeException)
61
+	 * @param string $user
62
+	 * @param string $usercert
63
+	 */
64
+	public function setCredentialskey($user,$usercert)
65
+	{
66
+		$this->user=$user;
67
+		$this->usercert=$usercert;
68
+		$this->authmethod='cert';
69
+		throw new RuntimeException('Certificate auth not implemented');
70
+	}
71 71
 
72
-    public function test(array $permissions)
73
-    {
74
-       try
75
-        {
76
-            $result=$this->request('GET', "", NULL, NULL);
77
-        } 
78
-        catch (Exception $e)
79
-        {
80
-            return array(true, 'Error with API : '.$e->getMessage());
81
-        }
82
-        //var_dump($result);
83
-        $permOk=1;
84
-        $permMissing='';
85
-        if ($permissions === NULL) // If no permission check return OK after connexion
86
-        {
87
-            return array(false,'OK');
88
-        }
89
-        if (property_exists($result, 'results') && property_exists($result->results[0], 'permissions'))
90
-        {
72
+	public function test(array $permissions)
73
+	{
74
+	   try
75
+		{
76
+			$result=$this->request('GET', "", NULL, NULL);
77
+		} 
78
+		catch (Exception $e)
79
+		{
80
+			return array(true, 'Error with API : '.$e->getMessage());
81
+		}
82
+		//var_dump($result);
83
+		$permOk=1;
84
+		$permMissing='';
85
+		if ($permissions === NULL) // If no permission check return OK after connexion
86
+		{
87
+			return array(false,'OK');
88
+		}
89
+		if (property_exists($result, 'results') && property_exists($result->results[0], 'permissions'))
90
+		{
91 91
             
92
-            foreach ( $permissions as $mustPermission)
93
-            {
94
-                $curPermOK=0;
95
-                foreach ( $result->results[0]->permissions as $curPermission)
96
-                {
97
-                    $curPermission=preg_replace('/\*/','.*',$curPermission); // put * as .* to created a regexp
98
-                    if (preg_match('#'.$curPermission.'#',$mustPermission))
99
-                    {
100
-                        $curPermOK=1;
101
-                        break;
102
-                    }
103
-                }
104
-                if ($curPermOK == 0)
105
-                {
106
-                    $permOk=0;
107
-                    $permMissing=$mustPermission;
108
-                    break;
109
-                }
110
-            }
111
-            if ($permOk == 0)
112
-            {
113
-                return array(true,'API connection OK, but missing permission : '.$permMissing);
114
-            }
115
-            return array(false,'API connection OK');
92
+			foreach ( $permissions as $mustPermission)
93
+			{
94
+				$curPermOK=0;
95
+				foreach ( $result->results[0]->permissions as $curPermission)
96
+				{
97
+					$curPermission=preg_replace('/\*/','.*',$curPermission); // put * as .* to created a regexp
98
+					if (preg_match('#'.$curPermission.'#',$mustPermission))
99
+					{
100
+						$curPermOK=1;
101
+						break;
102
+					}
103
+				}
104
+				if ($curPermOK == 0)
105
+				{
106
+					$permOk=0;
107
+					$permMissing=$mustPermission;
108
+					break;
109
+				}
110
+			}
111
+			if ($permOk == 0)
112
+			{
113
+				return array(true,'API connection OK, but missing permission : '.$permMissing);
114
+			}
115
+			return array(false,'API connection OK');
116 116
             
117
-        }
118
-        return array(true,'API connection OK, but cannot get permissions');
119
-    }
117
+		}
118
+		return array(true,'API connection OK, but cannot get permissions');
119
+	}
120 120
     
121 121
     
122
-    protected function url($url) {
123
-        return sprintf('https://%s:%d/%s/%s', $this->host, $this->port, $this->version, $url);
124
-    }
122
+	protected function url($url) {
123
+		return sprintf('https://%s:%d/%s/%s', $this->host, $this->port, $this->version, $url);
124
+	}
125 125
     
126
-    /**
127
-     * Create or return curl ressource
128
-     * @throws Exception
129
-     * @return resource
130
-     */
131
-    protected function curl() {
132
-        if ($this->curl === null) {
133
-            $this->curl = curl_init(sprintf('https://%s:%d', $this->host, $this->port));
134
-            if ($this->curl === false) {
135
-                throw new Exception('CURL INIT ERROR');
136
-            }
137
-        }
138
-        return $this->curl;
139
-    }
126
+	/**
127
+	 * Create or return curl ressource
128
+	 * @throws Exception
129
+	 * @return resource
130
+	 */
131
+	protected function curl() {
132
+		if ($this->curl === null) {
133
+			$this->curl = curl_init(sprintf('https://%s:%d', $this->host, $this->port));
134
+			if ($this->curl === false) {
135
+				throw new Exception('CURL INIT ERROR');
136
+			}
137
+		}
138
+		return $this->curl;
139
+	}
140 140
 
141
-    /**
142
-     * Send a passive service check
143
-     * @param string $host : host name 
144
-     * @param string $service : service name
145
-     * @param int $state : state of service
146
-     * @param string $display : service passive check output
147
-     * @param string $perfdata : performance data as string
148
-     * @return array (status = true (oK) or false (nok), string message)
149
-     */
150
-    public function serviceCheckResult($host,$service,$state,$display,$perfdata='')
151
-    {
152
-        //Send a POST request to the URL endpoint /v1/actions/process-check-result
153
-        //actions/process-check-result?service=example.localdomain!passive-ping6
154
-        $url='actions/process-check-result';
155
-        $body=array(
156
-            "filter"        => 'service.name=="'.$service.'" && service.host_name=="'.$host.'"',
157
-            'type'          => 'Service',
158
-            "exit_status"   => $state,
159
-            "plugin_output" => $display,
160
-            "performance_data" => $perfdata
161
-        );
162
-        try 
163
-        {
164
-            $result=$this->request('POST', $url, null, $body);
165
-        } catch (Exception $e) 
166
-        {
167
-            return array(false, $e->getMessage());
168
-        }
169
-        if (property_exists($result,'error') )
170
-        {
171
-            if (property_exists($result,'status'))
172
-            {
173
-                $message=$result->status;
174
-            }
175
-            else 
176
-            {
177
-                $message="Unkown status";
178
-            }
179
-            return array(false , 'Ret code ' .$result->error.' : '.$message);
180
-        }
181
-        if (property_exists($result, 'results'))
182
-        {
183
-            if (isset($result->results[0]))
184
-            {
185
-                return array(true,'code '.$result->results[0]->code.' : '.$result->results[0]->status);
186
-            }
187
-            else
188
-            {
189
-                return array(false,'Service not found');
190
-            }
141
+	/**
142
+	 * Send a passive service check
143
+	 * @param string $host : host name 
144
+	 * @param string $service : service name
145
+	 * @param int $state : state of service
146
+	 * @param string $display : service passive check output
147
+	 * @param string $perfdata : performance data as string
148
+	 * @return array (status = true (oK) or false (nok), string message)
149
+	 */
150
+	public function serviceCheckResult($host,$service,$state,$display,$perfdata='')
151
+	{
152
+		//Send a POST request to the URL endpoint /v1/actions/process-check-result
153
+		//actions/process-check-result?service=example.localdomain!passive-ping6
154
+		$url='actions/process-check-result';
155
+		$body=array(
156
+			"filter"        => 'service.name=="'.$service.'" && service.host_name=="'.$host.'"',
157
+			'type'          => 'Service',
158
+			"exit_status"   => $state,
159
+			"plugin_output" => $display,
160
+			"performance_data" => $perfdata
161
+		);
162
+		try 
163
+		{
164
+			$result=$this->request('POST', $url, null, $body);
165
+		} catch (Exception $e) 
166
+		{
167
+			return array(false, $e->getMessage());
168
+		}
169
+		if (property_exists($result,'error') )
170
+		{
171
+			if (property_exists($result,'status'))
172
+			{
173
+				$message=$result->status;
174
+			}
175
+			else 
176
+			{
177
+				$message="Unkown status";
178
+			}
179
+			return array(false , 'Ret code ' .$result->error.' : '.$message);
180
+		}
181
+		if (property_exists($result, 'results'))
182
+		{
183
+			if (isset($result->results[0]))
184
+			{
185
+				return array(true,'code '.$result->results[0]->code.' : '.$result->results[0]->status);
186
+			}
187
+			else
188
+			{
189
+				return array(false,'Service not found');
190
+			}
191 191
             
192
-        }
193
-        return array(false,'Unkown result, open issue with this : '.print_r($result,true));
194
-    }
192
+		}
193
+		return array(false,'Unkown result, open issue with this : '.print_r($result,true));
194
+	}
195 195
  
196
-    /**
197
-     * return array of host by IP (4 or 6)
198
-     * @param string $ip
199
-     * @throws Exception
200
-     * @return array objects : array('__name','name','display_name')
201
-     */
202
-    public function getHostByIP($ip) 
203
-    {
204
-        /*
196
+	/**
197
+	 * return array of host by IP (4 or 6)
198
+	 * @param string $ip
199
+	 * @throws Exception
200
+	 * @return array objects : array('__name','name','display_name')
201
+	 */
202
+	public function getHostByIP($ip) 
203
+	{
204
+		/*
205 205
          *  curl -k -s -u  trapdirector:trapdirector -H 'X-HTTP-Method-Override: GET' -X POST 'https://localhost:5665/v1/objects/hosts' 
206 206
          *  -d '{"filter":"host.group==\"test_trap\"","attrs": ["address" ,"address6"]}'
207 207
             
208 208
             {"results":[{"attrs":{"__name":"Icinga host","address":"127.0.0.1","display_name":"Icinga host","name":"Icinga host"},"joins":{},"meta":{},"name":"Icinga host","type":"Host"}]}
209 209
          */
210 210
         
211
-        $url='objects/hosts';
212
-        $body=array(
213
-            "filter"        => 'host.address=="'.$ip.'" || host.address6=="'.$ip.'"',
214
-            "attrs"         => array('__name','name','display_name')
215
-        );
216
-        try
217
-        {
218
-            $result=$this->request('POST', $url, array('X-HTTP-Method-Override: GET'), $body);
219
-        } catch (Exception $e)
220
-        {
221
-            throw new Exception($e->getMessage());
222
-        }
211
+		$url='objects/hosts';
212
+		$body=array(
213
+			"filter"        => 'host.address=="'.$ip.'" || host.address6=="'.$ip.'"',
214
+			"attrs"         => array('__name','name','display_name')
215
+		);
216
+		try
217
+		{
218
+			$result=$this->request('POST', $url, array('X-HTTP-Method-Override: GET'), $body);
219
+		} catch (Exception $e)
220
+		{
221
+			throw new Exception($e->getMessage());
222
+		}
223 223
         
224
-        if (property_exists($result,'error') )
225
-        {
226
-            if (property_exists($result,'status'))
227
-            {
228
-                throw new Exception('Ret code ' .$result->error.' : ' . $result->status);
229
-            }
230
-            else
231
-            {
232
-                throw new Exception('Ret code ' .$result->error.' : Unkown status');
233
-            }
234
-        }
235
-        if (property_exists($result, 'results'))
236
-        {
237
-            $numHost=0;
238
-            $hostArray=array();
239
-            while (isset($result->results[$numHost]) && property_exists ($result->results[$numHost],'attrs'))
240
-            {
241
-                $hostArray[$numHost] = $result->results[$numHost]->attrs;
242
-                $numHost++;
243
-            }
244
-            return $hostArray;            
245
-        }
246
-        throw new Exception('Unkown result');
247
-    }
224
+		if (property_exists($result,'error') )
225
+		{
226
+			if (property_exists($result,'status'))
227
+			{
228
+				throw new Exception('Ret code ' .$result->error.' : ' . $result->status);
229
+			}
230
+			else
231
+			{
232
+				throw new Exception('Ret code ' .$result->error.' : Unkown status');
233
+			}
234
+		}
235
+		if (property_exists($result, 'results'))
236
+		{
237
+			$numHost=0;
238
+			$hostArray=array();
239
+			while (isset($result->results[$numHost]) && property_exists ($result->results[$numHost],'attrs'))
240
+			{
241
+				$hostArray[$numHost] = $result->results[$numHost]->attrs;
242
+				$numHost++;
243
+			}
244
+			return $hostArray;            
245
+		}
246
+		throw new Exception('Unkown result');
247
+	}
248 248
 
249
-    /**
250
-     * Get all host and IP from hostgroup
251
-     * @param string $hostGroup
252
-     * @throws Exception
253
-     * @return array : attributes : address, address6, name
254
-     */
255
-    public function getHostsIPByHostGroup($hostGroup)
256
-    {        
257
-        $url='objects/hosts';
258
-        $body=array(
259
-            "filter"        => '\"'.$hostGroup.'\" in host.groups',
260
-            "attrs"         => array('address','address','name')
261
-        );
262
-        try
263
-        {
264
-            $result=$this->request('POST', $url, array('X-HTTP-Method-Override: GET'), $body);
265
-        } catch (Exception $e)
266
-        {
267
-            throw new Exception($e->getMessage());
268
-        }
249
+	/**
250
+	 * Get all host and IP from hostgroup
251
+	 * @param string $hostGroup
252
+	 * @throws Exception
253
+	 * @return array : attributes : address, address6, name
254
+	 */
255
+	public function getHostsIPByHostGroup($hostGroup)
256
+	{        
257
+		$url='objects/hosts';
258
+		$body=array(
259
+			"filter"        => '\"'.$hostGroup.'\" in host.groups',
260
+			"attrs"         => array('address','address','name')
261
+		);
262
+		try
263
+		{
264
+			$result=$this->request('POST', $url, array('X-HTTP-Method-Override: GET'), $body);
265
+		} catch (Exception $e)
266
+		{
267
+			throw new Exception($e->getMessage());
268
+		}
269 269
         
270
-        if (property_exists($result,'error') )
271
-        {
272
-            if (property_exists($result,'status'))
273
-            {
274
-                throw new Exception('Ret code ' .$result->error.' : ' . $result->status);
275
-            }
276
-            else
277
-            {
278
-                throw new Exception('Ret code ' .$result->error.' : Unkown status');
279
-            }
280
-        }
281
-        if (property_exists($result, 'results'))
282
-        {
283
-            $numHost=0;
284
-            $hostArray=array();
285
-            while (isset($result->results[$numHost]) && property_exists ($result->results[$numHost],'attrs'))
286
-            {
287
-                $hostArray[$numHost] = $result->results[$numHost]->attrs;
288
-                $hostArray[$numHost]->name = $result->results[$numHost]->name;
289
-                $numHost++;
290
-            }
291
-            return $hostArray;
292
-        }
293
-        throw new Exception('Unkown result');
294
-    }
270
+		if (property_exists($result,'error') )
271
+		{
272
+			if (property_exists($result,'status'))
273
+			{
274
+				throw new Exception('Ret code ' .$result->error.' : ' . $result->status);
275
+			}
276
+			else
277
+			{
278
+				throw new Exception('Ret code ' .$result->error.' : Unkown status');
279
+			}
280
+		}
281
+		if (property_exists($result, 'results'))
282
+		{
283
+			$numHost=0;
284
+			$hostArray=array();
285
+			while (isset($result->results[$numHost]) && property_exists ($result->results[$numHost],'attrs'))
286
+			{
287
+				$hostArray[$numHost] = $result->results[$numHost]->attrs;
288
+				$hostArray[$numHost]->name = $result->results[$numHost]->name;
289
+				$numHost++;
290
+			}
291
+			return $hostArray;
292
+		}
293
+		throw new Exception('Unkown result');
294
+	}
295 295
     
296
-    /**
297
-     * Send request to API
298
-     * @param string $method get/post/...
299
-     * @param string $url (after /v1/ )
300
-     * @param array $headers
301
-     * @param array $body 
302
-     * @throws Exception
303
-     * @return array
304
-     */
305
-    public function request($method, $url, $headers, $body) {
306
-        $auth = sprintf('%s:%s', $this->user, $this->pass);
307
-        $curlHeaders = array("Accept: application/json");
308
-        if ($body !== null) {
309
-            $body = json_encode($body);
310
-            array_push($curlHeaders, 'Content-Type: application/json');
311
-            //array_push($curlHeaders, 'X-HTTP-Method-Override: GET');
312
-        }
313
-        //var_dump($body);
314
-        //var_dump($this->url($url));
315
-        if ($headers !== null) {
316
-            $curlFinalHeaders = array_merge($curlHeaders, $headers);
317
-        } else 
318
-        {
319
-            $curlFinalHeaders=$curlHeaders;
320
-        }
321
-        $curl = $this->curl();
322
-        $opts = array(
323
-            CURLOPT_URL		=> $this->url($url),
324
-            CURLOPT_HTTPHEADER 	=> $curlFinalHeaders,
325
-            CURLOPT_USERPWD		=> $auth,
326
-            CURLOPT_CUSTOMREQUEST	=> strtoupper($method),
327
-            CURLOPT_RETURNTRANSFER 	=> true,
328
-            CURLOPT_CONNECTTIMEOUT 	=> 10,
329
-            CURLOPT_SSL_VERIFYHOST 	=> false,
330
-            CURLOPT_SSL_VERIFYPEER 	=> false,
331
-        );
332
-        if ($body !== null) {
333
-            $opts[CURLOPT_POSTFIELDS] = $body;
334
-        }
335
-        curl_setopt_array($curl, $opts);
336
-        $res = curl_exec($curl);
337
-        if ($res === false) {
338
-            throw new Exception('CURL ERROR: ' . curl_error($curl));
339
-        }
340
-        $statusCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
341
-        if ($statusCode === 401) {
342
-            throw new Exception('Unable to authenticate, please check your API credentials');
343
-        }
344
-        return $this->fromJsonResult($res);
345
-    }
296
+	/**
297
+	 * Send request to API
298
+	 * @param string $method get/post/...
299
+	 * @param string $url (after /v1/ )
300
+	 * @param array $headers
301
+	 * @param array $body 
302
+	 * @throws Exception
303
+	 * @return array
304
+	 */
305
+	public function request($method, $url, $headers, $body) {
306
+		$auth = sprintf('%s:%s', $this->user, $this->pass);
307
+		$curlHeaders = array("Accept: application/json");
308
+		if ($body !== null) {
309
+			$body = json_encode($body);
310
+			array_push($curlHeaders, 'Content-Type: application/json');
311
+			//array_push($curlHeaders, 'X-HTTP-Method-Override: GET');
312
+		}
313
+		//var_dump($body);
314
+		//var_dump($this->url($url));
315
+		if ($headers !== null) {
316
+			$curlFinalHeaders = array_merge($curlHeaders, $headers);
317
+		} else 
318
+		{
319
+			$curlFinalHeaders=$curlHeaders;
320
+		}
321
+		$curl = $this->curl();
322
+		$opts = array(
323
+			CURLOPT_URL		=> $this->url($url),
324
+			CURLOPT_HTTPHEADER 	=> $curlFinalHeaders,
325
+			CURLOPT_USERPWD		=> $auth,
326
+			CURLOPT_CUSTOMREQUEST	=> strtoupper($method),
327
+			CURLOPT_RETURNTRANSFER 	=> true,
328
+			CURLOPT_CONNECTTIMEOUT 	=> 10,
329
+			CURLOPT_SSL_VERIFYHOST 	=> false,
330
+			CURLOPT_SSL_VERIFYPEER 	=> false,
331
+		);
332
+		if ($body !== null) {
333
+			$opts[CURLOPT_POSTFIELDS] = $body;
334
+		}
335
+		curl_setopt_array($curl, $opts);
336
+		$res = curl_exec($curl);
337
+		if ($res === false) {
338
+			throw new Exception('CURL ERROR: ' . curl_error($curl));
339
+		}
340
+		$statusCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
341
+		if ($statusCode === 401) {
342
+			throw new Exception('Unable to authenticate, please check your API credentials');
343
+		}
344
+		return $this->fromJsonResult($res);
345
+	}
346 346
     
347
-    /**
348
-     * 
349
-     * @param string $json json encoded 
350
-     * @throws Exception
351
-     * @return array json decoded
352
-     */
353
-    protected function fromJsonResult($json) {
354
-        $result = @json_decode($json);
355
-        //var_dump($json);
356
-        if ($result === null) {
357
-            throw new Exception('Parsing JSON failed: '.$this->getLastJsonErrorMessage(json_last_error()));
358
-        }
359
-        return $result;
360
-    }
347
+	/**
348
+	 * 
349
+	 * @param string $json json encoded 
350
+	 * @throws Exception
351
+	 * @return array json decoded
352
+	 */
353
+	protected function fromJsonResult($json) {
354
+		$result = @json_decode($json);
355
+		//var_dump($json);
356
+		if ($result === null) {
357
+			throw new Exception('Parsing JSON failed: '.$this->getLastJsonErrorMessage(json_last_error()));
358
+		}
359
+		return $result;
360
+	}
361 361
     
362
-    /**
363
-     * Return text error no json error
364
-     * @param string $errorCode
365
-     * @return string
366
-     */
367
-    protected function getLastJsonErrorMessage($errorCode) {
368
-        if (!array_key_exists($errorCode, $this->errorReference)) {
369
-            return self::JSON_UNKNOWN_ERROR;
370
-        }
371
-        return $this->errorReference[$errorCode];
372
-    }
362
+	/**
363
+	 * Return text error no json error
364
+	 * @param string $errorCode
365
+	 * @return string
366
+	 */
367
+	protected function getLastJsonErrorMessage($errorCode) {
368
+		if (!array_key_exists($errorCode, $this->errorReference)) {
369
+			return self::JSON_UNKNOWN_ERROR;
370
+		}
371
+		return $this->errorReference[$errorCode];
372
+	}
373 373
 }
374 374
 
Please login to merge, or discard this patch.
Spacing   +54 added lines, -54 removed lines patch added patch discarded remove patch
@@ -8,19 +8,19 @@  discard block
 block discarded – undo
8 8
 
9 9
 class Icinga2API 
10 10
 {
11
-    protected $version = 'v1';      //< icinga2 api version
11
+    protected $version='v1'; //< icinga2 api version
12 12
     
13
-    protected $host;                //< icinga2 host name or IP
14
-    protected $port;                //< icinga2 api port
13
+    protected $host; //< icinga2 host name or IP
14
+    protected $port; //< icinga2 api port
15 15
     
16
-    protected $user;                //< user name
17
-    protected $pass;                //< user password
18
-    protected $usercert;            //< user key for certificate auth (NOT IMPLEMENTED)
19
-    protected $authmethod='pass';   //< Authentication : 'pass' or 'cert'
16
+    protected $user; //< user name
17
+    protected $pass; //< user password
18
+    protected $usercert; //< user key for certificate auth (NOT IMPLEMENTED)
19
+    protected $authmethod='pass'; //< Authentication : 'pass' or 'cert'
20 20
 
21 21
     protected $curl;
22 22
     // http://php.net/manual/de/function.json-last-error.php#119985
23
-    protected $errorReference = [
23
+    protected $errorReference=[
24 24
         JSON_ERROR_NONE => 'No error has occurred.',
25 25
         JSON_ERROR_DEPTH => 'The maximum stack depth has been exceeded.',
26 26
         JSON_ERROR_STATE_MISMATCH => 'Invalid or malformed JSON.',
@@ -31,7 +31,7 @@  discard block
 block discarded – undo
31 31
         JSON_ERROR_INF_OR_NAN => 'One or more NAN or INF values in the value to be encoded.',
32 32
         JSON_ERROR_UNSUPPORTED_TYPE => 'A value of a type that cannot be encoded was given.',
33 33
     ];
34
-    const JSON_UNKNOWN_ERROR = 'Unknown error.';
34
+    const JSON_UNKNOWN_ERROR='Unknown error.';
35 35
     
36 36
     /**
37 37
      * Creates Icinga2API object
@@ -39,7 +39,7 @@  discard block
 block discarded – undo
39 39
      * @param string $host host name or IP
40 40
      * @param number $port API port
41 41
      */
42
-    public function __construct($host, $port = 5665)
42
+    public function __construct($host, $port=5665)
43 43
     {
44 44
         $this->host=$host;
45 45
         $this->port=$port;
@@ -49,7 +49,7 @@  discard block
 block discarded – undo
49 49
      * @param string $user
50 50
      * @param string $pass
51 51
      */
52
-    public function setCredentials($user,$pass)
52
+    public function setCredentials($user, $pass)
53 53
     {
54 54
         $this->user=$user;
55 55
         $this->pass=$pass;
@@ -61,7 +61,7 @@  discard block
 block discarded – undo
61 61
      * @param string $user
62 62
      * @param string $usercert
63 63
      */
64
-    public function setCredentialskey($user,$usercert)
64
+    public function setCredentialskey($user, $usercert)
65 65
     {
66 66
         $this->user=$user;
67 67
         $this->usercert=$usercert;
@@ -84,18 +84,18 @@  discard block
 block discarded – undo
84 84
         $permMissing='';
85 85
         if ($permissions === NULL) // If no permission check return OK after connexion
86 86
         {
87
-            return array(false,'OK');
87
+            return array(false, 'OK');
88 88
         }
89 89
         if (property_exists($result, 'results') && property_exists($result->results[0], 'permissions'))
90 90
         {
91 91
             
92
-            foreach ( $permissions as $mustPermission)
92
+            foreach ($permissions as $mustPermission)
93 93
             {
94 94
                 $curPermOK=0;
95
-                foreach ( $result->results[0]->permissions as $curPermission)
95
+                foreach ($result->results[0]->permissions as $curPermission)
96 96
                 {
97
-                    $curPermission=preg_replace('/\*/','.*',$curPermission); // put * as .* to created a regexp
98
-                    if (preg_match('#'.$curPermission.'#',$mustPermission))
97
+                    $curPermission=preg_replace('/\*/', '.*', $curPermission); // put * as .* to created a regexp
98
+                    if (preg_match('#'.$curPermission.'#', $mustPermission))
99 99
                     {
100 100
                         $curPermOK=1;
101 101
                         break;
@@ -110,12 +110,12 @@  discard block
 block discarded – undo
110 110
             }
111 111
             if ($permOk == 0)
112 112
             {
113
-                return array(true,'API connection OK, but missing permission : '.$permMissing);
113
+                return array(true, 'API connection OK, but missing permission : '.$permMissing);
114 114
             }
115
-            return array(false,'API connection OK');
115
+            return array(false, 'API connection OK');
116 116
             
117 117
         }
118
-        return array(true,'API connection OK, but cannot get permissions');
118
+        return array(true, 'API connection OK, but cannot get permissions');
119 119
     }
120 120
     
121 121
     
@@ -130,7 +130,7 @@  discard block
 block discarded – undo
130 130
      */
131 131
     protected function curl() {
132 132
         if ($this->curl === null) {
133
-            $this->curl = curl_init(sprintf('https://%s:%d', $this->host, $this->port));
133
+            $this->curl=curl_init(sprintf('https://%s:%d', $this->host, $this->port));
134 134
             if ($this->curl === false) {
135 135
                 throw new Exception('CURL INIT ERROR');
136 136
             }
@@ -147,7 +147,7 @@  discard block
 block discarded – undo
147 147
      * @param string $perfdata : performance data as string
148 148
      * @return array (status = true (oK) or false (nok), string message)
149 149
      */
150
-    public function serviceCheckResult($host,$service,$state,$display,$perfdata='')
150
+    public function serviceCheckResult($host, $service, $state, $display, $perfdata='')
151 151
     {
152 152
         //Send a POST request to the URL endpoint /v1/actions/process-check-result
153 153
         //actions/process-check-result?service=example.localdomain!passive-ping6
@@ -166,9 +166,9 @@  discard block
 block discarded – undo
166 166
         {
167 167
             return array(false, $e->getMessage());
168 168
         }
169
-        if (property_exists($result,'error') )
169
+        if (property_exists($result, 'error'))
170 170
         {
171
-            if (property_exists($result,'status'))
171
+            if (property_exists($result, 'status'))
172 172
             {
173 173
                 $message=$result->status;
174 174
             }
@@ -176,21 +176,21 @@  discard block
 block discarded – undo
176 176
             {
177 177
                 $message="Unkown status";
178 178
             }
179
-            return array(false , 'Ret code ' .$result->error.' : '.$message);
179
+            return array(false, 'Ret code '.$result->error.' : '.$message);
180 180
         }
181 181
         if (property_exists($result, 'results'))
182 182
         {
183 183
             if (isset($result->results[0]))
184 184
             {
185
-                return array(true,'code '.$result->results[0]->code.' : '.$result->results[0]->status);
185
+                return array(true, 'code '.$result->results[0]->code.' : '.$result->results[0]->status);
186 186
             }
187 187
             else
188 188
             {
189
-                return array(false,'Service not found');
189
+                return array(false, 'Service not found');
190 190
             }
191 191
             
192 192
         }
193
-        return array(false,'Unkown result, open issue with this : '.print_r($result,true));
193
+        return array(false, 'Unkown result, open issue with this : '.print_r($result, true));
194 194
     }
195 195
  
196 196
     /**
@@ -211,7 +211,7 @@  discard block
 block discarded – undo
211 211
         $url='objects/hosts';
212 212
         $body=array(
213 213
             "filter"        => 'host.address=="'.$ip.'" || host.address6=="'.$ip.'"',
214
-            "attrs"         => array('__name','name','display_name')
214
+            "attrs"         => array('__name', 'name', 'display_name')
215 215
         );
216 216
         try
217 217
         {
@@ -221,24 +221,24 @@  discard block
 block discarded – undo
221 221
             throw new Exception($e->getMessage());
222 222
         }
223 223
         
224
-        if (property_exists($result,'error') )
224
+        if (property_exists($result, 'error'))
225 225
         {
226
-            if (property_exists($result,'status'))
226
+            if (property_exists($result, 'status'))
227 227
             {
228
-                throw new Exception('Ret code ' .$result->error.' : ' . $result->status);
228
+                throw new Exception('Ret code '.$result->error.' : '.$result->status);
229 229
             }
230 230
             else
231 231
             {
232
-                throw new Exception('Ret code ' .$result->error.' : Unkown status');
232
+                throw new Exception('Ret code '.$result->error.' : Unkown status');
233 233
             }
234 234
         }
235 235
         if (property_exists($result, 'results'))
236 236
         {
237 237
             $numHost=0;
238 238
             $hostArray=array();
239
-            while (isset($result->results[$numHost]) && property_exists ($result->results[$numHost],'attrs'))
239
+            while (isset($result->results[$numHost]) && property_exists($result->results[$numHost], 'attrs'))
240 240
             {
241
-                $hostArray[$numHost] = $result->results[$numHost]->attrs;
241
+                $hostArray[$numHost]=$result->results[$numHost]->attrs;
242 242
                 $numHost++;
243 243
             }
244 244
             return $hostArray;            
@@ -257,7 +257,7 @@  discard block
 block discarded – undo
257 257
         $url='objects/hosts';
258 258
         $body=array(
259 259
             "filter"        => '\"'.$hostGroup.'\" in host.groups',
260
-            "attrs"         => array('address','address','name')
260
+            "attrs"         => array('address', 'address', 'name')
261 261
         );
262 262
         try
263 263
         {
@@ -267,25 +267,25 @@  discard block
 block discarded – undo
267 267
             throw new Exception($e->getMessage());
268 268
         }
269 269
         
270
-        if (property_exists($result,'error') )
270
+        if (property_exists($result, 'error'))
271 271
         {
272
-            if (property_exists($result,'status'))
272
+            if (property_exists($result, 'status'))
273 273
             {
274
-                throw new Exception('Ret code ' .$result->error.' : ' . $result->status);
274
+                throw new Exception('Ret code '.$result->error.' : '.$result->status);
275 275
             }
276 276
             else
277 277
             {
278
-                throw new Exception('Ret code ' .$result->error.' : Unkown status');
278
+                throw new Exception('Ret code '.$result->error.' : Unkown status');
279 279
             }
280 280
         }
281 281
         if (property_exists($result, 'results'))
282 282
         {
283 283
             $numHost=0;
284 284
             $hostArray=array();
285
-            while (isset($result->results[$numHost]) && property_exists ($result->results[$numHost],'attrs'))
285
+            while (isset($result->results[$numHost]) && property_exists($result->results[$numHost], 'attrs'))
286 286
             {
287
-                $hostArray[$numHost] = $result->results[$numHost]->attrs;
288
-                $hostArray[$numHost]->name = $result->results[$numHost]->name;
287
+                $hostArray[$numHost]=$result->results[$numHost]->attrs;
288
+                $hostArray[$numHost]->name=$result->results[$numHost]->name;
289 289
                 $numHost++;
290 290
             }
291 291
             return $hostArray;
@@ -303,23 +303,23 @@  discard block
 block discarded – undo
303 303
      * @return array
304 304
      */
305 305
     public function request($method, $url, $headers, $body) {
306
-        $auth = sprintf('%s:%s', $this->user, $this->pass);
307
-        $curlHeaders = array("Accept: application/json");
306
+        $auth=sprintf('%s:%s', $this->user, $this->pass);
307
+        $curlHeaders=array("Accept: application/json");
308 308
         if ($body !== null) {
309
-            $body = json_encode($body);
309
+            $body=json_encode($body);
310 310
             array_push($curlHeaders, 'Content-Type: application/json');
311 311
             //array_push($curlHeaders, 'X-HTTP-Method-Override: GET');
312 312
         }
313 313
         //var_dump($body);
314 314
         //var_dump($this->url($url));
315 315
         if ($headers !== null) {
316
-            $curlFinalHeaders = array_merge($curlHeaders, $headers);
316
+            $curlFinalHeaders=array_merge($curlHeaders, $headers);
317 317
         } else 
318 318
         {
319 319
             $curlFinalHeaders=$curlHeaders;
320 320
         }
321
-        $curl = $this->curl();
322
-        $opts = array(
321
+        $curl=$this->curl();
322
+        $opts=array(
323 323
             CURLOPT_URL		=> $this->url($url),
324 324
             CURLOPT_HTTPHEADER 	=> $curlFinalHeaders,
325 325
             CURLOPT_USERPWD		=> $auth,
@@ -330,14 +330,14 @@  discard block
 block discarded – undo
330 330
             CURLOPT_SSL_VERIFYPEER 	=> false,
331 331
         );
332 332
         if ($body !== null) {
333
-            $opts[CURLOPT_POSTFIELDS] = $body;
333
+            $opts[CURLOPT_POSTFIELDS]=$body;
334 334
         }
335 335
         curl_setopt_array($curl, $opts);
336
-        $res = curl_exec($curl);
336
+        $res=curl_exec($curl);
337 337
         if ($res === false) {
338
-            throw new Exception('CURL ERROR: ' . curl_error($curl));
338
+            throw new Exception('CURL ERROR: '.curl_error($curl));
339 339
         }
340
-        $statusCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
340
+        $statusCode=curl_getinfo($curl, CURLINFO_HTTP_CODE);
341 341
         if ($statusCode === 401) {
342 342
             throw new Exception('Unable to authenticate, please check your API credentials');
343 343
         }
@@ -351,7 +351,7 @@  discard block
 block discarded – undo
351 351
      * @return array json decoded
352 352
      */
353 353
     protected function fromJsonResult($json) {
354
-        $result = @json_decode($json);
354
+        $result=@json_decode($json);
355 355
         //var_dump($json);
356 356
         if ($result === null) {
357 357
             throw new Exception('Parsing JSON failed: '.$this->getLastJsonErrorMessage(json_last_error()));
Please login to merge, or discard this patch.
Braces   +8 added lines, -11 removed lines patch added patch discarded remove patch
@@ -74,18 +74,19 @@  discard block
 block discarded – undo
74 74
        try
75 75
         {
76 76
             $result=$this->request('GET', "", NULL, NULL);
77
-        } 
78
-        catch (Exception $e)
77
+        } catch (Exception $e)
79 78
         {
80 79
             return array(true, 'Error with API : '.$e->getMessage());
81 80
         }
82 81
         //var_dump($result);
83 82
         $permOk=1;
84 83
         $permMissing='';
85
-        if ($permissions === NULL) // If no permission check return OK after connexion
84
+        if ($permissions === NULL) {
85
+        	// If no permission check return OK after connexion
86 86
         {
87 87
             return array(false,'OK');
88 88
         }
89
+        }
89 90
         if (property_exists($result, 'results') && property_exists($result->results[0], 'permissions'))
90 91
         {
91 92
             
@@ -171,8 +172,7 @@  discard block
 block discarded – undo
171 172
             if (property_exists($result,'status'))
172 173
             {
173 174
                 $message=$result->status;
174
-            }
175
-            else 
175
+            } else 
176 176
             {
177 177
                 $message="Unkown status";
178 178
             }
@@ -183,8 +183,7 @@  discard block
 block discarded – undo
183 183
             if (isset($result->results[0]))
184 184
             {
185 185
                 return array(true,'code '.$result->results[0]->code.' : '.$result->results[0]->status);
186
-            }
187
-            else
186
+            } else
188 187
             {
189 188
                 return array(false,'Service not found');
190 189
             }
@@ -226,8 +225,7 @@  discard block
 block discarded – undo
226 225
             if (property_exists($result,'status'))
227 226
             {
228 227
                 throw new Exception('Ret code ' .$result->error.' : ' . $result->status);
229
-            }
230
-            else
228
+            } else
231 229
             {
232 230
                 throw new Exception('Ret code ' .$result->error.' : Unkown status');
233 231
             }
@@ -272,8 +270,7 @@  discard block
 block discarded – undo
272 270
             if (property_exists($result,'status'))
273 271
             {
274 272
                 throw new Exception('Ret code ' .$result->error.' : ' . $result->status);
275
-            }
276
-            else
273
+            } else
277 274
             {
278 275
                 throw new Exception('Ret code ' .$result->error.' : Unkown status');
279 276
             }
Please login to merge, or discard this patch.
library/Trapdirector/TrapsProcess/TrapConfig.php 3 patches
Indentation   +158 added lines, -158 removed lines patch added patch discarded remove patch
@@ -15,181 +15,181 @@
 block discarded – undo
15 15
 trait TrapConfig
16 16
 {
17 17
 
18
-    /** @return \Trapdirector\Logging   */
19
-    abstract public function getLogging();
20
-    /** @return \Trapdirector\TrapApi   */
21
-    abstract public function getTrapApi();
18
+	/** @return \Trapdirector\Logging   */
19
+	abstract public function getLogging();
20
+	/** @return \Trapdirector\TrapApi   */
21
+	abstract public function getTrapApi();
22 22
     
23
-    /**
24
-     * Get option from array of ini file, send message if empty
25
-     * @param string $option_array Array of ini file
26
-     * @param string $option_category category in ini file
27
-     * @param string $option_name name of option in category
28
-     * @param mixed $option_var variable to fill if found, left untouched if not found
29
-     * @param integer $log_level default 2 (warning)
30
-     * @param string $message warning message if not found
31
-     * @return boolean true if found, or false
32
-     */
33
-    protected function getOptionIfSet($option_array,$option_category,$option_name, &$option_var, $log_level = WARN, $message = null)
34
-    {
35
-        if (!isset($option_array[$option_category][$option_name]))
36
-        {
37
-            if ($message === null)
38
-            {
39
-                $message='No ' . $option_name . ' in config file: '. $this->trapModuleConfig;
40
-            }
41
-            $this->getLogging()->log($message,$log_level);
42
-            return false;
43
-        }
44
-        else
45
-        {
46
-            $option_var=$option_array[$option_category][$option_name];
47
-            return true;
48
-        }
49
-    }
23
+	/**
24
+	 * Get option from array of ini file, send message if empty
25
+	 * @param string $option_array Array of ini file
26
+	 * @param string $option_category category in ini file
27
+	 * @param string $option_name name of option in category
28
+	 * @param mixed $option_var variable to fill if found, left untouched if not found
29
+	 * @param integer $log_level default 2 (warning)
30
+	 * @param string $message warning message if not found
31
+	 * @return boolean true if found, or false
32
+	 */
33
+	protected function getOptionIfSet($option_array,$option_category,$option_name, &$option_var, $log_level = WARN, $message = null)
34
+	{
35
+		if (!isset($option_array[$option_category][$option_name]))
36
+		{
37
+			if ($message === null)
38
+			{
39
+				$message='No ' . $option_name . ' in config file: '. $this->trapModuleConfig;
40
+			}
41
+			$this->getLogging()->log($message,$log_level);
42
+			return false;
43
+		}
44
+		else
45
+		{
46
+			$option_var=$option_array[$option_category][$option_name];
47
+			return true;
48
+		}
49
+	}
50 50
 
51
-    /**
52
-     * Get options in database
53
-     */
54
-    protected function getDatabaseOptions()
55
-    {
56
-        // Database options
57
-        if ($this->logSetup === false) // Only if logging was no setup in constructor
58
-        {
59
-            $this->getDBConfigIfSet('log_level',$this->getLogging()->debugLevel);
60
-            $this->getDBConfigIfSet('log_destination',$this->getLogging()->outputMode);
61
-            $this->getDBConfigIfSet('log_file',$this->getLogging()->outputFile);
62
-        }
63
-    }
51
+	/**
52
+	 * Get options in database
53
+	 */
54
+	protected function getDatabaseOptions()
55
+	{
56
+		// Database options
57
+		if ($this->logSetup === false) // Only if logging was no setup in constructor
58
+		{
59
+			$this->getDBConfigIfSet('log_level',$this->getLogging()->debugLevel);
60
+			$this->getDBConfigIfSet('log_destination',$this->getLogging()->outputMode);
61
+			$this->getDBConfigIfSet('log_file',$this->getLogging()->outputFile);
62
+		}
63
+	}
64 64
         
65
-    /** Set $variable to value if $element found in database config table
66
-     * @param string $element
67
-     * @param string $variable
68
-     */
69
-    protected function getDBConfigIfSet($element,&$variable)
70
-    {
71
-        $value=$this->getDBConfig($element);
72
-        if ($value != null) $variable=$value;
73
-    }
65
+	/** Set $variable to value if $element found in database config table
66
+	 * @param string $element
67
+	 * @param string $variable
68
+	 */
69
+	protected function getDBConfigIfSet($element,&$variable)
70
+	{
71
+		$value=$this->getDBConfig($element);
72
+		if ($value != null) $variable=$value;
73
+	}
74 74
     
75
-    /**
76
-     *   Get data from db_config
77
-     *	@param $element string name of param
78
-     *	@return mixed : value (or null)
79
-     */
80
-    protected function getDBConfig($element)  // TODO : put this in DB class
81
-    {
82
-        $db_conn=$this->trapsDB->db_connect_trap();
83
-        $sql='SELECT value from '.$this->dbPrefix.'db_config WHERE ( name=\''.$element.'\' )';
84
-        if (($ret_code=$db_conn->query($sql)) === false) {
85
-            $this->logging->log('No result in query : ' . $sql,WARN,'');
86
-            return null;
87
-        }
88
-        $value=$ret_code->fetch();
89
-        if ($value != null && isset($value['value']))
90
-        {
91
-            return $value['value'];
92
-        }
93
-        return null;
94
-    }
75
+	/**
76
+	 *   Get data from db_config
77
+	 *	@param $element string name of param
78
+	 *	@return mixed : value (or null)
79
+	 */
80
+	protected function getDBConfig($element)  // TODO : put this in DB class
81
+	{
82
+		$db_conn=$this->trapsDB->db_connect_trap();
83
+		$sql='SELECT value from '.$this->dbPrefix.'db_config WHERE ( name=\''.$element.'\' )';
84
+		if (($ret_code=$db_conn->query($sql)) === false) {
85
+			$this->logging->log('No result in query : ' . $sql,WARN,'');
86
+			return null;
87
+		}
88
+		$value=$ret_code->fetch();
89
+		if ($value != null && isset($value['value']))
90
+		{
91
+			return $value['value'];
92
+		}
93
+		return null;
94
+	}
95 95
     
96
-    /**
97
-     * Get options from ini file
98
-     * @param array $trap_config : ini file array
99
-     */
100
-    protected function getMainOptions($trapConfig)
101
-    {
96
+	/**
97
+	 * Get options from ini file
98
+	 * @param array $trap_config : ini file array
99
+	 */
100
+	protected function getMainOptions($trapConfig)
101
+	{
102 102
         
103
-        $nodeStatus='';
104
-        $this->getOptionIfSet($trapConfig,'config','node', $nodeStatus);
105
-        if ($this->getTrapApi()->setStatus($nodeStatus) === FALSE)
106
-        {
107
-            $this->getLogging()->log('Unknown node status '.$nodeStatus.' : setting to MASTER',WARN);
108
-            $this->getTrapApi()->setStatusMaster();
109
-        }
110
-        else 
111
-        {
112
-            if ($this->getTrapApi()->getStatus() != TrapApi::MASTER)
113
-            {
114
-                // Get options to connect to API
115
-                $IP = $port = $user =  $pass = null;
116
-                $this->getOptionIfSet($trapConfig,'config','masterIP', $IP, ERROR);
117
-                $this->getOptionIfSet($trapConfig,'config','masterPort', $port, ERROR);
118
-                $this->getOptionIfSet($trapConfig,'config','masterUser', $user, ERROR);
119
-                $this->getOptionIfSet($trapConfig,'config','masterPass', $pass, ERROR);
120
-                $this->getTrapApi()->setParams($IP, $port, $user, $pass);
121
-                return;
122
-            }
123
-        }
103
+		$nodeStatus='';
104
+		$this->getOptionIfSet($trapConfig,'config','node', $nodeStatus);
105
+		if ($this->getTrapApi()->setStatus($nodeStatus) === FALSE)
106
+		{
107
+			$this->getLogging()->log('Unknown node status '.$nodeStatus.' : setting to MASTER',WARN);
108
+			$this->getTrapApi()->setStatusMaster();
109
+		}
110
+		else 
111
+		{
112
+			if ($this->getTrapApi()->getStatus() != TrapApi::MASTER)
113
+			{
114
+				// Get options to connect to API
115
+				$IP = $port = $user =  $pass = null;
116
+				$this->getOptionIfSet($trapConfig,'config','masterIP', $IP, ERROR);
117
+				$this->getOptionIfSet($trapConfig,'config','masterPort', $port, ERROR);
118
+				$this->getOptionIfSet($trapConfig,'config','masterUser', $user, ERROR);
119
+				$this->getOptionIfSet($trapConfig,'config','masterPass', $pass, ERROR);
120
+				$this->getTrapApi()->setParams($IP, $port, $user, $pass);
121
+				return;
122
+			}
123
+		}
124 124
         
125
-        // Snmptranslate binary path
126
-        $this->getOptionIfSet($trapConfig,'config','snmptranslate', $this->snmptranslate);
125
+		// Snmptranslate binary path
126
+		$this->getOptionIfSet($trapConfig,'config','snmptranslate', $this->snmptranslate);
127 127
         
128
-        // mibs path
129
-        $this->getOptionIfSet($trapConfig,'config','snmptranslate_dirs', $this->snmptranslate_dirs);
128
+		// mibs path
129
+		$this->getOptionIfSet($trapConfig,'config','snmptranslate_dirs', $this->snmptranslate_dirs);
130 130
         
131
-        // icinga2cmd path
132
-        $this->getOptionIfSet($trapConfig,'config','icingacmd', $this->icinga2cmd);
131
+		// icinga2cmd path
132
+		$this->getOptionIfSet($trapConfig,'config','icingacmd', $this->icinga2cmd);
133 133
         
134
-        // table prefix
135
-        $this->getOptionIfSet($trapConfig,'config','database_prefix', $this->dbPrefix);
134
+		// table prefix
135
+		$this->getOptionIfSet($trapConfig,'config','database_prefix', $this->dbPrefix);
136 136
         
137
-        // API options
138
-        if ($this->getOptionIfSet($trapConfig,'config','icingaAPI_host', $this->apiHostname))
139
-        {
140
-            $this->apiUse=true;
141
-            // Get API options or throw exception as not configured correctly
142
-            $this->getOptionIfSet($trapConfig,'config','icingaAPI_port', $this->apiPort,ERROR);
143
-            $this->getOptionIfSet($trapConfig,'config','icingaAPI_user', $this->apiUsername,ERROR);
144
-            $this->getOptionIfSet($trapConfig,'config','icingaAPI_password', $this->apiPassword,ERROR);
145
-        }
146
-    }
137
+		// API options
138
+		if ($this->getOptionIfSet($trapConfig,'config','icingaAPI_host', $this->apiHostname))
139
+		{
140
+			$this->apiUse=true;
141
+			// Get API options or throw exception as not configured correctly
142
+			$this->getOptionIfSet($trapConfig,'config','icingaAPI_port', $this->apiPort,ERROR);
143
+			$this->getOptionIfSet($trapConfig,'config','icingaAPI_user', $this->apiUsername,ERROR);
144
+			$this->getOptionIfSet($trapConfig,'config','icingaAPI_password', $this->apiPassword,ERROR);
145
+		}
146
+	}
147 147
     
148
-    /**
149
-     * Create and setup database class for trap & ido (if no api) db
150
-     * @param array $trap_config : ini file array
151
-     */
152
-    protected function setupDatabase($trapConfig)
153
-    {
154
-        // Trap database
155
-        if (!array_key_exists('database',$trapConfig['config']))
156
-        {
157
-            $this->logging->log("No database in config file: ".$this->trapModuleConfig,ERROR,'');
158
-            return;
159
-        }
160
-        $dbTrapName=$trapConfig['config']['database'];
161
-        $this->logging->log("Found database in config file: ".$dbTrapName,INFO );
148
+	/**
149
+	 * Create and setup database class for trap & ido (if no api) db
150
+	 * @param array $trap_config : ini file array
151
+	 */
152
+	protected function setupDatabase($trapConfig)
153
+	{
154
+		// Trap database
155
+		if (!array_key_exists('database',$trapConfig['config']))
156
+		{
157
+			$this->logging->log("No database in config file: ".$this->trapModuleConfig,ERROR,'');
158
+			return;
159
+		}
160
+		$dbTrapName=$trapConfig['config']['database'];
161
+		$this->logging->log("Found database in config file: ".$dbTrapName,INFO );
162 162
         
163
-        if ( ($dbConfig=parse_ini_file($this->icingaweb2Ressources,true)) === false)
164
-        {
165
-            $this->logging->log("Error reading ini file : ".$this->icingaweb2Ressources,ERROR,'');
166
-            return;
167
-        }
168
-        if (!array_key_exists($dbTrapName,$dbConfig))
169
-        {
170
-            $this->logging->log("No database '.$dbTrapName.' in config file: ".$this->icingaweb2Ressources,ERROR,'');
171
-            return;
172
-        }
163
+		if ( ($dbConfig=parse_ini_file($this->icingaweb2Ressources,true)) === false)
164
+		{
165
+			$this->logging->log("Error reading ini file : ".$this->icingaweb2Ressources,ERROR,'');
166
+			return;
167
+		}
168
+		if (!array_key_exists($dbTrapName,$dbConfig))
169
+		{
170
+			$this->logging->log("No database '.$dbTrapName.' in config file: ".$this->icingaweb2Ressources,ERROR,'');
171
+			return;
172
+		}
173 173
         
174
-        $this->trapsDB = new Database($this->logging,$dbConfig[$dbTrapName],$this->dbPrefix);
174
+		$this->trapsDB = new Database($this->logging,$dbConfig[$dbTrapName],$this->dbPrefix);
175 175
         
176
-        // TODO enable this again when API queries are all done : if ($this->apiUse === true) return; // In case of API use, no IDO is necessary
176
+		// TODO enable this again when API queries are all done : if ($this->apiUse === true) return; // In case of API use, no IDO is necessary
177 177
         
178
-        // IDO Database
179
-        if (!array_key_exists('IDOdatabase',$trapConfig['config']))
180
-        {
181
-            $this->logging->log("No IDOdatabase in config file: ".$this->trapModuleConfig,ERROR,'');
182
-        }
183
-        $dbIdoName=$trapConfig['config']['IDOdatabase'];
178
+		// IDO Database
179
+		if (!array_key_exists('IDOdatabase',$trapConfig['config']))
180
+		{
181
+			$this->logging->log("No IDOdatabase in config file: ".$this->trapModuleConfig,ERROR,'');
182
+		}
183
+		$dbIdoName=$trapConfig['config']['IDOdatabase'];
184 184
         
185
-        $this->logging->log("Found IDO database in config file: ".$dbIdoName,INFO );
186
-        if (!array_key_exists($dbIdoName,$dbConfig))
187
-        {
188
-            $this->logging->log("No database '.$dbIdoName.' in config file: ".$this->icingaweb2Ressources,ERROR,'');
189
-            return;
190
-        }
185
+		$this->logging->log("Found IDO database in config file: ".$dbIdoName,INFO );
186
+		if (!array_key_exists($dbIdoName,$dbConfig))
187
+		{
188
+			$this->logging->log("No database '.$dbIdoName.' in config file: ".$this->icingaweb2Ressources,ERROR,'');
189
+			return;
190
+		}
191 191
         
192
-        $this->trapsDB->setupIDO($dbConfig[$dbIdoName]);
193
-    }
192
+		$this->trapsDB->setupIDO($dbConfig[$dbIdoName]);
193
+	}
194 194
     
195 195
 }
Please login to merge, or discard this patch.
Spacing   +36 added lines, -36 removed lines patch added patch discarded remove patch
@@ -30,15 +30,15 @@  discard block
 block discarded – undo
30 30
      * @param string $message warning message if not found
31 31
      * @return boolean true if found, or false
32 32
      */
33
-    protected function getOptionIfSet($option_array,$option_category,$option_name, &$option_var, $log_level = WARN, $message = null)
33
+    protected function getOptionIfSet($option_array, $option_category, $option_name, &$option_var, $log_level=WARN, $message=null)
34 34
     {
35 35
         if (!isset($option_array[$option_category][$option_name]))
36 36
         {
37 37
             if ($message === null)
38 38
             {
39
-                $message='No ' . $option_name . ' in config file: '. $this->trapModuleConfig;
39
+                $message='No '.$option_name.' in config file: '.$this->trapModuleConfig;
40 40
             }
41
-            $this->getLogging()->log($message,$log_level);
41
+            $this->getLogging()->log($message, $log_level);
42 42
             return false;
43 43
         }
44 44
         else
@@ -56,9 +56,9 @@  discard block
 block discarded – undo
56 56
         // Database options
57 57
         if ($this->logSetup === false) // Only if logging was no setup in constructor
58 58
         {
59
-            $this->getDBConfigIfSet('log_level',$this->getLogging()->debugLevel);
60
-            $this->getDBConfigIfSet('log_destination',$this->getLogging()->outputMode);
61
-            $this->getDBConfigIfSet('log_file',$this->getLogging()->outputFile);
59
+            $this->getDBConfigIfSet('log_level', $this->getLogging()->debugLevel);
60
+            $this->getDBConfigIfSet('log_destination', $this->getLogging()->outputMode);
61
+            $this->getDBConfigIfSet('log_file', $this->getLogging()->outputFile);
62 62
         }
63 63
     }
64 64
         
@@ -66,7 +66,7 @@  discard block
 block discarded – undo
66 66
      * @param string $element
67 67
      * @param string $variable
68 68
      */
69
-    protected function getDBConfigIfSet($element,&$variable)
69
+    protected function getDBConfigIfSet($element, &$variable)
70 70
     {
71 71
         $value=$this->getDBConfig($element);
72 72
         if ($value != null) $variable=$value;
@@ -82,7 +82,7 @@  discard block
 block discarded – undo
82 82
         $db_conn=$this->trapsDB->db_connect_trap();
83 83
         $sql='SELECT value from '.$this->dbPrefix.'db_config WHERE ( name=\''.$element.'\' )';
84 84
         if (($ret_code=$db_conn->query($sql)) === false) {
85
-            $this->logging->log('No result in query : ' . $sql,WARN,'');
85
+            $this->logging->log('No result in query : '.$sql, WARN, '');
86 86
             return null;
87 87
         }
88 88
         $value=$ret_code->fetch();
@@ -101,10 +101,10 @@  discard block
 block discarded – undo
101 101
     {
102 102
         
103 103
         $nodeStatus='';
104
-        $this->getOptionIfSet($trapConfig,'config','node', $nodeStatus);
104
+        $this->getOptionIfSet($trapConfig, 'config', 'node', $nodeStatus);
105 105
         if ($this->getTrapApi()->setStatus($nodeStatus) === FALSE)
106 106
         {
107
-            $this->getLogging()->log('Unknown node status '.$nodeStatus.' : setting to MASTER',WARN);
107
+            $this->getLogging()->log('Unknown node status '.$nodeStatus.' : setting to MASTER', WARN);
108 108
             $this->getTrapApi()->setStatusMaster();
109 109
         }
110 110
         else 
@@ -112,36 +112,36 @@  discard block
 block discarded – undo
112 112
             if ($this->getTrapApi()->getStatus() != TrapApi::MASTER)
113 113
             {
114 114
                 // Get options to connect to API
115
-                $IP = $port = $user =  $pass = null;
116
-                $this->getOptionIfSet($trapConfig,'config','masterIP', $IP, ERROR);
117
-                $this->getOptionIfSet($trapConfig,'config','masterPort', $port, ERROR);
118
-                $this->getOptionIfSet($trapConfig,'config','masterUser', $user, ERROR);
119
-                $this->getOptionIfSet($trapConfig,'config','masterPass', $pass, ERROR);
115
+                $IP=$port=$user=$pass=null;
116
+                $this->getOptionIfSet($trapConfig, 'config', 'masterIP', $IP, ERROR);
117
+                $this->getOptionIfSet($trapConfig, 'config', 'masterPort', $port, ERROR);
118
+                $this->getOptionIfSet($trapConfig, 'config', 'masterUser', $user, ERROR);
119
+                $this->getOptionIfSet($trapConfig, 'config', 'masterPass', $pass, ERROR);
120 120
                 $this->getTrapApi()->setParams($IP, $port, $user, $pass);
121 121
                 return;
122 122
             }
123 123
         }
124 124
         
125 125
         // Snmptranslate binary path
126
-        $this->getOptionIfSet($trapConfig,'config','snmptranslate', $this->snmptranslate);
126
+        $this->getOptionIfSet($trapConfig, 'config', 'snmptranslate', $this->snmptranslate);
127 127
         
128 128
         // mibs path
129
-        $this->getOptionIfSet($trapConfig,'config','snmptranslate_dirs', $this->snmptranslate_dirs);
129
+        $this->getOptionIfSet($trapConfig, 'config', 'snmptranslate_dirs', $this->snmptranslate_dirs);
130 130
         
131 131
         // icinga2cmd path
132
-        $this->getOptionIfSet($trapConfig,'config','icingacmd', $this->icinga2cmd);
132
+        $this->getOptionIfSet($trapConfig, 'config', 'icingacmd', $this->icinga2cmd);
133 133
         
134 134
         // table prefix
135
-        $this->getOptionIfSet($trapConfig,'config','database_prefix', $this->dbPrefix);
135
+        $this->getOptionIfSet($trapConfig, 'config', 'database_prefix', $this->dbPrefix);
136 136
         
137 137
         // API options
138
-        if ($this->getOptionIfSet($trapConfig,'config','icingaAPI_host', $this->apiHostname))
138
+        if ($this->getOptionIfSet($trapConfig, 'config', 'icingaAPI_host', $this->apiHostname))
139 139
         {
140 140
             $this->apiUse=true;
141 141
             // Get API options or throw exception as not configured correctly
142
-            $this->getOptionIfSet($trapConfig,'config','icingaAPI_port', $this->apiPort,ERROR);
143
-            $this->getOptionIfSet($trapConfig,'config','icingaAPI_user', $this->apiUsername,ERROR);
144
-            $this->getOptionIfSet($trapConfig,'config','icingaAPI_password', $this->apiPassword,ERROR);
142
+            $this->getOptionIfSet($trapConfig, 'config', 'icingaAPI_port', $this->apiPort, ERROR);
143
+            $this->getOptionIfSet($trapConfig, 'config', 'icingaAPI_user', $this->apiUsername, ERROR);
144
+            $this->getOptionIfSet($trapConfig, 'config', 'icingaAPI_password', $this->apiPassword, ERROR);
145 145
         }
146 146
     }
147 147
     
@@ -152,40 +152,40 @@  discard block
 block discarded – undo
152 152
     protected function setupDatabase($trapConfig)
153 153
     {
154 154
         // Trap database
155
-        if (!array_key_exists('database',$trapConfig['config']))
155
+        if (!array_key_exists('database', $trapConfig['config']))
156 156
         {
157
-            $this->logging->log("No database in config file: ".$this->trapModuleConfig,ERROR,'');
157
+            $this->logging->log("No database in config file: ".$this->trapModuleConfig, ERROR, '');
158 158
             return;
159 159
         }
160 160
         $dbTrapName=$trapConfig['config']['database'];
161
-        $this->logging->log("Found database in config file: ".$dbTrapName,INFO );
161
+        $this->logging->log("Found database in config file: ".$dbTrapName, INFO);
162 162
         
163
-        if ( ($dbConfig=parse_ini_file($this->icingaweb2Ressources,true)) === false)
163
+        if (($dbConfig=parse_ini_file($this->icingaweb2Ressources, true)) === false)
164 164
         {
165
-            $this->logging->log("Error reading ini file : ".$this->icingaweb2Ressources,ERROR,'');
165
+            $this->logging->log("Error reading ini file : ".$this->icingaweb2Ressources, ERROR, '');
166 166
             return;
167 167
         }
168
-        if (!array_key_exists($dbTrapName,$dbConfig))
168
+        if (!array_key_exists($dbTrapName, $dbConfig))
169 169
         {
170
-            $this->logging->log("No database '.$dbTrapName.' in config file: ".$this->icingaweb2Ressources,ERROR,'');
170
+            $this->logging->log("No database '.$dbTrapName.' in config file: ".$this->icingaweb2Ressources, ERROR, '');
171 171
             return;
172 172
         }
173 173
         
174
-        $this->trapsDB = new Database($this->logging,$dbConfig[$dbTrapName],$this->dbPrefix);
174
+        $this->trapsDB=new Database($this->logging, $dbConfig[$dbTrapName], $this->dbPrefix);
175 175
         
176 176
         // TODO enable this again when API queries are all done : if ($this->apiUse === true) return; // In case of API use, no IDO is necessary
177 177
         
178 178
         // IDO Database
179
-        if (!array_key_exists('IDOdatabase',$trapConfig['config']))
179
+        if (!array_key_exists('IDOdatabase', $trapConfig['config']))
180 180
         {
181
-            $this->logging->log("No IDOdatabase in config file: ".$this->trapModuleConfig,ERROR,'');
181
+            $this->logging->log("No IDOdatabase in config file: ".$this->trapModuleConfig, ERROR, '');
182 182
         }
183 183
         $dbIdoName=$trapConfig['config']['IDOdatabase'];
184 184
         
185
-        $this->logging->log("Found IDO database in config file: ".$dbIdoName,INFO );
186
-        if (!array_key_exists($dbIdoName,$dbConfig))
185
+        $this->logging->log("Found IDO database in config file: ".$dbIdoName, INFO);
186
+        if (!array_key_exists($dbIdoName, $dbConfig))
187 187
         {
188
-            $this->logging->log("No database '.$dbIdoName.' in config file: ".$this->icingaweb2Ressources,ERROR,'');
188
+            $this->logging->log("No database '.$dbIdoName.' in config file: ".$this->icingaweb2Ressources, ERROR, '');
189 189
             return;
190 190
         }
191 191
         
Please login to merge, or discard this patch.
Braces   +8 added lines, -6 removed lines patch added patch discarded remove patch
@@ -40,8 +40,7 @@  discard block
 block discarded – undo
40 40
             }
41 41
             $this->getLogging()->log($message,$log_level);
42 42
             return false;
43
-        }
44
-        else
43
+        } else
45 44
         {
46 45
             $option_var=$option_array[$option_category][$option_name];
47 46
             return true;
@@ -54,9 +53,11 @@  discard block
 block discarded – undo
54 53
     protected function getDatabaseOptions()
55 54
     {
56 55
         // Database options
57
-        if ($this->logSetup === false) // Only if logging was no setup in constructor
56
+        if ($this->logSetup === false) {
57
+        	// Only if logging was no setup in constructor
58 58
         {
59 59
             $this->getDBConfigIfSet('log_level',$this->getLogging()->debugLevel);
60
+        }
60 61
             $this->getDBConfigIfSet('log_destination',$this->getLogging()->outputMode);
61 62
             $this->getDBConfigIfSet('log_file',$this->getLogging()->outputFile);
62 63
         }
@@ -69,7 +70,9 @@  discard block
 block discarded – undo
69 70
     protected function getDBConfigIfSet($element,&$variable)
70 71
     {
71 72
         $value=$this->getDBConfig($element);
72
-        if ($value != null) $variable=$value;
73
+        if ($value != null) {
74
+        	$variable=$value;
75
+        }
73 76
     }
74 77
     
75 78
     /**
@@ -106,8 +109,7 @@  discard block
 block discarded – undo
106 109
         {
107 110
             $this->getLogging()->log('Unknown node status '.$nodeStatus.' : setting to MASTER',WARN);
108 111
             $this->getTrapApi()->setStatusMaster();
109
-        }
110
-        else 
112
+        } else 
111 113
         {
112 114
             if ($this->getTrapApi()->getStatus() != TrapApi::MASTER)
113 115
             {
Please login to merge, or discard this patch.