Passed
Push — master ( 27233f...bd4945 )
by Patrick
02:03
created
application/controllers/SettingsController.php 1 patch
Indentation   +100 added lines, -100 removed lines patch added patch discarded remove patch
@@ -22,37 +22,37 @@  discard block
 block discarded – undo
22 22
   public function indexAction()
23 23
   {
24 24
       
25
-    // CHeck permissions : display tests in any case, but no configuration.
25
+	// CHeck permissions : display tests in any case, but no configuration.
26 26
 	$this->view->configPermission=$this->checkModuleConfigPermission(1);
27 27
 	// But check read permission
28 28
 	$this->checkReadPermission();
29 29
 	// Get message : sent on configuration problems detected by controllers
30 30
 	$dberrorMsg=$this->params->get('dberror');
31 31
 	if ($dberrorMsg != '')
32
-	    $this->view->errorDetected=$dberrorMsg;
33
-    $dberrorMsg=$this->params->get('idodberror');
34
-    if ($dberrorMsg != '')
35
-        $this->view->errorDetected=$dberrorMsg;
32
+		$this->view->errorDetected=$dberrorMsg;
33
+	$dberrorMsg=$this->params->get('idodberror');
34
+	if ($dberrorMsg != '')
35
+		$this->view->errorDetected=$dberrorMsg;
36 36
     
37
-    $this->view->configErrorDetected == NULL; // Displayed error on various conifugration errors.
37
+	$this->view->configErrorDetected == NULL; // Displayed error on various conifugration errors.
38 38
     
39
-    // Test if configuration exists, if not create for installer script
39
+	// Test if configuration exists, if not create for installer script
40 40
 	//$emptyConfig=0;
41
-    if ($this->Config()->isEmpty() == true)
42
-    {
43
-        $this->Config()->setSection('config'); // Set base config section.
44
-        try 
45
-        { 
46
-            $this->Config()->saveIni();
47
-            $this->view->configErrorDetected='Configuration is empty : you can run install script with parameters (see Automatic installation below)';
41
+	if ($this->Config()->isEmpty() == true)
42
+	{
43
+		$this->Config()->setSection('config'); // Set base config section.
44
+		try 
45
+		{ 
46
+			$this->Config()->saveIni();
47
+			$this->view->configErrorDetected='Configuration is empty : you can run install script with parameters (see Automatic installation below)';
48 48
 			//$emptyConfig=1;
49
-        }
50
-        catch (Exception $e)
51
-        {
52
-            $this->view->configErrorDetected=$e->getMessage();
53
-        }
49
+		}
50
+		catch (Exception $e)
51
+		{
52
+			$this->view->configErrorDetected=$e->getMessage();
53
+		}
54 54
         
55
-    }
55
+	}
56 56
 	// Test Database
57 57
 	$db_message=array( // index => ( message OK, message NOK, optional link if NOK ) 
58 58
 		0	=>	array('Database configuration OK','',''),
@@ -97,20 +97,20 @@  discard block
 block discarded – undo
97 97
 	//********* Test API
98 98
 	if ($this->Config()->get('config', 'icingaAPI_host') != '')
99 99
 	{
100
-	    $apitest=new Icinga2Api($this->Config()->get('config', 'icingaAPI_host'),$this->Config()->get('config', 'icingaAPI_port'));
101
-    	$apitest->setCredentials($this->Config()->get('config', 'icingaAPI_user'), $this->Config()->get('config', 'icingaAPI_password'));
102
-    	try {
103
-    	    list($this->view->apimessageError,$this->view->apimessage)=$apitest->test($this->getModuleConfig()::getapiUserPermissions());
104
-    	    //$this->view->apimessageError=false;
105
-    	} catch (RuntimeException $e) {
106
-    	    $this->view->apimessage='API config : ' . $e->getMessage();
107
-    	    $this->view->apimessageError=true;
108
-    	} 
100
+		$apitest=new Icinga2Api($this->Config()->get('config', 'icingaAPI_host'),$this->Config()->get('config', 'icingaAPI_port'));
101
+		$apitest->setCredentials($this->Config()->get('config', 'icingaAPI_user'), $this->Config()->get('config', 'icingaAPI_password'));
102
+		try {
103
+			list($this->view->apimessageError,$this->view->apimessage)=$apitest->test($this->getModuleConfig()::getapiUserPermissions());
104
+			//$this->view->apimessageError=false;
105
+		} catch (RuntimeException $e) {
106
+			$this->view->apimessage='API config : ' . $e->getMessage();
107
+			$this->view->apimessageError=true;
108
+		} 
109 109
 	}
110 110
 	else
111 111
 	{
112
-	    $this->view->apimessage='API parameters not configured';
113
-	    $this->view->apimessageError=true;
112
+		$this->view->apimessage='API parameters not configured';
113
+		$this->view->apimessageError=true;
114 114
 	}
115 115
 	
116 116
 	//*********** Test snmptrapd alive and options
@@ -125,33 +125,33 @@  discard block
 block discarded – undo
125 125
 		}
126 126
 	}
127 127
 
128
-    $this->view->tabs = $this->Module()->getConfigTabs()->activate('config');
128
+	$this->view->tabs = $this->Module()->getConfigTabs()->activate('config');
129 129
 
130 130
 	// Check standard Icingaweb2 path
131 131
 	$this->view->icingaEtcWarn=0;
132 132
 	$icingaweb2_etc=$this->Config()->get('config', 'icingaweb2_etc');
133 133
 	if ($icingaweb2_etc != "/etc/icingaweb2/" && $icingaweb2_etc != '')
134 134
 	{
135
-	    $output=array();
135
+		$output=array();
136 136
 	    
137
-	    exec('cat ' . $this->module->getBaseDir() .'/bin/trap_in.php | grep "\$icingaweb2_etc=" ',$output);
137
+		exec('cat ' . $this->module->getBaseDir() .'/bin/trap_in.php | grep "\$icingaweb2_etc=" ',$output);
138 138
 	    
139
-	    if (! preg_match('#"'. $icingaweb2_etc .'"#',$output[0]))
140
-	    {
141
-    	    $this->view->icingaEtcWarn=1;
142
-	        $this->view->icingaweb2_etc=$icingaweb2_etc;
143
-	    }
139
+		if (! preg_match('#"'. $icingaweb2_etc .'"#',$output[0]))
140
+		{
141
+			$this->view->icingaEtcWarn=1;
142
+			$this->view->icingaweb2_etc=$icingaweb2_etc;
143
+		}
144 144
 	}
145 145
 
146 146
 	// Setup path for mini documentation
147 147
 	$this->view->traps_in_config= PHP_BINARY . ' ' . $this->Module()->getBaseDir() . '/bin/trap_in.php';
148 148
 	
149 149
 	$this->view->installer= $this->Module()->getBaseDir() . '/bin/installer.sh '
150
-	    . ' -c all ' 
151
-	    . ' -d ' . $this->Module()->getBaseDir()
152
-	    . ' -p ' . PHP_BINARY
153
-	    . ' -a ' . exec('whoami')
154
-	    . ' -w ' . Icinga::app()->getConfigDir();
150
+		. ' -c all ' 
151
+		. ' -d ' . $this->Module()->getBaseDir()
152
+		. ' -p ' . PHP_BINARY
153
+		. ' -a ' . exec('whoami')
154
+		. ' -w ' . Icinga::app()->getConfigDir();
155 155
 	        
156 156
 	// ******************* configuration form setup*******************
157 157
 	$this->view->form = $form = new TrapsConfigForm();
@@ -196,19 +196,19 @@  discard block
 block discarded – undo
196 196
 		  $dbResource = ResourceFactory::getResourceConfig($dbName);
197 197
 		  $dbType=$dbResource->get('db');
198 198
 		  switch ($dbType) {
199
-		      case 'mysql':
200
-		          $dbFileExt='sql';
201
-		          break;
202
-		      case 'pgsql':
203
-		          $dbFileExt='pgsql';
204
-		          break;
205
-		      default:
206
-		          throw new ConfigurationError('Unsuported database : '.$dbType);
199
+			  case 'mysql':
200
+				  $dbFileExt='sql';
201
+				  break;
202
+			  case 'pgsql':
203
+				  $dbFileExt='pgsql';
204
+				  break;
205
+			  default:
206
+				  throw new ConfigurationError('Unsuported database : '.$dbType);
207 207
 		  }
208 208
 		} catch (ConfigurationError $e )
209 209
 		{
210
-		    printf("Database configuration error : %s",$e->getMessage());
211
-		    return;
210
+			printf("Database configuration error : %s",$e->getMessage());
211
+			return;
212 212
 		}
213 213
 		printf('<pre>');
214 214
 		require_once $this->Module()->getBaseDir() .'/bin/trap_class.php';
@@ -232,11 +232,11 @@  discard block
 block discarded – undo
232 232
   public function updateschemaAction()
233 233
   {
234 234
 	  $this->checkModuleConfigPermission();
235
-    	$this->getTabs()->add('get',array(
236
-    		'active'	=> true,
237
-    		'label'		=> $this->translate('Update Schema'),
238
-    		'url'		=> Url::fromRequest()
239
-    	));
235
+		$this->getTabs()->add('get',array(
236
+			'active'	=> true,
237
+			'label'		=> $this->translate('Update Schema'),
238
+			'url'		=> Url::fromRequest()
239
+		));
240 240
 	  // check if needed
241 241
 	  
242 242
 	  $dberror=$this->getDb(true); // Get DB in test mode
@@ -245,15 +245,15 @@  discard block
 block discarded – undo
245 245
 	  
246 246
 	  if ($dberror[0] == 0)
247 247
 	  {
248
-	      echo 'Schema already exists and is up to date<br>';
249
-	      return;
248
+		  echo 'Schema already exists and is up to date<br>';
249
+		  return;
250 250
 	  }
251 251
 	  if ($dberror[0] != 5)
252 252
 	  {
253
-	      echo 'Database does not exists or is not setup correctly<br>';
254
-	      return;
253
+		  echo 'Database does not exists or is not setup correctly<br>';
254
+		  return;
255 255
 	  }
256
-      // setup
256
+	  // setup
257 257
 	  require_once($this->Module()->getBaseDir() .'/bin/trap_class.php');
258 258
 	  $icingaweb2_etc=$this->Config()->get('config', 'icingaweb2_etc');
259 259
 	  $debug_level=4;
@@ -266,20 +266,20 @@  discard block
 block discarded – undo
266 266
 	  $target_version=$dberror[2];
267 267
 	  
268 268
 	  if ($this->params->get('msgok') == null) {
269
-	      // Check for messages and display if any
270
-              echo "Upgrade databse is going to start.<br>Don't forget to backup your database before update<br>";
271
-	      $Trap->setLogging(2,'syslog');
272
-	      $message = $Trap->mibClass->update_schema($updateSchema,$target_version,$prefix,true);
273
-	      if ($message != '')
274
-	      {
275
-	          echo 'Note :<br><pre>';
276
-	          echo $message;
277
-	          echo '</pre>';
278
-	          echo '<br>';
279
-	          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>';
280
-	          echo '<br>';
281
-	          return;
282
-	      }
269
+		  // Check for messages and display if any
270
+			  echo "Upgrade databse is going to start.<br>Don't forget to backup your database before update<br>";
271
+		  $Trap->setLogging(2,'syslog');
272
+		  $message = $Trap->mibClass->update_schema($updateSchema,$target_version,$prefix,true);
273
+		  if ($message != '')
274
+		  {
275
+			  echo 'Note :<br><pre>';
276
+			  echo $message;
277
+			  echo '</pre>';
278
+			  echo '<br>';
279
+			  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>';
280
+			  echo '<br>';
281
+			  return;
282
+		  }
283 283
 	  }
284 284
 	  
285 285
 	  $Trap->setLogging($debug_level,'display');
@@ -293,28 +293,28 @@  discard block
 block discarded – undo
293 293
 
294 294
   private function checkSnmpTrapd()
295 295
   {
296
-      $psOutput=array();
297
-      // First check is someone is listening to port 162. As not root, we can't have pid... 
298
-      exec('netstat -an |grep -E "udp.*:162"',$psOutput);
299
-      if (count($psOutput) == 0)
300
-      {
301
-          return array(1,'Port UDP/162 is not open : snmptrapd must not be started');
302
-      }
303
-      $psOutput=array();
304
-      exec('ps fax |grep snmptrapd |grep -v grep',$psOutput);
305
-      if (count($psOutput) == 0)
306
-      {
307
-          return array(1,"UDP/162 : OK, but no snmptrapd process (?)");
308
-      }
309
-      // Assume there is only one line... TODO : see if there is a better way to do this
310
-      $line = preg_replace('/^.*snmptrapd /','',$psOutput[0]);
311
-      if (!preg_match('/-n/',$line))
312
-          return array(1,'snmptrapd has no -n option : '.$line);
313
-      if (!preg_match('/-O[^ ]*n/',$line))
314
-          return array(1,'snmptrapd has no -On option : '.$line);
315
-      if (!preg_match('/-O[^ ]*e/',$line))
316
-          return array(1,'snmptrapd has no -Oe option : '.$line);
296
+	  $psOutput=array();
297
+	  // First check is someone is listening to port 162. As not root, we can't have pid... 
298
+	  exec('netstat -an |grep -E "udp.*:162"',$psOutput);
299
+	  if (count($psOutput) == 0)
300
+	  {
301
+		  return array(1,'Port UDP/162 is not open : snmptrapd must not be started');
302
+	  }
303
+	  $psOutput=array();
304
+	  exec('ps fax |grep snmptrapd |grep -v grep',$psOutput);
305
+	  if (count($psOutput) == 0)
306
+	  {
307
+		  return array(1,"UDP/162 : OK, but no snmptrapd process (?)");
308
+	  }
309
+	  // Assume there is only one line... TODO : see if there is a better way to do this
310
+	  $line = preg_replace('/^.*snmptrapd /','',$psOutput[0]);
311
+	  if (!preg_match('/-n/',$line))
312
+		  return array(1,'snmptrapd has no -n option : '.$line);
313
+	  if (!preg_match('/-O[^ ]*n/',$line))
314
+		  return array(1,'snmptrapd has no -On option : '.$line);
315
+	  if (!preg_match('/-O[^ ]*e/',$line))
316
+		  return array(1,'snmptrapd has no -Oe option : '.$line);
317 317
       
318
-      return array(0,'snmptrapd listening to UDP/162, options : '.$line);
318
+	  return array(0,'snmptrapd listening to UDP/162, options : '.$line);
319 319
   }
320 320
 }
Please login to merge, or discard this patch.
bin/trap_in.php 1 patch
Indentation   +14 added lines, -14 removed lines patch added patch discarded remove patch
@@ -15,13 +15,13 @@  discard block
 block discarded – undo
15 15
 
16 16
 try
17 17
 {
18
-    //$Trap = new Trap($icingaweb2_etc);
19
-    //$Trap = new Trap($icingaweb2_etc,4,'display'); // For debug
20
-    $Trap = new Trap($icingaweb2_etc,4,'syslog'); // For debug
21
-    //$Trap->setLogging(4,'syslog'); 
18
+	//$Trap = new Trap($icingaweb2_etc);
19
+	//$Trap = new Trap($icingaweb2_etc,4,'display'); // For debug
20
+	$Trap = new Trap($icingaweb2_etc,4,'syslog'); // For debug
21
+	//$Trap->setLogging(4,'syslog'); 
22 22
     
23
-    // TODO : tranfer this to reset_trap cli command
24
-    $Trap->eraseOldTraps();
23
+	// TODO : tranfer this to reset_trap cli command
24
+	$Trap->eraseOldTraps();
25 25
 
26 26
 	$Trap->read_trap('php://stdin');
27 27
 
@@ -34,15 +34,15 @@  discard block
 block discarded – undo
34 34
 }
35 35
 catch (Exception $e) 
36 36
 {
37
-    if ($Trap == null)
38
-    {  // Exception in trap creation : log in display & syslog
39
-        $logging = new Logging();
40
-        $logging->log("Caught exception creating Trap class",2);
41
-    }
42
-    else
43
-    {
37
+	if ($Trap == null)
38
+	{  // Exception in trap creation : log in display & syslog
39
+		$logging = new Logging();
40
+		$logging->log("Caught exception creating Trap class",2);
41
+	}
42
+	else
43
+	{
44 44
 	   $Trap->trapLog("Exception : ". $e->getMessage(),2,0);
45
-    }
45
+	}
46 46
 }
47 47
 
48 48
 //end
Please login to merge, or discard this patch.
bin/trap_class.php 1 patch
Indentation   +479 added lines, -479 removed lines patch added patch discarded remove patch
@@ -57,7 +57,7 @@  discard block
 block discarded – undo
57 57
 	
58 58
 	function __construct($etc_dir='/etc/icingaweb2',$baseLogLevel=null,$baseLogMode='syslog',$baseLogFile='')
59 59
 	{
60
-	    // Paths of ini files
60
+		// Paths of ini files
61 61
 		$this->icingaweb2_etc=$etc_dir;
62 62
 		$this->trap_module_config=$this->icingaweb2_etc."/modules/trapdirector/config.ini";		
63 63
 		$this->icingaweb2_ressources=$this->icingaweb2_etc."/resources.ini";
@@ -66,18 +66,18 @@  discard block
 block discarded – undo
66 66
 		$this->logging = new Logging();
67 67
 		if ($baseLogLevel != null)
68 68
 		{
69
-		    $this->logging->setLogging($baseLogLevel, $baseLogMode,$baseLogFile);
70
-		    $this->logSetup=true;
69
+			$this->logging->setLogging($baseLogLevel, $baseLogMode,$baseLogFile);
70
+			$this->logSetup=true;
71 71
 		}
72 72
 		else 
73
-		    $this->logSetup=false;
73
+			$this->logSetup=false;
74 74
 		$this->logging->log('Loggin started', INFO);
75 75
 
76 76
 		// Get options from ini files
77 77
 		$trapConfig=parse_ini_file($this->trap_module_config,true);
78 78
 		if ($trapConfig == false)
79 79
 		{
80
-		    $this->logging->log("Error reading ini file : ".$this->trap_module_config,ERROR,'syslog');
80
+			$this->logging->log("Error reading ini file : ".$this->trap_module_config,ERROR,'syslog');
81 81
 		}
82 82
 		$this->getMainOptions($trapConfig); // Get main options from ini file
83 83
 		$this->setupDatabase($trapConfig); // Setup database class
@@ -109,26 +109,26 @@  discard block
 block discarded – undo
109 109
 	 */
110 110
 	protected function getOptionIfSet($option_array,$option_category,$option_name, &$option_var, $log_level = 2, $message = null)
111 111
 	{
112
-	    if (!isset($option_array[$option_category][$option_name]))
113
-	    {
114
-	        if ($message === null)
115
-	        {
116
-	            $message='No ' . $option_name . ' in config file: '. $this->trap_module_config;
117
-	        }
118
-	        $this->logging->log($message,$log_level,'syslog');
119
-	        return false;
120
-	    }
121
-	    else
122
-	    {
123
-	        $option_var=$option_array[$option_category][$option_name];
124
-	        return true;
125
-	    }
112
+		if (!isset($option_array[$option_category][$option_name]))
113
+		{
114
+			if ($message === null)
115
+			{
116
+				$message='No ' . $option_name . ' in config file: '. $this->trap_module_config;
117
+			}
118
+			$this->logging->log($message,$log_level,'syslog');
119
+			return false;
120
+		}
121
+		else
122
+		{
123
+			$option_var=$option_array[$option_category][$option_name];
124
+			return true;
125
+		}
126 126
 	}
127 127
 	
128 128
 	/** 
129 129
 	 * Get options from ini file
130 130
 	 * @param array $trap_config : ini file array
131
-	*/
131
+	 */
132 132
 	protected function getMainOptions($trapConfig)
133 133
 	{
134 134
 
@@ -147,10 +147,10 @@  discard block
 block discarded – undo
147 147
 		// API options
148 148
 		if ($this->getOptionIfSet($trapConfig,'config','icingaAPI_host', $this->api_hostname))
149 149
 		{
150
-		    $this->api_use=true;
151
-		    $this->getOptionIfSet($trapConfig,'config','icingaAPI_port', $this->api_port);
152
-		    $this->getOptionIfSet($trapConfig,'config','icingaAPI_user', $this->api_username);
153
-		    $this->getOptionIfSet($trapConfig,'config','icingaAPI_password', $this->api_password);
150
+			$this->api_use=true;
151
+			$this->getOptionIfSet($trapConfig,'config','icingaAPI_port', $this->api_port);
152
+			$this->getOptionIfSet($trapConfig,'config','icingaAPI_user', $this->api_username);
153
+			$this->getOptionIfSet($trapConfig,'config','icingaAPI_password', $this->api_password);
154 154
 		}
155 155
 	}
156 156
 	
@@ -160,45 +160,45 @@  discard block
 block discarded – undo
160 160
 	 */
161 161
 	protected function setupDatabase($trapConfig)
162 162
 	{
163
-	    // Trap database
164
-	    if (!array_key_exists('database',$trapConfig['config']))
165
-        {
166
-            $this->logging->log("No database in config file: ".$this->trap_module_config,ERROR,'');
167
-            return;
168
-        }
169
-        $dbTrapName=$trapConfig['config']['database'];
170
-        $this->logging->log("Found database in config file: ".$dbTrapName,INFO );
163
+		// Trap database
164
+		if (!array_key_exists('database',$trapConfig['config']))
165
+		{
166
+			$this->logging->log("No database in config file: ".$this->trap_module_config,ERROR,'');
167
+			return;
168
+		}
169
+		$dbTrapName=$trapConfig['config']['database'];
170
+		$this->logging->log("Found database in config file: ".$dbTrapName,INFO );
171 171
 	    
172 172
 	   if ( ($dbConfig=parse_ini_file($this->icingaweb2_ressources,true)) === false)
173
-	    {
174
-	        $this->logging->log("Error reading ini file : ".$this->icingaweb2_ressources,ERROR,'');
175
-	        return;
176
-	    }
177
-	    if (!array_key_exists($dbTrapName,$dbConfig))
178
-	    {
179
-	        $this->logging->log("No database '.$dbTrapName.' in config file: ".$this->icingaweb2_ressources,ERROR,'');
180
-	        return;
181
-	    }
173
+		{
174
+			$this->logging->log("Error reading ini file : ".$this->icingaweb2_ressources,ERROR,'');
175
+			return;
176
+		}
177
+		if (!array_key_exists($dbTrapName,$dbConfig))
178
+		{
179
+			$this->logging->log("No database '.$dbTrapName.' in config file: ".$this->icingaweb2_ressources,ERROR,'');
180
+			return;
181
+		}
182 182
 	    
183
-        $this->trapsDB = new Database($this->logging,$dbConfig[$dbTrapName]);
183
+		$this->trapsDB = new Database($this->logging,$dbConfig[$dbTrapName]);
184 184
 	    
185
-	    if ($this->api_use === true) return; // In case of API use, no IDO is necessary
185
+		if ($this->api_use === true) return; // In case of API use, no IDO is necessary
186 186
         
187
-	    // IDO Database
188
-	    if (!array_key_exists('IDOdatabase',$trapConfig['config']))
189
-	    {
190
-	        $this->logging->log("No IDOdatabase in config file: ".$this->trap_module_config,ERROR,'');
191
-	    }
192
-	    $dbIdoName=$trapConfig['config']['IDOdatabase'];		
187
+		// IDO Database
188
+		if (!array_key_exists('IDOdatabase',$trapConfig['config']))
189
+		{
190
+			$this->logging->log("No IDOdatabase in config file: ".$this->trap_module_config,ERROR,'');
191
+		}
192
+		$dbIdoName=$trapConfig['config']['IDOdatabase'];		
193 193
 
194
-	    $this->logging->log("Found IDO database in config file: ".$dbIdoName,INFO );
195
-        if (!array_key_exists($dbIdoName,$dbConfig))
196
-	    {
197
-	        $this->logging->log("No database '.$dbIdoName.' in config file: ".$this->icingaweb2_ressources,ERROR,'');
198
-	        return;
199
-	    }
194
+		$this->logging->log("Found IDO database in config file: ".$dbIdoName,INFO );
195
+		if (!array_key_exists($dbIdoName,$dbConfig))
196
+		{
197
+			$this->logging->log("No database '.$dbIdoName.' in config file: ".$this->icingaweb2_ressources,ERROR,'');
198
+			return;
199
+		}
200 200
 	    
201
-	    $this->trapsDB->setupIDO($dbConfig[$dbIdoName]);
201
+		$this->trapsDB->setupIDO($dbConfig[$dbIdoName]);
202 202
 	}
203 203
 	
204 204
 	/**
@@ -209,9 +209,9 @@  discard block
 block discarded – undo
209 209
 		// Database options
210 210
 		if ($this->logSetup === false) // Only if logging was no setup in constructor
211 211
 		{
212
-    		$this->getDBConfigIfSet('log_level',$this->logging->debugLevel);
213
-    		$this->getDBConfigIfSet('log_destination',$this->logging->outputMode);
214
-    		$this->getDBConfigIfSet('log_file',$this->logging->outputFile);
212
+			$this->getDBConfigIfSet('log_level',$this->logging->debugLevel);
213
+			$this->getDBConfigIfSet('log_destination',$this->logging->outputMode);
214
+			$this->getDBConfigIfSet('log_file',$this->logging->outputFile);
215 215
 		}
216 216
 	}
217 217
 
@@ -222,10 +222,10 @@  discard block
 block discarded – undo
222 222
 	}
223 223
 	
224 224
 	/** 
225
-	*   Get data from db_config
226
-	*	@param $element string name of param
227
-	*	@return mixed : value (or null)
228
-	*/	
225
+	 *   Get data from db_config
226
+	 *	@param $element string name of param
227
+	 *	@return mixed : value (or null)
228
+	 */	
229 229
 	protected function getDBConfig($element)
230 230
 	{
231 231
 		$db_conn=$this->trapsDB->db_connect_trap();
@@ -243,15 +243,15 @@  discard block
 block discarded – undo
243 243
 	}
244 244
 	
245 245
 	/** OBSOLETE Send log. Throws exception on critical error
246
-	*	@param	string $message Message to log
247
-	*	@param	int $level 1=critical 2=warning 3=trace 4=debug
248
-	*	@param  string $destination file/syslog/display
249
-	*	@return void
250
-	**/	
246
+	 *	@param	string $message Message to log
247
+	 *	@param	int $level 1=critical 2=warning 3=trace 4=debug
248
+	 *	@param  string $destination file/syslog/display
249
+	 *	@return void
250
+	 **/	
251 251
 	public function trapLog( $message, $level, $destination ='') // OBSOLETE
252 252
 	{	
253 253
 		// TODO : replace ref with $this->logging->log 
254
-	    $this->logging->log($message, $level, $destination);
254
+		$this->logging->log($message, $level, $destination);
255 255
 	}
256 256
 	
257 257
 	public function setLogging($debugLvl,$outputType,$outputOption=null)  // OBSOLETE
@@ -261,19 +261,19 @@  discard block
 block discarded – undo
261 261
 	
262 262
 	protected function getAPI()
263 263
 	{
264
-	    if ($this->icinga2api == null)
265
-	    {
266
-	        $this->icinga2api = new Icinga2API($this->api_hostname,$this->api_port);
267
-	    }
268
-	    return $this->icinga2api;
264
+		if ($this->icinga2api == null)
265
+		{
266
+			$this->icinga2api = new Icinga2API($this->api_hostname,$this->api_port);
267
+		}
268
+		return $this->icinga2api;
269 269
 	}
270 270
 	
271 271
 	
272 272
 	/** 
273 273
 	 * read data from stream
274
-	*	@param $stream string input stream, defaults to "php://stdin"
275
-	*	@return mixed array trap data or exception with error
276
-	*/
274
+	 *	@param $stream string input stream, defaults to "php://stdin"
275
+	 *	@return mixed array trap data or exception with error
276
+	 */
277 277
 	public function read_trap($stream='php://stdin')
278 278
 	{
279 279
 		//Read data from snmptrapd from stdin
@@ -281,7 +281,7 @@  discard block
 block discarded – undo
281 281
 
282 282
 		if ($input_stream === false)
283 283
 		{
284
-		    $this->writeTrapErrorToDB("Error reading trap (code 1/Stdin)");
284
+			$this->writeTrapErrorToDB("Error reading trap (code 1/Stdin)");
285 285
 			$this->logging->log("Error reading stdin !",ERROR,'');
286 286
 			return null; // note : exception thrown by logging
287 287
 		}
@@ -290,21 +290,21 @@  discard block
 block discarded – undo
290 290
 		$this->receivingHost=chop(fgets($input_stream));
291 291
 		if ($this->receivingHost === false)
292 292
 		{
293
-		    $this->writeTrapErrorToDB("Error reading trap (code 1/Line Host)");
293
+			$this->writeTrapErrorToDB("Error reading trap (code 1/Line Host)");
294 294
 			$this->logging->log("Error reading Host !",ERROR,''); 
295 295
 		}
296 296
 		// line 2 IP:port=>IP:port
297 297
 		$IP=chop(fgets($input_stream));
298 298
 		if ($IP === false)
299 299
 		{
300
-		    $this->writeTrapErrorToDB("Error reading trap (code 1/Line IP)");
300
+			$this->writeTrapErrorToDB("Error reading trap (code 1/Line IP)");
301 301
 			$this->logging->log("Error reading IP !",ERROR,''); 
302 302
 		}
303 303
 		$matches=array();
304 304
 		$ret_code=preg_match('/.DP: \[(.*)\]:(.*)->\[(.*)\]:(.*)/',$IP,$matches);
305 305
 		if ($ret_code===0 || $ret_code===false) 
306 306
 		{
307
-		    $this->writeTrapErrorToDB("Error parsing trap (code 2/IP)");
307
+			$this->writeTrapErrorToDB("Error parsing trap (code 2/IP)");
308 308
 			$this->logging->log('Error parsing IP : '.$IP,ERROR,'');
309 309
 		} 
310 310
 		else 
@@ -325,7 +325,7 @@  discard block
 block discarded – undo
325 325
 			}
326 326
 			else 
327 327
 			{
328
-			    if (($matches[1]=='.1.3.6.1.6.3.1.1.4.1.0') || ($matches[1]=='.1.3.6.1.6.3.1.1.4.1'))
328
+				if (($matches[1]=='.1.3.6.1.6.3.1.1.4.1.0') || ($matches[1]=='.1.3.6.1.6.3.1.1.4.1'))
329 329
 				{
330 330
 					$this->trap_data['trap_oid']=$matches[2];				
331 331
 				}
@@ -341,7 +341,7 @@  discard block
 block discarded – undo
341 341
 
342 342
 		if ($this->trap_data['trap_oid']=='unknown') 
343 343
 		{
344
-		    $this->writeTrapErrorToDB("No trap oid found : check snmptrapd configuration (code 3/OID)",$this->trap_data['source_ip']);
344
+			$this->writeTrapErrorToDB("No trap oid found : check snmptrapd configuration (code 3/OID)",$this->trap_data['source_ip']);
345 345
 			$this->logging->log('no trap oid found',ERROR,'');
346 346
 		} 
347 347
 
@@ -371,9 +371,9 @@  discard block
 block discarded – undo
371 371
 
372 372
 	/** 
373 373
 	 * Translate oid into array(MIB,Name)
374
-	* @param $oid string oid to translate
375
-	* @return mixed : null if not found or array(MIB,Name)
376
-	*/
374
+	 * @param $oid string oid to translate
375
+	 * @return mixed : null if not found or array(MIB,Name)
376
+	 */
377 377
 	public function translateOID($oid)
378 378
 	{
379 379
 		// try from database
@@ -406,7 +406,7 @@  discard block
 block discarded – undo
406 406
 		
407 407
 		// Try to get oid name from snmptranslate
408 408
 		$translate=exec($this->snmptranslate . ' -m ALL -M +'.$this->snmptranslate_dirs.
409
-		    ' '.$oid);
409
+			' '.$oid);
410 410
 		$matches=array();
411 411
 		$ret_code=preg_match('/(.*)::(.*)/',$translate,$matches);
412 412
 		if ($ret_code===0 || $ret_code === false) {
@@ -419,9 +419,9 @@  discard block
 block discarded – undo
419 419
 	
420 420
 	/** 
421 421
 	 * Erase old trap records 
422
-	*	@param integer $days : erase traps when more than $days old
423
-	*	@return integer : number of lines deleted
424
-	**/
422
+	 *	@param integer $days : erase traps when more than $days old
423
+	 *	@return integer : number of lines deleted
424
+	 **/
425 425
 	public function eraseOldTraps($days=0)
426 426
 	{
427 427
 		if ($days==0)
@@ -446,72 +446,72 @@  discard block
 block discarded – undo
446 446
 	public function writeTrapErrorToDB($message,$sourceIP=null,$trapoid=null)
447 447
 	{
448 448
 	    
449
-	    $db_conn=$this->trapsDB->db_connect_trap();
449
+		$db_conn=$this->trapsDB->db_connect_trap();
450 450
 	    
451
-	    // add date time
452
-	    $insert_col ='date_received,status';
453
-	    $insert_val = "'" . date("Y-m-d H:i:s")."','error'";
451
+		// add date time
452
+		$insert_col ='date_received,status';
453
+		$insert_val = "'" . date("Y-m-d H:i:s")."','error'";
454 454
         
455
-	    if ($sourceIP !=null)
456
-	    {
457
-	        $insert_col .=',source_ip';
458
-	        $insert_val .=",'". $sourceIP ."'";
459
-	    }
460
-	    if ($trapoid !=null)
461
-	    {
462
-	        $insert_col .=',trap_oid';
463
-	        $insert_val .=",'". $trapoid ."'";
464
-	    }
465
-	    $insert_col .=',status_detail';
466
-	    $insert_val .=",'". $message ."'";
455
+		if ($sourceIP !=null)
456
+		{
457
+			$insert_col .=',source_ip';
458
+			$insert_val .=",'". $sourceIP ."'";
459
+		}
460
+		if ($trapoid !=null)
461
+		{
462
+			$insert_col .=',trap_oid';
463
+			$insert_val .=",'". $trapoid ."'";
464
+		}
465
+		$insert_col .=',status_detail';
466
+		$insert_val .=",'". $message ."'";
467 467
 	    
468
-	    $sql= 'INSERT INTO '.$this->db_prefix.'received (' . $insert_col . ') VALUES ('.$insert_val.')';
468
+		$sql= 'INSERT INTO '.$this->db_prefix.'received (' . $insert_col . ') VALUES ('.$insert_val.')';
469 469
 	    
470
-	    switch ($this->trapsDB->trapDBType)
471
-	    {
472
-	        case 'pgsql':
473
-	            $sql .= ' RETURNING id;';
474
-	            $this->logging->log('sql : '.$sql,INFO);
475
-	            if (($ret_code=$db_conn->query($sql)) === false) {
476
-	                $this->logging->log('Error SQL insert : '.$sql,1,'');
477
-	            }
478
-	            $this->logging->log('SQL insertion OK',INFO );
479
-	            // Get last id to insert oid/values in secondary table
480
-	            if (($inserted_id_ret=$ret_code->fetch(PDO::FETCH_ASSOC)) === false) {
470
+		switch ($this->trapsDB->trapDBType)
471
+		{
472
+			case 'pgsql':
473
+				$sql .= ' RETURNING id;';
474
+				$this->logging->log('sql : '.$sql,INFO);
475
+				if (($ret_code=$db_conn->query($sql)) === false) {
476
+					$this->logging->log('Error SQL insert : '.$sql,1,'');
477
+				}
478
+				$this->logging->log('SQL insertion OK',INFO );
479
+				// Get last id to insert oid/values in secondary table
480
+				if (($inserted_id_ret=$ret_code->fetch(PDO::FETCH_ASSOC)) === false) {
481 481
 	                
482
-	                $this->logging->log('Erreur recuperation id',1,'');
483
-	            }
484
-	            if (! isset($inserted_id_ret['id'])) {
485
-	                $this->logging->log('Error getting id',1,'');
486
-	            }
487
-	            $this->trap_id=$inserted_id_ret['id'];
488
-	            break;
489
-	        case 'mysql':
490
-	            $sql .= ';';
491
-	            $this->logging->log('sql : '.$sql,INFO );
492
-	            if ($db_conn->query($sql) === false) {
493
-	                $this->logging->log('Error SQL insert : '.$sql,1,'');
494
-	            }
495
-	            $this->logging->log('SQL insertion OK',INFO );
496
-	            // Get last id to insert oid/values in secondary table
497
-	            $sql='SELECT LAST_INSERT_ID();';
498
-	            if (($ret_code=$db_conn->query($sql)) === false) {
499
-	                $this->logging->log('Erreur recuperation id',1,'');
500
-	            }
482
+					$this->logging->log('Erreur recuperation id',1,'');
483
+				}
484
+				if (! isset($inserted_id_ret['id'])) {
485
+					$this->logging->log('Error getting id',1,'');
486
+				}
487
+				$this->trap_id=$inserted_id_ret['id'];
488
+				break;
489
+			case 'mysql':
490
+				$sql .= ';';
491
+				$this->logging->log('sql : '.$sql,INFO );
492
+				if ($db_conn->query($sql) === false) {
493
+					$this->logging->log('Error SQL insert : '.$sql,1,'');
494
+				}
495
+				$this->logging->log('SQL insertion OK',INFO );
496
+				// Get last id to insert oid/values in secondary table
497
+				$sql='SELECT LAST_INSERT_ID();';
498
+				if (($ret_code=$db_conn->query($sql)) === false) {
499
+					$this->logging->log('Erreur recuperation id',1,'');
500
+				}
501 501
 	            
502
-	            $inserted_id=$ret_code->fetch(PDO::FETCH_ASSOC)['LAST_INSERT_ID()'];
503
-	            if ($inserted_id==false) throw new Exception("Weird SQL error : last_insert_id returned false : open issue");
504
-	            $this->trap_id=$inserted_id;
505
-	            break;
506
-	        default:
507
-	            $this->logging->log('Error SQL type unknown  : '.$this->trapsDB->trapDBType,1,'');
508
-	    }
502
+				$inserted_id=$ret_code->fetch(PDO::FETCH_ASSOC)['LAST_INSERT_ID()'];
503
+				if ($inserted_id==false) throw new Exception("Weird SQL error : last_insert_id returned false : open issue");
504
+				$this->trap_id=$inserted_id;
505
+				break;
506
+			default:
507
+				$this->logging->log('Error SQL type unknown  : '.$this->trapsDB->trapDBType,1,'');
508
+		}
509 509
 	    
510
-	    $this->logging->log('id found: '. $this->trap_id,INFO );    
510
+		$this->logging->log('id found: '. $this->trap_id,INFO );    
511 511
 	}
512 512
 	
513 513
 	/** Write trap data to trap database
514
-	*/
514
+	 */
515 515
 	public function writeTrapToDB()
516 516
 	{
517 517
 		
@@ -609,10 +609,10 @@  discard block
 block discarded – undo
609 609
 	}
610 610
 
611 611
 	/** Get rules from rule database with ip and oid
612
-	*	@param $ip string ipv4 or ipv6
613
-	*	@param $oid string oid in numeric
614
-	*	@return mixed : PDO object or false
615
-	*/	
612
+	 *	@param $ip string ipv4 or ipv6
613
+	 *	@param $oid string oid in numeric
614
+	 *	@return mixed : PDO object or false
615
+	 */	
616 616
 	protected function getRules($ip,$oid)
617 617
 	{
618 618
 		$db_conn=$this->trapsDB->db_connect_trap();
@@ -671,9 +671,9 @@  discard block
 block discarded – undo
671 671
 	}
672 672
 
673 673
 	/** Add rule match to rule
674
-	*	@param id int : rule id
675
-	*   @param set int : value to set
676
-	*/
674
+	 *	@param id int : rule id
675
+	 *   @param set int : value to set
676
+	 */
677 677
 	protected function add_rule_match($id, $set)
678 678
 	{
679 679
 		$db_conn=$this->trapsDB->db_connect_trap();
@@ -690,53 +690,53 @@  discard block
 block discarded – undo
690 690
 	 * @param integer $state numerical staus 
691 691
 	 * @param string $display
692 692
 	 * @returnn bool true is service check was sent without error
693
-	*/
693
+	 */
694 694
 	public function serviceCheckResult($host,$service,$state,$display)
695 695
 	{
696
-	    if ($this->api_use === false)
697
-	    {
698
-    		$send = '[' . date('U') .'] PROCESS_SERVICE_CHECK_RESULT;' .
699
-    			$host.';' .$service .';' . $state . ';'.$display;
700
-    		$this->logging->log( $send." : to : " .$this->icinga2cmd,INFO );
696
+		if ($this->api_use === false)
697
+		{
698
+			$send = '[' . date('U') .'] PROCESS_SERVICE_CHECK_RESULT;' .
699
+				$host.';' .$service .';' . $state . ';'.$display;
700
+			$this->logging->log( $send." : to : " .$this->icinga2cmd,INFO );
701 701
     		
702
-    		// TODO : file_put_contents & fopen (,'w' or 'a') does not work. See why. Or not as using API will be by default....
703
-    		exec('echo "'.$send.'" > ' .$this->icinga2cmd);
704
-    		return true;
705
-	    }
706
-	    else
707
-	    {
708
-	        $api = $this->getAPI();
709
-	        $api->setCredentials($this->api_username, $this->api_password);
710
-	        list($retcode,$retmessage)=$api->serviceCheckResult($host,$service,$state,$display);
711
-	        if ($retcode == false)
712
-	        {
713
-	            $this->logging->log( "Error sending result : " .$retmessage,WARN,'');
714
-	            return false;
715
-	        }
716
-	        else 
717
-	        {
718
-	            $this->logging->log( "Sent result : " .$retmessage,INFO );
719
-	            return true;
720
-	        }
721
-	    }
702
+			// TODO : file_put_contents & fopen (,'w' or 'a') does not work. See why. Or not as using API will be by default....
703
+			exec('echo "'.$send.'" > ' .$this->icinga2cmd);
704
+			return true;
705
+		}
706
+		else
707
+		{
708
+			$api = $this->getAPI();
709
+			$api->setCredentials($this->api_username, $this->api_password);
710
+			list($retcode,$retmessage)=$api->serviceCheckResult($host,$service,$state,$display);
711
+			if ($retcode == false)
712
+			{
713
+				$this->logging->log( "Error sending result : " .$retmessage,WARN,'');
714
+				return false;
715
+			}
716
+			else 
717
+			{
718
+				$this->logging->log( "Sent result : " .$retmessage,INFO );
719
+				return true;
720
+			}
721
+		}
722 722
 	}
723 723
 	
724 724
 	public function getHostByIP($ip)
725 725
 	{
726
-	    $api = $this->getAPI();
727
-	    $api->setCredentials($this->api_username, $this->api_password);
728
-	    return $api->getHostByIP($ip);
726
+		$api = $this->getAPI();
727
+		$api->setCredentials($this->api_username, $this->api_password);
728
+		return $api->getHostByIP($ip);
729 729
 	}
730 730
 	
731 731
 	/** Resolve display. 
732
-	*	Changes OID(<oid>) to value if found or text "<not in trap>"
733
-	*	@param $display string
734
-	*	@return string display
735
-	*/
732
+	 *	Changes OID(<oid>) to value if found or text "<not in trap>"
733
+	 *	@param $display string
734
+	 *	@return string display
735
+	 */
736 736
 	protected function applyDisplay($display)
737 737
 	{
738
-	    $matches=array();
739
-	    while (preg_match('/_OID\(([0-9\.]+)\)/',$display,$matches) == 1)
738
+		$matches=array();
739
+		while (preg_match('/_OID\(([0-9\.]+)\)/',$display,$matches) == 1)
740 740
 		{
741 741
 			$oid=$matches[1];
742 742
 			$found=0;
@@ -796,11 +796,11 @@  discard block
 block discarded – undo
796 796
 		
797 797
 		if ($rule[$item] == '(')
798 798
 		{ // grouping
799
-		    $item++;
799
+			$item++;
800 800
 			$start=$item;
801 801
 			$parenthesis_count=0; 
802 802
 			while (($item < strlen($rule)) // Not end of string AND
803
-			      && ( ($rule[$item] != ')' ) || $parenthesis_count > 0) ) // Closing ')' or embeded ()
803
+				  && ( ($rule[$item] != ')' ) || $parenthesis_count > 0) ) // Closing ')' or embeded ()
804 804
 			{ 
805 805
 				if ($rule[$item] == '"' )
806 806
 				{ // pass through string
@@ -808,14 +808,14 @@  discard block
 block discarded – undo
808 808
 					$item=$this->eval_getNext($rule,$item,'"');
809 809
 				} 
810 810
 				else{
811
-				    if ($rule[$item] == '(')
812
-				    {
813
-				        $parenthesis_count++;
814
-				    }
815
-				    if ($rule[$item] == ')')
816
-				    {
817
-				        $parenthesis_count--;
818
-				    }
811
+					if ($rule[$item] == '(')
812
+					{
813
+						$parenthesis_count++;
814
+					}
815
+					if ($rule[$item] == ')')
816
+					{
817
+						$parenthesis_count--;
818
+					}
819 819
 					$item++;
820 820
 				}
821 821
 			}
@@ -867,24 +867,24 @@  discard block
 block discarded – undo
867 867
 	}
868 868
 	
869 869
 	/** Evaluation : makes token and evaluate. 
870
-	*	Public function for expressions testing
871
-	*	accepts : < > = <= >= !=  (typec = 0)
872
-	*	operators : & | (typec=1)
873
-	*	with : integers/float  (type 0) or strings "" (type 1) or results (type 2)
874
-	*   comparison int vs strings will return null (error)
875
-	*	return : bool or null on error
876
-	*/
870
+	 *	Public function for expressions testing
871
+	 *	accepts : < > = <= >= !=  (typec = 0)
872
+	 *	operators : & | (typec=1)
873
+	 *	with : integers/float  (type 0) or strings "" (type 1) or results (type 2)
874
+	 *   comparison int vs strings will return null (error)
875
+	 *	return : bool or null on error
876
+	 */
877 877
 	public function evaluation($rule,&$item)
878 878
 	{
879
-	    //echo "Evaluation of ".substr($rule,$item)."\n";
879
+		//echo "Evaluation of ".substr($rule,$item)."\n";
880 880
 		if ( $rule[$item] == '!') // If '!' found, negate next expression.
881 881
 		{
882
-		    $negate=true;
883
-		    $item++;
882
+			$negate=true;
883
+			$item++;
884 884
 		}
885 885
 		else
886 886
 		{
887
-		    $negate=false;
887
+			$negate=false;
888 888
 		}
889 889
 		// First element : number, string or ()
890 890
 		list($type1,$val1) = $this->eval_getElement($rule,$item);
@@ -904,24 +904,24 @@  discard block
 block discarded – undo
904 904
 		// Third element : number, string or ()
905 905
 		if ( $rule[$item] == '!') // starts with a ! so evaluate whats next
906 906
 		{
907
-		    $item++;
908
-		    if ($typec != 1) throw new Exception("Mixing boolean and comparison : ".$rule);
909
-		    $val2= ! $this->evaluation($rule,$item);
910
-		    $type2=2; // result is a boolean 
907
+			$item++;
908
+			if ($typec != 1) throw new Exception("Mixing boolean and comparison : ".$rule);
909
+			$val2= ! $this->evaluation($rule,$item);
910
+			$type2=2; // result is a boolean 
911 911
 		}
912 912
 		else 
913 913
 		{
914
-		    list($type2,$val2) = $this->eval_getElement($rule,$item);
914
+			list($type2,$val2) = $this->eval_getElement($rule,$item);
915 915
 		}
916 916
 		//echo "Elmt2: ".$val2."/".$type2." : ".substr($rule,$item)."\n";
917 917
 		
918 918
 		if ($type1!=$type2)  // cannot compare different types
919 919
 		{ 
920
-		    throw new Exception("Cannot compare string & number : ".$rule);
920
+			throw new Exception("Cannot compare string & number : ".$rule);
921 921
 		}
922 922
 		if ($typec==1 && $type1 !=2) // cannot use & or | with string/number
923 923
 		{
924
-		    throw new Exception("Cannot use boolean operators with string & number : ".$rule);
924
+			throw new Exception("Cannot use boolean operators with string & number : ".$rule);
925 925
 		}
926 926
 		
927 927
 		switch ($comp){
@@ -979,9 +979,9 @@  discard block
 block discarded – undo
979 979
 	}		
980 980
 	
981 981
 	/** Evaluation rule (uses eval_* functions recursively)
982
-	*	@param $rule string rule ( _OID(.1.3.6.1.4.1.8072.2.3.2.1)=_OID(.1.3.6.1.2.1.1.3.0) )
983
-	*	@return bool : true : rule match, false : rule don't match , throw exception on error.
984
-	*/
982
+	 *	@param $rule string rule ( _OID(.1.3.6.1.4.1.8072.2.3.2.1)=_OID(.1.3.6.1.2.1.1.3.0) )
983
+	 *	@return bool : true : rule match, false : rule don't match , throw exception on error.
984
+	 */
985 985
 	
986 986
 	protected function eval_rule($rule)
987 987
 	{
@@ -1026,7 +1026,7 @@  discard block
 block discarded – undo
1026 1026
 			}
1027 1027
 			if ($found==0)
1028 1028
 			{	// OID not found : throw error
1029
-			    throw new Exception('OID '.$oid.' not found in trap');
1029
+				throw new Exception('OID '.$oid.' not found in trap');
1030 1030
 			}
1031 1031
 		}
1032 1032
 		$item=0;
@@ -1037,7 +1037,7 @@  discard block
 block discarded – undo
1037 1037
 	}
1038 1038
 	
1039 1039
 	/** Match rules for current trap and do action
1040
-	*/
1040
+	 */
1041 1041
 	public function applyRules()
1042 1042
 	{
1043 1043
 		$rules = $this->getRules($this->trap_data['source_ip'],$this->trap_data['trap_oid']);
@@ -1074,12 +1074,12 @@  discard block
 block discarded – undo
1074 1074
 					{
1075 1075
 						if ($this->serviceCheckResult($host_name,$service_name,$action,$display) == false)
1076 1076
 						{
1077
-						    $this->trap_action.='Error sending status : check cmd/API';
1077
+							$this->trap_action.='Error sending status : check cmd/API';
1078 1078
 						}
1079 1079
 						else
1080 1080
 						{
1081
-						    $this->add_rule_match($rule['id'],$rule['num_match']+1);
1082
-						    $this->trap_action.='Status '.$action.' to '.$host_name.'/'.$service_name;
1081
+							$this->add_rule_match($rule['id'],$rule['num_match']+1);
1082
+							$this->trap_action.='Status '.$action.' to '.$host_name.'/'.$service_name;
1083 1083
 						}
1084 1084
 					}
1085 1085
 					else
@@ -1096,15 +1096,15 @@  discard block
 block discarded – undo
1096 1096
 					$this->logging->log('action NOK : '.$action,INFO );
1097 1097
 					if ($action >= 0)
1098 1098
 					{
1099
-					    if ($this->serviceCheckResult($host_name,$service_name,$action,$display)==false)
1100
-					    {
1101
-					        $this->trap_action.='Error sending status : check cmd/API';
1102
-					    }
1103
-					    else
1104
-					    {
1105
-    						$this->add_rule_match($rule['id'],$rule['num_match']+1);
1106
-    						$this->trap_action.='Status '.$action.' to '.$host_name.'/'.$service_name;
1107
-					    }
1099
+						if ($this->serviceCheckResult($host_name,$service_name,$action,$display)==false)
1100
+						{
1101
+							$this->trap_action.='Error sending status : check cmd/API';
1102
+						}
1103
+						else
1104
+						{
1105
+							$this->add_rule_match($rule['id'],$rule['num_match']+1);
1106
+							$this->trap_action.='Status '.$action.' to '.$host_name.'/'.$service_name;
1107
+						}
1108 1108
 					}
1109 1109
 					else
1110 1110
 					{
@@ -1127,9 +1127,9 @@  discard block
 block discarded – undo
1127 1127
 			}
1128 1128
 			catch (Exception $e) 
1129 1129
 			{ 
1130
-			    $this->logging->log('Error in rule eval : '.$e->getMessage(),WARN,'');
1131
-			    $this->trap_action.=' ERR : '.$e->getMessage();
1132
-			    $this->trap_data['status']='error';
1130
+				$this->logging->log('Error in rule eval : '.$e->getMessage(),WARN,'');
1131
+				$this->trap_action.=' ERR : '.$e->getMessage();
1132
+				$this->trap_data['status']='error';
1133 1133
 			}
1134 1134
 			
1135 1135
 		}
@@ -1144,8 +1144,8 @@  discard block
 block discarded – undo
1144 1144
 	}
1145 1145
 
1146 1146
 	/** Add Time a action to rule
1147
-	*	@param string $time : time to process to insert in SQL
1148
-	*/
1147
+	 *	@param string $time : time to process to insert in SQL
1148
+	 */
1149 1149
 	public function add_rule_final($time)
1150 1150
 	{
1151 1151
 		$db_conn=$this->trapsDB->db_connect_trap();
@@ -1162,9 +1162,9 @@  discard block
 block discarded – undo
1162 1162
 	/*********** UTILITIES *********************/
1163 1163
 	
1164 1164
 	/** reset service to OK after time defined in rule
1165
-	*	TODO logic is : get all service in error + all rules, see if getting all rules then select services is better 
1166
-	*	@return integer : not in use
1167
-	**/
1165
+	 *	TODO logic is : get all service in error + all rules, see if getting all rules then select services is better 
1166
+	 *	@return integer : not in use
1167
+	 **/
1168 1168
 	public function reset_services()
1169 1169
 	{
1170 1170
 		// Get all services not in 'ok' state
@@ -1236,105 +1236,105 @@  discard block
 block discarded – undo
1236 1236
 		$description=$db_conn->quote($description);
1237 1237
 		if (isset($this->dbOidIndex[$oid]))
1238 1238
 		{
1239
-		    if ($this->dbOidIndex[$oid]['key'] == -1)
1240
-		    { // newly created.
1241
-		        return 0;
1242
-		    }
1239
+			if ($this->dbOidIndex[$oid]['key'] == -1)
1240
+			{ // newly created.
1241
+				return 0;
1242
+			}
1243 1243
 			if ( $name != $this->dbOidAll[$this->dbOidIndex[$oid]['key']]['name'] ||
1244
-			    $mib != $this->dbOidAll[$this->dbOidIndex[$oid]['key']]['mib'] ||
1245
-			    $type != $this->dbOidAll[$this->dbOidIndex[$oid]['key']]['type'] //||
1246
-			    //$textConv != $this->dbOidAll[$this->dbOidIndex[$oid]['key']]['textual_convention'] //||
1247
-			    //$dispHint != $this->dbOidAll[$this->dbOidIndex[$oid]['key']]['display_hint'] ||
1248
-			    //$syntax != $this->dbOidAll[$this->dbOidIndex[$oid]['key']]['syntax'] ||
1249
-			    //$type_enum != $this->dbOidAll[$this->dbOidIndex[$oid]['key']]['type_enum'] ||
1250
-			    //$description != $this->dbOidAll[$this->dbOidIndex[$oid]['key']]['description']
1251
-			    )
1244
+				$mib != $this->dbOidAll[$this->dbOidIndex[$oid]['key']]['mib'] ||
1245
+				$type != $this->dbOidAll[$this->dbOidIndex[$oid]['key']]['type'] //||
1246
+				//$textConv != $this->dbOidAll[$this->dbOidIndex[$oid]['key']]['textual_convention'] //||
1247
+				//$dispHint != $this->dbOidAll[$this->dbOidIndex[$oid]['key']]['display_hint'] ||
1248
+				//$syntax != $this->dbOidAll[$this->dbOidIndex[$oid]['key']]['syntax'] ||
1249
+				//$type_enum != $this->dbOidAll[$this->dbOidIndex[$oid]['key']]['type_enum'] ||
1250
+				//$description != $this->dbOidAll[$this->dbOidIndex[$oid]['key']]['description']
1251
+				)
1252 1252
 			{ // Do update
1253
-			    $sql='UPDATE '.$this->db_prefix.'mib_cache SET '.
1254
- 			    'name = :name , type = :type , mib = :mib , textual_convention = :tc , display_hint = :display_hint'. 
1255
- 			    ', syntax = :syntax, type_enum = :type_enum, description = :description '.
1256
- 			    ' WHERE id= :id';
1257
-			    $sqlQuery=$db_conn->prepare($sql);
1253
+				$sql='UPDATE '.$this->db_prefix.'mib_cache SET '.
1254
+ 				'name = :name , type = :type , mib = :mib , textual_convention = :tc , display_hint = :display_hint'. 
1255
+ 				', syntax = :syntax, type_enum = :type_enum, description = :description '.
1256
+ 				' WHERE id= :id';
1257
+				$sqlQuery=$db_conn->prepare($sql);
1258 1258
 			    
1259
-			    $sqlParam=array(
1260
-			        ':name' => $name,
1261
-			        ':type' => $type, 
1262
-			        ':mib' => $mib, 
1263
-			        ':tc' =>  ($textConv==null)?'null':$textConv , 
1264
-			        ':display_hint' => ($dispHint==null)?'null':$dispHint ,
1265
-			        ':syntax' => ($syntax==null)?'null':$syntax,
1266
-			        ':type_enum' => ($type_enum==null)?'null':$type_enum, 
1267
-			        ':description' => ($description==null)?'null':$description,
1268
-			        ':id' => $this->dbOidAll[$this->dbOidIndex[$oid]['id']]
1269
-			    );
1259
+				$sqlParam=array(
1260
+					':name' => $name,
1261
+					':type' => $type, 
1262
+					':mib' => $mib, 
1263
+					':tc' =>  ($textConv==null)?'null':$textConv , 
1264
+					':display_hint' => ($dispHint==null)?'null':$dispHint ,
1265
+					':syntax' => ($syntax==null)?'null':$syntax,
1266
+					':type_enum' => ($type_enum==null)?'null':$type_enum, 
1267
+					':description' => ($description==null)?'null':$description,
1268
+					':id' => $this->dbOidAll[$this->dbOidIndex[$oid]['id']]
1269
+				);
1270 1270
 			    
1271
-			    if ($sqlQuery->execute($sqlParam) === false) {
1272
-			        $this->logging->log('Error in query : ' . $sql,ERROR,'');
1273
-			    }
1274
-			    $this->logging->log('Trap updated : '.$name . ' / OID : '.$oid,DEBUG );
1271
+				if ($sqlQuery->execute($sqlParam) === false) {
1272
+					$this->logging->log('Error in query : ' . $sql,ERROR,'');
1273
+				}
1274
+				$this->logging->log('Trap updated : '.$name . ' / OID : '.$oid,DEBUG );
1275 1275
 				return 1;
1276 1276
 			}
1277 1277
 			else
1278 1278
 			{
1279
-			    $this->logging->log('Trap unchanged : '.$name . ' / OID : '.$oid,DEBUG );
1280
-			    return 0;
1279
+				$this->logging->log('Trap unchanged : '.$name . ' / OID : '.$oid,DEBUG );
1280
+				return 0;
1281 1281
 			}
1282 1282
 		}
1283
-        // create new OID.
1283
+		// create new OID.
1284 1284
 			
1285 1285
 		// Insert data
1286 1286
 
1287 1287
 		$sql='INSERT INTO '.$this->db_prefix.'mib_cache '.
1288
-		      '(oid, name, type , mib, textual_convention, display_hint '.
1289
-              ', syntax, type_enum , description ) ' . 
1290
-              'values (:oid, :name , :type ,:mib ,:tc , :display_hint'.
1291
-              ', :syntax, :type_enum, :description )';
1288
+			  '(oid, name, type , mib, textual_convention, display_hint '.
1289
+			  ', syntax, type_enum , description ) ' . 
1290
+			  'values (:oid, :name , :type ,:mib ,:tc , :display_hint'.
1291
+			  ', :syntax, :type_enum, :description )';
1292 1292
         
1293 1293
 		if ($this->trapsDB->trapDBType == 'pgsql') $sql .= 'RETURNING id';
1294 1294
 		
1295 1295
 		$sqlQuery=$db_conn->prepare($sql);
1296 1296
 		
1297 1297
 		$sqlParam=array(
1298
-		    ':oid' => $oid,
1299
-		    ':name' => $name,
1300
-		    ':type' => $type,
1301
-		    ':mib' => $mib,
1302
-		    ':tc' =>  ($textConv==null)?'null':$textConv ,
1303
-		    ':display_hint' => ($dispHint==null)?'null':$dispHint ,
1304
-		    ':syntax' => ($syntax==null)?'null':$syntax,
1305
-		    ':type_enum' => ($type_enum==null)?'null':$type_enum,
1306
-		    ':description' => ($description==null)?'null':$description
1298
+			':oid' => $oid,
1299
+			':name' => $name,
1300
+			':type' => $type,
1301
+			':mib' => $mib,
1302
+			':tc' =>  ($textConv==null)?'null':$textConv ,
1303
+			':display_hint' => ($dispHint==null)?'null':$dispHint ,
1304
+			':syntax' => ($syntax==null)?'null':$syntax,
1305
+			':type_enum' => ($type_enum==null)?'null':$type_enum,
1306
+			':description' => ($description==null)?'null':$description
1307 1307
 		);
1308 1308
 		
1309 1309
 		if ($sqlQuery->execute($sqlParam) === false) {
1310
-		    $this->logging->log('Error in query : ' . $sql,1,'');
1310
+			$this->logging->log('Error in query : ' . $sql,1,'');
1311 1311
 		}
1312 1312
 		
1313 1313
 		switch ($this->trapsDB->trapDBType)
1314 1314
 		{
1315
-		    case 'pgsql':
1316
-		        // Get last id to insert oid/values in secondary table
1317
-		        if (($inserted_id_ret=$sqlQuery->fetch(PDO::FETCH_ASSOC)) === false) {		            
1318
-		            $this->logging->log('Error getting id - pgsql - ',1,'');
1319
-		        }
1320
-		        if (! isset($inserted_id_ret['id'])) {
1321
-		            $this->logging->log('Error getting id - pgsql - empty.',1,'');
1322
-		        }
1323
-		        $this->dbOidIndex[$oid]['id']=$inserted_id_ret['id'];
1324
-		        break;
1325
-		    case 'mysql':
1326
-		        // Get last id to insert oid/values in secondary table
1327
-		        $sql='SELECT LAST_INSERT_ID();';
1328
-		        if (($ret_code=$db_conn->query($sql)) === false) {
1329
-		            $this->logging->log('Erreur getting id - mysql - ',1,'');
1330
-		        }
1315
+			case 'pgsql':
1316
+				// Get last id to insert oid/values in secondary table
1317
+				if (($inserted_id_ret=$sqlQuery->fetch(PDO::FETCH_ASSOC)) === false) {		            
1318
+					$this->logging->log('Error getting id - pgsql - ',1,'');
1319
+				}
1320
+				if (! isset($inserted_id_ret['id'])) {
1321
+					$this->logging->log('Error getting id - pgsql - empty.',1,'');
1322
+				}
1323
+				$this->dbOidIndex[$oid]['id']=$inserted_id_ret['id'];
1324
+				break;
1325
+			case 'mysql':
1326
+				// Get last id to insert oid/values in secondary table
1327
+				$sql='SELECT LAST_INSERT_ID();';
1328
+				if (($ret_code=$db_conn->query($sql)) === false) {
1329
+					$this->logging->log('Erreur getting id - mysql - ',1,'');
1330
+				}
1331 1331
 		        
1332
-		        $inserted_id=$ret_code->fetch(PDO::FETCH_ASSOC)['LAST_INSERT_ID()'];
1333
-		        if ($inserted_id==false) throw new Exception("Weird SQL error : last_insert_id returned false : open issue");
1334
-		        $this->dbOidIndex[$oid]['id']=$inserted_id;
1335
-		        break;
1336
-		    default:
1337
-		        $this->logging->log('Error SQL type Unknown : '.$this->trapsDB->trapDBType,1,'');
1332
+				$inserted_id=$ret_code->fetch(PDO::FETCH_ASSOC)['LAST_INSERT_ID()'];
1333
+				if ($inserted_id==false) throw new Exception("Weird SQL error : last_insert_id returned false : open issue");
1334
+				$this->dbOidIndex[$oid]['id']=$inserted_id;
1335
+				break;
1336
+			default:
1337
+				$this->logging->log('Error SQL type Unknown : '.$this->trapsDB->trapDBType,1,'');
1338 1338
 		}
1339 1339
 
1340 1340
 		// Set as newly created.
@@ -1342,148 +1342,148 @@  discard block
 block discarded – undo
1342 1342
 		return 2;
1343 1343
 	}
1344 1344
 
1345
-    /**
1346
-     * create or update (with check_existing = true) objects of trap
1347
-     * @param string $trapOID : trap oid
1348
-     * @param string $trapmib : mib of trap
1349
-     * @param array $objects : array of objects name (without MIB)
1350
-     * @param bool $check_existing : check instead of create
1351
-     */
1345
+	/**
1346
+	 * create or update (with check_existing = true) objects of trap
1347
+	 * @param string $trapOID : trap oid
1348
+	 * @param string $trapmib : mib of trap
1349
+	 * @param array $objects : array of objects name (without MIB)
1350
+	 * @param bool $check_existing : check instead of create
1351
+	 */
1352 1352
 	public function trap_objects($trapOID,$trapmib,$objects,$check_existing)
1353 1353
 	{
1354
-	    $dbObjects=null; // cache of objects for trap in db
1355
-	    $db_conn=$this->trapsDB->db_connect_trap();
1354
+		$dbObjects=null; // cache of objects for trap in db
1355
+		$db_conn=$this->trapsDB->db_connect_trap();
1356 1356
 	    
1357
-	    // Get id of trapmib.
1357
+		// Get id of trapmib.
1358 1358
 
1359
-	    $trapId = $this->dbOidIndex[$trapOID]['id'];
1360
-	    if ($check_existing === true)
1361
-	    {
1362
-	        // Get all objects
1363
-	        $sql='SELECT * FROM '.$this->db_prefix.'mib_cache_trap_object where trap_id='.$trapId.';';
1364
-	        $this->logging->log('SQL query get all traps: '.$sql,DEBUG );
1365
-	        if (($ret_code=$db_conn->query($sql)) === false) {
1366
-	            $this->logging->log('No result in query : ' . $sql,1,'');
1367
-	        }
1368
-	        $dbObjectsRaw=$ret_code->fetchAll();
1359
+		$trapId = $this->dbOidIndex[$trapOID]['id'];
1360
+		if ($check_existing === true)
1361
+		{
1362
+			// Get all objects
1363
+			$sql='SELECT * FROM '.$this->db_prefix.'mib_cache_trap_object where trap_id='.$trapId.';';
1364
+			$this->logging->log('SQL query get all traps: '.$sql,DEBUG );
1365
+			if (($ret_code=$db_conn->query($sql)) === false) {
1366
+				$this->logging->log('No result in query : ' . $sql,1,'');
1367
+			}
1368
+			$dbObjectsRaw=$ret_code->fetchAll();
1369 1369
 	        
1370
-	        foreach ($dbObjectsRaw as $val)
1371
-	        {
1372
-	            $dbObjects[$val['object_id']]=1;
1373
-	        }
1374
-	    }
1375
-	    foreach ($objects as $object)
1376
-	    {
1377
-	        $match=$snmptrans=array();
1378
-	        $retVal=0;
1379
-	        $objOid=$objTc=$objDispHint=$objSyntax=$objDesc=$objEnum=NULL;
1380
-	        $tmpdesc='';$indesc=false;
1370
+			foreach ($dbObjectsRaw as $val)
1371
+			{
1372
+				$dbObjects[$val['object_id']]=1;
1373
+			}
1374
+		}
1375
+		foreach ($objects as $object)
1376
+		{
1377
+			$match=$snmptrans=array();
1378
+			$retVal=0;
1379
+			$objOid=$objTc=$objDispHint=$objSyntax=$objDesc=$objEnum=NULL;
1380
+			$tmpdesc='';$indesc=false;
1381 1381
 	        
1382
-	        $objMib=$trapmib;
1383
-	        exec($this->snmptranslate . ' -m ALL -M +'.$this->snmptranslate_dirs.
1384
-	            ' -On -Td '.$objMib.'::'.$object . ' 2>/dev/null',$snmptrans,$retVal);
1385
-	        if ($retVal!=0)
1386
-	        {
1387
-	            // Maybe not trap mib, search with IR
1388
-	            exec($this->snmptranslate . ' -m ALL -M +'.$this->snmptranslate_dirs.
1389
-	                ' -IR '.$object . ' 2>/dev/null',$snmptrans,$retVal);
1390
-	            if ($retVal != 0 || !preg_match('/(.*)::(.*)/',$snmptrans[0],$match))
1391
-	            { // Not found -> continue with warning
1392
-	               $this->logging->log('Error finding trap object : '.$trapmib.'::'.$object,2,'');
1393
-	               continue;
1394
-	            }
1395
-	            $objMib=$match[1];
1382
+			$objMib=$trapmib;
1383
+			exec($this->snmptranslate . ' -m ALL -M +'.$this->snmptranslate_dirs.
1384
+				' -On -Td '.$objMib.'::'.$object . ' 2>/dev/null',$snmptrans,$retVal);
1385
+			if ($retVal!=0)
1386
+			{
1387
+				// Maybe not trap mib, search with IR
1388
+				exec($this->snmptranslate . ' -m ALL -M +'.$this->snmptranslate_dirs.
1389
+					' -IR '.$object . ' 2>/dev/null',$snmptrans,$retVal);
1390
+				if ($retVal != 0 || !preg_match('/(.*)::(.*)/',$snmptrans[0],$match))
1391
+				{ // Not found -> continue with warning
1392
+				   $this->logging->log('Error finding trap object : '.$trapmib.'::'.$object,2,'');
1393
+				   continue;
1394
+				}
1395
+				$objMib=$match[1];
1396 1396
 	            
1397
-	            // Do the snmptranslate again.
1398
-	            exec($this->snmptranslate . ' -m ALL -M +'.$this->snmptranslate_dirs.
1399
-	                ' -On -Td '.$objMib.'::'.$object,$snmptrans,$retVal);
1400
-	            if ($retVal!=0) {
1401
-	                $this->logging->log('Error finding trap object : '.$objMib.'::'.$object,2,'');
1402
-	            }
1397
+				// Do the snmptranslate again.
1398
+				exec($this->snmptranslate . ' -m ALL -M +'.$this->snmptranslate_dirs.
1399
+					' -On -Td '.$objMib.'::'.$object,$snmptrans,$retVal);
1400
+				if ($retVal!=0) {
1401
+					$this->logging->log('Error finding trap object : '.$objMib.'::'.$object,2,'');
1402
+				}
1403 1403
 	            
1404
-	        }
1405
-	        foreach ($snmptrans as $line)
1406
-	        {
1407
-	            if ($indesc===true)
1408
-	            {
1409
-	                $line=preg_replace('/[\t ]+/',' ',$line);
1410
-	                if (preg_match('/(.*)"$/', $line,$match))
1411
-	                {
1412
-	                    $objDesc = $tmpdesc . $match[1];
1413
-	                    $indesc=false;
1414
-	                }
1415
-	                $tmpdesc.=$line;
1416
-	                continue;
1417
-	            }
1418
-	            if (preg_match('/^\.[0-9\.]+$/', $line))
1419
-	            {
1420
-	                $objOid=$line;
1421
-	                continue;
1422
-	            }
1423
-	            if (preg_match('/^[\t ]+SYNTAX[\t ]+([^{]*) \{(.*)\}/',$line,$match))
1424
-	            {
1425
-	                $objSyntax=$match[1];
1426
-                    $objEnum=$match[2];
1427
-	                continue;
1428
-	            }
1429
-	            if (preg_match('/^[\t ]+SYNTAX[\t ]+(.*)/',$line,$match))
1430
-	            {
1431
-	                $objSyntax=$match[1];
1432
-	                continue;
1433
-	            }
1434
-	            if (preg_match('/^[\t ]+DISPLAY-HINT[\t ]+"(.*)"/',$line,$match))
1435
-	            {
1436
-	                $objDispHint=$match[1];
1437
-	                continue;
1438
-	            }
1439
-	            if (preg_match('/^[\t ]+DESCRIPTION[\t ]+"(.*)"/',$line,$match))
1440
-	            {
1441
-	                $objDesc=$match[1];
1442
-	                continue;
1443
-	            }
1444
-	            if (preg_match('/^[\t ]+DESCRIPTION[\t ]+"(.*)/',$line,$match))
1445
-	            {
1446
-	                $tmpdesc=$match[1];
1447
-	                $indesc=true;
1448
-	                continue;
1449
-	            }
1450
-	            if (preg_match('/^[\t ]+-- TEXTUAL CONVENTION[\t ]+(.*)/',$line,$match))
1451
-	            {
1452
-	                $objTc=$match[1];
1453
-	                continue;
1454
-	            }
1455
-	        }
1456
-	        $this->logging->log("Adding trap $object : $objOid / $objSyntax / $objEnum / $objDispHint / $objTc",DEBUG );
1457
-	        //echo "$object : $objOid / $objSyntax / $objEnum / $objDispHint / $objTc / $objDesc\n";
1458
-	        // Update 
1459
-	        $this->update_oid($objOid, $objMib, $object, '3', $objTc, $objDispHint, $objSyntax, $objEnum,$objDesc);
1404
+			}
1405
+			foreach ($snmptrans as $line)
1406
+			{
1407
+				if ($indesc===true)
1408
+				{
1409
+					$line=preg_replace('/[\t ]+/',' ',$line);
1410
+					if (preg_match('/(.*)"$/', $line,$match))
1411
+					{
1412
+						$objDesc = $tmpdesc . $match[1];
1413
+						$indesc=false;
1414
+					}
1415
+					$tmpdesc.=$line;
1416
+					continue;
1417
+				}
1418
+				if (preg_match('/^\.[0-9\.]+$/', $line))
1419
+				{
1420
+					$objOid=$line;
1421
+					continue;
1422
+				}
1423
+				if (preg_match('/^[\t ]+SYNTAX[\t ]+([^{]*) \{(.*)\}/',$line,$match))
1424
+				{
1425
+					$objSyntax=$match[1];
1426
+					$objEnum=$match[2];
1427
+					continue;
1428
+				}
1429
+				if (preg_match('/^[\t ]+SYNTAX[\t ]+(.*)/',$line,$match))
1430
+				{
1431
+					$objSyntax=$match[1];
1432
+					continue;
1433
+				}
1434
+				if (preg_match('/^[\t ]+DISPLAY-HINT[\t ]+"(.*)"/',$line,$match))
1435
+				{
1436
+					$objDispHint=$match[1];
1437
+					continue;
1438
+				}
1439
+				if (preg_match('/^[\t ]+DESCRIPTION[\t ]+"(.*)"/',$line,$match))
1440
+				{
1441
+					$objDesc=$match[1];
1442
+					continue;
1443
+				}
1444
+				if (preg_match('/^[\t ]+DESCRIPTION[\t ]+"(.*)/',$line,$match))
1445
+				{
1446
+					$tmpdesc=$match[1];
1447
+					$indesc=true;
1448
+					continue;
1449
+				}
1450
+				if (preg_match('/^[\t ]+-- TEXTUAL CONVENTION[\t ]+(.*)/',$line,$match))
1451
+				{
1452
+					$objTc=$match[1];
1453
+					continue;
1454
+				}
1455
+			}
1456
+			$this->logging->log("Adding trap $object : $objOid / $objSyntax / $objEnum / $objDispHint / $objTc",DEBUG );
1457
+			//echo "$object : $objOid / $objSyntax / $objEnum / $objDispHint / $objTc / $objDesc\n";
1458
+			// Update 
1459
+			$this->update_oid($objOid, $objMib, $object, '3', $objTc, $objDispHint, $objSyntax, $objEnum,$objDesc);
1460 1460
             
1461
-	        if (isset($dbObjects[$this->dbOidIndex[$objOid]['id']]))
1462
-	        {   // if link exists, continue
1463
-	            $dbObjects[$this->dbOidIndex[$objOid]['id']]=2;
1464
-	            continue;
1465
-	        }
1466
-	        if ($check_existing === true) 
1467
-	        {
1468
-	            // TODO : check link trap - objects exists, mark them.
1469
-	        }
1470
-	        // Associate in object table
1471
-	        $sql='INSERT INTO '.$this->db_prefix.'mib_cache_trap_object (trap_id,object_id) '.
1472
-	   	        'values (:trap_id, :object_id)';	        
1473
-	        $sqlQuery=$db_conn->prepare($sql);	        
1474
-	        $sqlParam=array(
1475
-	            ':trap_id' => $trapId,
1476
-	            ':object_id' => $this->dbOidIndex[$objOid]['id'],
1477
-	        );
1461
+			if (isset($dbObjects[$this->dbOidIndex[$objOid]['id']]))
1462
+			{   // if link exists, continue
1463
+				$dbObjects[$this->dbOidIndex[$objOid]['id']]=2;
1464
+				continue;
1465
+			}
1466
+			if ($check_existing === true) 
1467
+			{
1468
+				// TODO : check link trap - objects exists, mark them.
1469
+			}
1470
+			// Associate in object table
1471
+			$sql='INSERT INTO '.$this->db_prefix.'mib_cache_trap_object (trap_id,object_id) '.
1472
+	   			'values (:trap_id, :object_id)';	        
1473
+			$sqlQuery=$db_conn->prepare($sql);	        
1474
+			$sqlParam=array(
1475
+				':trap_id' => $trapId,
1476
+				':object_id' => $this->dbOidIndex[$objOid]['id'],
1477
+			);
1478 1478
 	        
1479
-	        if ($sqlQuery->execute($sqlParam) === false) {
1480
-	            $this->logging->log('Error adding trap object : ' . $sql . ' / ' . $trapId . '/'. $this->dbOidIndex[$objOid]['id'] ,1,'');
1481
-	        }
1482
-	    }
1483
-	    if ($check_existing === true)
1484
-	    {
1485
-	        // TODO : remove link trap - objects that wasn't marked.
1486
-	    }
1479
+			if ($sqlQuery->execute($sqlParam) === false) {
1480
+				$this->logging->log('Error adding trap object : ' . $sql . ' / ' . $trapId . '/'. $this->dbOidIndex[$objOid]['id'] ,1,'');
1481
+			}
1482
+		}
1483
+		if ($check_existing === true)
1484
+		{
1485
+			// TODO : remove link trap - objects that wasn't marked.
1486
+		}
1487 1487
 	    
1488 1488
 	}
1489 1489
 	
@@ -1493,7 +1493,7 @@  discard block
 block discarded – undo
1493 1493
 	 * @param boolean $check_change : Force check of trap params & objects
1494 1494
 	 * @param boolean $onlyTraps : only cache traps and objects (true) or all (false)
1495 1495
 	 * @param string $startOID : only cache under startOID (NOT IMPLEMENTED)
1496
-	*/	
1496
+	 */	
1497 1497
 	public function update_mib_database($display_progress=false,$check_change=false,$onlyTraps=true,$startOID='.1')
1498 1498
 	{
1499 1499
 		// Timing 
@@ -1545,7 +1545,7 @@  discard block
 block discarded – undo
1545 1545
 		
1546 1546
 		for ($curElement=0;$curElement < $numElements;$curElement++)
1547 1547
 		{
1548
-		    $time_1= microtime(true);
1548
+			$time_1= microtime(true);
1549 1549
 			if ((microtime(true)-$timeFiveSec) > 2 && $display_progress)
1550 1550
 			{ // echo a . every 2 sec
1551 1551
 				echo '.';
@@ -1563,8 +1563,8 @@  discard block
 block discarded – undo
1563 1563
 			// Get oid or pass if not found
1564 1564
 			if (!preg_match('/^\.[0-9\.]+$/',$this->objectsAll[$curElement]))
1565 1565
 			{
1566
-			    $time_parse1 += microtime(true) - $time_1;
1567
-			    $time_parse1N ++;
1566
+				$time_parse1 += microtime(true) - $time_1;
1567
+				$time_parse1N ++;
1568 1568
 				continue;
1569 1569
 			}
1570 1570
 			$oid=$this->objectsAll[$curElement];
@@ -1575,7 +1575,7 @@  discard block
 block discarded – undo
1575 1575
 			if (!preg_match('/ +([^\(]+)\(.+\) type=([0-9]+)( tc=([0-9]+))?( hint=(.+))?/',
1576 1576
 						$this->objectsAll[$curElement],$match))
1577 1577
 			{
1578
-			    $time_check1 += microtime(true) - $time_1;
1578
+				$time_check1 += microtime(true) - $time_1;
1579 1579
 				$time_check1N++;
1580 1580
 				continue;
1581 1581
 			}
@@ -1588,8 +1588,8 @@  discard block
 block discarded – undo
1588 1588
 				// Check if next is suboid -> in that case is cannot be a trap
1589 1589
 				if (preg_match("/^$oid/",$this->objectsAll[$curElement+1]))
1590 1590
 				{
1591
-				    $time_check2 += microtime(true) - $time_1;
1592
-				    $time_check2N++;
1591
+					$time_check2 += microtime(true) - $time_1;
1592
+					$time_check2N++;
1593 1593
 					continue;
1594 1594
 				}		
1595 1595
 				unset($snmptrans);
@@ -1597,8 +1597,8 @@  discard block
 block discarded – undo
1597 1597
 					' -Td '.$oid . ' | grep OBJECTS ',$snmptrans,$retVal);
1598 1598
 				if ($retVal!=0)
1599 1599
 				{
1600
-				    $time_check2 += microtime(true) - $time_1;
1601
-				    $time_check2N++;
1600
+					$time_check2 += microtime(true) - $time_1;
1601
+					$time_check2N++;
1602 1602
 					continue;
1603 1603
 				}
1604 1604
 				//echo "\n v1 trap found : $oid \n";
@@ -1607,7 +1607,7 @@  discard block
 block discarded – undo
1607 1607
 			}
1608 1608
 			if ($onlyTraps===true && $type!=21) // if only traps and not a trap, continue
1609 1609
 			{
1610
-			    $time_check3 += microtime(true) - $time_1;
1610
+				$time_check3 += microtime(true) - $time_1;
1611 1611
 				$time_check3N++;
1612 1612
 				continue;
1613 1613
 			}
@@ -1628,7 +1628,7 @@  discard block
 block discarded – undo
1628 1628
 			
1629 1629
 			if (!preg_match('/^(.*)::/',$snmptrans[0],$match))
1630 1630
 			{
1631
-			    $this->logging->log('Error getting mib from trap '.$oid.' : ' . $snmptrans[0],1,'');
1631
+				$this->logging->log('Error getting mib from trap '.$oid.' : ' . $snmptrans[0],1,'');
1632 1632
 			}
1633 1633
 			$trapMib=$match[1];
1634 1634
 			
@@ -1636,17 +1636,17 @@  discard block
 block discarded – undo
1636 1636
 			while (isset($snmptrans[$numLine]) && !preg_match('/^[\t ]+DESCRIPTION[\t ]+"(.*)/',$snmptrans[$numLine],$match)) $numLine++;
1637 1637
 			if (isset($snmptrans[$numLine]))
1638 1638
 			{
1639
-			    $snmptrans[$numLine] = preg_replace('/^[\t ]+DESCRIPTION[\t ]+"/','',$snmptrans[$numLine]);
1639
+				$snmptrans[$numLine] = preg_replace('/^[\t ]+DESCRIPTION[\t ]+"/','',$snmptrans[$numLine]);
1640 1640
 
1641
-			    while (isset($snmptrans[$numLine]) && !preg_match('/"/',$snmptrans[$numLine]))
1642
-			    {
1643
-			        $trapDesc.=preg_replace('/[\t ]+/',' ',$snmptrans[$numLine]);
1644
-			        $numLine++;
1645
-			    }
1646
-			    if (isset($snmptrans[$numLine])) {
1647
-			        $trapDesc.=preg_replace('/".*/','',$snmptrans[$numLine]);
1648
-			        $trapDesc=preg_replace('/[\t ]+/',' ',$trapDesc);
1649
-			    }
1641
+				while (isset($snmptrans[$numLine]) && !preg_match('/"/',$snmptrans[$numLine]))
1642
+				{
1643
+					$trapDesc.=preg_replace('/[\t ]+/',' ',$snmptrans[$numLine]);
1644
+					$numLine++;
1645
+				}
1646
+				if (isset($snmptrans[$numLine])) {
1647
+					$trapDesc.=preg_replace('/".*/','',$snmptrans[$numLine]);
1648
+					$trapDesc=preg_replace('/[\t ]+/',' ',$trapDesc);
1649
+				}
1650 1650
 
1651 1651
 			}
1652 1652
 			$update=$this->update_oid($oid,$trapMib,$name,$type,NULL,NULL,NULL,NULL,$trapDesc);
@@ -1654,23 +1654,23 @@  discard block
 block discarded – undo
1654 1654
 			
1655 1655
 			if (($update==0) && ($check_change===false))
1656 1656
 			{ // Trapd didn't change & force check disabled
1657
-			    $time_objects += microtime(true) - $time_1;
1658
-			    if ($display_progress) echo "C";
1659
-			    continue;
1657
+				$time_objects += microtime(true) - $time_1;
1658
+				if ($display_progress) echo "C";
1659
+				continue;
1660 1660
 			}
1661 1661
 			
1662 1662
 			$synt=null;
1663 1663
 			foreach ($snmptrans as $line)
1664 1664
 			{	
1665
-    			if (preg_match('/OBJECTS.*\{([^\}]+)\}/',$line,$match))
1666
-    				{
1667
-    					$synt=$match[1];
1668
-    				}
1665
+				if (preg_match('/OBJECTS.*\{([^\}]+)\}/',$line,$match))
1666
+					{
1667
+						$synt=$match[1];
1668
+					}
1669 1669
 			}
1670 1670
 			if ($synt == null) 
1671 1671
 			{
1672 1672
 				//echo "No objects for $trapOID\n";
1673
-			    $time_objects += microtime(true) - $time_1;
1673
+				$time_objects += microtime(true) - $time_1;
1674 1674
 				continue;
1675 1675
 			}
1676 1676
 			//echo "$synt \n";
@@ -1689,18 +1689,18 @@  discard block
 block discarded – undo
1689 1689
 		
1690 1690
 		if ($display_progress)
1691 1691
 		{
1692
-    		echo "\nNumber of processed traps : $time_num_traps \n";
1693
-    		echo "\nParsing : " . number_format($time_parse1+$time_check1,1) ." sec / " . ($time_parse1N+ $time_check1N)  . " occurences\n";
1694
-    		echo "Detecting traps : " . number_format($time_check2+$time_check3,1) . " sec / " . ($time_check2N+$time_check3N) ." occurences\n";
1695
-    		echo "Trap processing ($time_updateN): ".number_format($time_update,1)." sec , ";
1696
-    		echo "Objects processing ($time_objectsN) : ".number_format($time_objects,1)." sec \n";
1692
+			echo "\nNumber of processed traps : $time_num_traps \n";
1693
+			echo "\nParsing : " . number_format($time_parse1+$time_check1,1) ." sec / " . ($time_parse1N+ $time_check1N)  . " occurences\n";
1694
+			echo "Detecting traps : " . number_format($time_check2+$time_check3,1) . " sec / " . ($time_check2N+$time_check3N) ." occurences\n";
1695
+			echo "Trap processing ($time_updateN): ".number_format($time_update,1)." sec , ";
1696
+			echo "Objects processing ($time_objectsN) : ".number_format($time_objects,1)." sec \n";
1697 1697
 		}
1698 1698
 		
1699 1699
 		// Timing ends
1700 1700
 		$timeTaken=microtime(true) - $timeTaken;
1701 1701
 		if ($display_progress)
1702 1702
 		{
1703
-		    echo "Global time : ".round($timeTaken)." seconds\n";
1703
+			echo "Global time : ".round($timeTaken)." seconds\n";
1704 1704
 		}
1705 1705
 		
1706 1706
 	}
Please login to merge, or discard this patch.
library/Trapdirector/TrapsProcess/Mib.php 1 patch
Indentation   +168 added lines, -168 removed lines patch added patch discarded remove patch
@@ -8,186 +8,186 @@
 block discarded – undo
8 8
 class Mib
9 9
 {
10 10
     
11
-    protected $logging; //< logging class
12
-    protected $trapsDB; //< Database class
11
+	protected $logging; //< logging class
12
+	protected $trapsDB; //< Database class
13 13
     
14 14
     
15
-    /**
16
-     * Setup Mib Class
17
-     * @param Logging $logClass : where to log
18
-     * @param Database $dbClass : Database
19
-     */
20
-    function __construct($logClass,$dbClass)
21
-    {
22
-        $this->logging=$logClass;
23
-        $this->trapsDB=$dbClass;       
24
-    }
15
+	/**
16
+	 * Setup Mib Class
17
+	 * @param Logging $logClass : where to log
18
+	 * @param Database $dbClass : Database
19
+	 */
20
+	function __construct($logClass,$dbClass)
21
+	{
22
+		$this->logging=$logClass;
23
+		$this->trapsDB=$dbClass;       
24
+	}
25 25
 
26
-    /** Create database schema
27
-     *	@param $schema_file	string File to read schema from
28
-     *	@param $table_prefix string to replace #PREFIX# in schema file by this
29
-     */
30
-    public function create_schema($schema_file,$table_prefix)
31
-    {
32
-        //Read data from snmptrapd from stdin
33
-        $input_stream=fopen($schema_file, 'r');
26
+	/** Create database schema
27
+	 *	@param $schema_file	string File to read schema from
28
+	 *	@param $table_prefix string to replace #PREFIX# in schema file by this
29
+	 */
30
+	public function create_schema($schema_file,$table_prefix)
31
+	{
32
+		//Read data from snmptrapd from stdin
33
+		$input_stream=fopen($schema_file, 'r');
34 34
         
35
-        if ($input_stream=== false)
36
-        {
37
-            $this->logging->log("Error reading schema !",ERROR,'');
38
-            return;
39
-        }
40
-        $newline='';
41
-        $cur_table='';
42
-        $cur_table_array=array();
43
-        $db_conn=$this->trapsDB->db_connect_trap();
35
+		if ($input_stream=== false)
36
+		{
37
+			$this->logging->log("Error reading schema !",ERROR,'');
38
+			return;
39
+		}
40
+		$newline='';
41
+		$cur_table='';
42
+		$cur_table_array=array();
43
+		$db_conn=$this->trapsDB->db_connect_trap();
44 44
         
45
-        while (($line=fgets($input_stream)) !== false)
46
-        {
47
-            $newline.=chop(preg_replace('/#PREFIX#/',$table_prefix,$line));
48
-            if (preg_match('/; *$/', $newline))
49
-            {
50
-                $sql= $newline;
51
-                if ($db_conn->query($sql) === false) {
52
-                    $this->logging->log('Error create schema : '.$sql,ERROR,'');
53
-                    return;
54
-                }
55
-                if (preg_match('/^ *CREATE TABLE ([^ ]+)/',$newline,$cur_table_array))
56
-                {
57
-                    $cur_table='table '.$cur_table_array[1];
58
-                }
59
-                else
60
-                {
61
-                    $cur_table='secret SQL stuff :-)';
62
-                }
63
-                $this->logging->log('Creating : ' . $cur_table,INFO );
64
-                $newline='';
65
-            }
66
-        }
45
+		while (($line=fgets($input_stream)) !== false)
46
+		{
47
+			$newline.=chop(preg_replace('/#PREFIX#/',$table_prefix,$line));
48
+			if (preg_match('/; *$/', $newline))
49
+			{
50
+				$sql= $newline;
51
+				if ($db_conn->query($sql) === false) {
52
+					$this->logging->log('Error create schema : '.$sql,ERROR,'');
53
+					return;
54
+				}
55
+				if (preg_match('/^ *CREATE TABLE ([^ ]+)/',$newline,$cur_table_array))
56
+				{
57
+					$cur_table='table '.$cur_table_array[1];
58
+				}
59
+				else
60
+				{
61
+					$cur_table='secret SQL stuff :-)';
62
+				}
63
+				$this->logging->log('Creating : ' . $cur_table,INFO );
64
+				$newline='';
65
+			}
66
+		}
67 67
         
68
-        $sql= $newline;
69
-        if ($sql != '' )
70
-        {
71
-            if ($db_conn->query($sql) === false) {
72
-                $this->logging->log('Error create schema : '.$sql,ERROR,'');
73
-                return;
74
-            }
75
-        }
76
-        $this->logging->log('Schema created',INFO);
77
-    }
68
+		$sql= $newline;
69
+		if ($sql != '' )
70
+		{
71
+			if ($db_conn->query($sql) === false) {
72
+				$this->logging->log('Error create schema : '.$sql,ERROR,'');
73
+				return;
74
+			}
75
+		}
76
+		$this->logging->log('Schema created',INFO);
77
+	}
78 78
     
79
-    /**
80
-     * Update database schema from current (as set in db) to $target_version
81
-     *     @param $prefix string file prefix of sql update File
82
-     *     @param $target_version int target db version number
83
-     *     @param $table_prefix string to replace #PREFIX# in schema file by this
84
-     *     @param bool $getmsg : only get messages from version upgrades
85
-     *     @return string : if $getmsg=true, return messages.
86
-     */
87
-    public function update_schema($prefix,$target_version,$table_prefix,$getmsg=false)
88
-    {
89
-        // Get current db number
90
-        $db_conn=$this->trapsDB->db_connect_trap();
91
-        $sql='SELECT id,value from '.$this->db_prefix.'db_config WHERE name=\'db_version\' ';
92
-        $this->logging->log('SQL query : '.$sql,DEBUG );
93
-        if (($ret_code=$db_conn->query($sql)) === false) {
94
-            $this->logging->log('Cannot get db version. Query : ' . $sql,2,'');
95
-            return;
96
-        }
97
-        $version=$ret_code->fetchAll();
98
-        $cur_version=$version[0]['value'];
99
-        $db_version_id=$version[0]['id'];
79
+	/**
80
+	 * Update database schema from current (as set in db) to $target_version
81
+	 *     @param $prefix string file prefix of sql update File
82
+	 *     @param $target_version int target db version number
83
+	 *     @param $table_prefix string to replace #PREFIX# in schema file by this
84
+	 *     @param bool $getmsg : only get messages from version upgrades
85
+	 *     @return string : if $getmsg=true, return messages.
86
+	 */
87
+	public function update_schema($prefix,$target_version,$table_prefix,$getmsg=false)
88
+	{
89
+		// Get current db number
90
+		$db_conn=$this->trapsDB->db_connect_trap();
91
+		$sql='SELECT id,value from '.$this->db_prefix.'db_config WHERE name=\'db_version\' ';
92
+		$this->logging->log('SQL query : '.$sql,DEBUG );
93
+		if (($ret_code=$db_conn->query($sql)) === false) {
94
+			$this->logging->log('Cannot get db version. Query : ' . $sql,2,'');
95
+			return;
96
+		}
97
+		$version=$ret_code->fetchAll();
98
+		$cur_version=$version[0]['value'];
99
+		$db_version_id=$version[0]['id'];
100 100
         
101
-        if ($this->trapsDB->trapDBType == 'pgsql')
102
-        {
103
-            $prefix .= 'update_pgsql/schema_';
104
-        }
105
-        else
106
-        {
107
-            $prefix .= 'update_sql/schema_';
108
-        }
109
-        //echo "version all :\n";print_r($version);echo " \n $cur_ver \n";
110
-        if ($getmsg === true)
111
-        {
112
-            $message='';
113
-            $this->logging->log('getting message for upgrade',DEBUG );
114
-            while($cur_version<$target_version)
115
-            {
116
-                $cur_version++;
117
-                $updateFile=$prefix.'v'.($cur_version-1).'_v'.$cur_version.'.sql';
118
-                $input_stream=fopen($updateFile, 'r');
119
-                if ($input_stream=== false)
120
-                {
121
-                    $this->logging->log("Error reading update file ". $updateFile,2,'');
122
-                    return;
123
-                }
124
-                do { $line=fgets($input_stream); }
125
-                while ($line !== false && !preg_match('/#MESSAGE/',$line));
126
-                if ($line === false)
127
-                {
128
-                    $this->logging->log("No message in file ". $updateFile,2,'');
129
-                    return;
130
-                }
131
-                $message .= ($cur_version-1) . '->' . $cur_version. ' : ' . preg_replace('/#MESSAGE : /','',$line)."\n";
132
-            }
133
-            return $message;
134
-        }
135
-        while($cur_version<$target_version)
136
-        { // tODO : execute pre & post scripts
137
-            $cur_version++;
138
-            $this->logging->log('Updating to version : ' .$cur_version ,INFO );
139
-            $updateFile=$prefix.'v'.($cur_version-1).'_v'.$cur_version.'.sql';
140
-            $input_stream=fopen($updateFile, 'r');
141
-            if ($input_stream=== false)
142
-            {
143
-                $this->logging->log("Error reading update file ". $updateFile,2,'');
144
-                return;
145
-            }
146
-            $newline='';
147
-            $db_conn=$this->trapsDB->db_connect_trap();
148
-            $db_conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
149
-            while (($line=fgets($input_stream)) !== false)
150
-            {
151
-                if (preg_match('/^#/', $line)) continue; // ignore comment lines
152
-                $newline.=chop(preg_replace('/#PREFIX#/',$table_prefix,$line));
153
-                if (preg_match('/; *$/', $newline))
154
-                {
155
-                    $sql_req=$db_conn->prepare($newline);
156
-                    if ($sql_req->execute() === false) {
157
-                        $this->logging->log('Error create schema : '.$newline,1,'');
158
-                    }
159
-                    $cur_table_array=array();
160
-                    if (preg_match('/^ *([^ ]+) TABLE ([^ ]+)/',$newline,$cur_table_array))
161
-                    {
162
-                        $cur_table=$cur_table_array[1] . ' SQL table '.$cur_table_array[2];
163
-                    }
164
-                    else
165
-                    {
166
-                        $cur_table='secret SQL stuff :-)';
167
-                        //$cur_table=$newline;
168
-                    }
169
-                    $this->logging->log('Doing : ' . $cur_table,INFO );
101
+		if ($this->trapsDB->trapDBType == 'pgsql')
102
+		{
103
+			$prefix .= 'update_pgsql/schema_';
104
+		}
105
+		else
106
+		{
107
+			$prefix .= 'update_sql/schema_';
108
+		}
109
+		//echo "version all :\n";print_r($version);echo " \n $cur_ver \n";
110
+		if ($getmsg === true)
111
+		{
112
+			$message='';
113
+			$this->logging->log('getting message for upgrade',DEBUG );
114
+			while($cur_version<$target_version)
115
+			{
116
+				$cur_version++;
117
+				$updateFile=$prefix.'v'.($cur_version-1).'_v'.$cur_version.'.sql';
118
+				$input_stream=fopen($updateFile, 'r');
119
+				if ($input_stream=== false)
120
+				{
121
+					$this->logging->log("Error reading update file ". $updateFile,2,'');
122
+					return;
123
+				}
124
+				do { $line=fgets($input_stream); }
125
+				while ($line !== false && !preg_match('/#MESSAGE/',$line));
126
+				if ($line === false)
127
+				{
128
+					$this->logging->log("No message in file ". $updateFile,2,'');
129
+					return;
130
+				}
131
+				$message .= ($cur_version-1) . '->' . $cur_version. ' : ' . preg_replace('/#MESSAGE : /','',$line)."\n";
132
+			}
133
+			return $message;
134
+		}
135
+		while($cur_version<$target_version)
136
+		{ // tODO : execute pre & post scripts
137
+			$cur_version++;
138
+			$this->logging->log('Updating to version : ' .$cur_version ,INFO );
139
+			$updateFile=$prefix.'v'.($cur_version-1).'_v'.$cur_version.'.sql';
140
+			$input_stream=fopen($updateFile, 'r');
141
+			if ($input_stream=== false)
142
+			{
143
+				$this->logging->log("Error reading update file ". $updateFile,2,'');
144
+				return;
145
+			}
146
+			$newline='';
147
+			$db_conn=$this->trapsDB->db_connect_trap();
148
+			$db_conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
149
+			while (($line=fgets($input_stream)) !== false)
150
+			{
151
+				if (preg_match('/^#/', $line)) continue; // ignore comment lines
152
+				$newline.=chop(preg_replace('/#PREFIX#/',$table_prefix,$line));
153
+				if (preg_match('/; *$/', $newline))
154
+				{
155
+					$sql_req=$db_conn->prepare($newline);
156
+					if ($sql_req->execute() === false) {
157
+						$this->logging->log('Error create schema : '.$newline,1,'');
158
+					}
159
+					$cur_table_array=array();
160
+					if (preg_match('/^ *([^ ]+) TABLE ([^ ]+)/',$newline,$cur_table_array))
161
+					{
162
+						$cur_table=$cur_table_array[1] . ' SQL table '.$cur_table_array[2];
163
+					}
164
+					else
165
+					{
166
+						$cur_table='secret SQL stuff :-)';
167
+						//$cur_table=$newline;
168
+					}
169
+					$this->logging->log('Doing : ' . $cur_table,INFO );
170 170
                     
171
-                    $newline='';
172
-                }
173
-            }
174
-            fclose($input_stream);
171
+					$newline='';
172
+				}
173
+			}
174
+			fclose($input_stream);
175 175
             
176
-            //$sql= $newline;
177
-            //if ($db_conn->query($sql) === false) {
178
-            //    $this->logging->log('Error updating schema : '.$sql,1,'');
179
-            //}
176
+			//$sql= $newline;
177
+			//if ($db_conn->query($sql) === false) {
178
+			//    $this->logging->log('Error updating schema : '.$sql,1,'');
179
+			//}
180 180
             
181
-            $sql='UPDATE '.$this->db_prefix.'db_config SET value='.$cur_version.' WHERE ( id = '.$db_version_id.' )';
182
-            $this->logging->log('SQL query : '.$sql,DEBUG );
183
-            if ($db_conn->query($sql) === false) {
184
-                $this->logging->log('Cannot update db version. Query : ' . $sql,2);
185
-                return;
186
-            }
181
+			$sql='UPDATE '.$this->db_prefix.'db_config SET value='.$cur_version.' WHERE ( id = '.$db_version_id.' )';
182
+			$this->logging->log('SQL query : '.$sql,DEBUG );
183
+			if ($db_conn->query($sql) === false) {
184
+				$this->logging->log('Cannot update db version. Query : ' . $sql,2);
185
+				return;
186
+			}
187 187
             
188
-            $this->logging->log('Schema updated to version : '.$cur_version ,INFO);
189
-        }
190
-    }
188
+			$this->logging->log('Schema updated to version : '.$cur_version ,INFO);
189
+		}
190
+	}
191 191
     
192 192
     
193 193
     
Please login to merge, or discard this patch.