GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Completed
Push — master ( e39801...b79b58 )
by Marco
03:51
created
lookup.php 1 patch
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -11,7 +11,7 @@
 block discarded – undo
11 11
 <h1> DNSBL Lookup</h1> 
12 12
 <?php
13 13
 
14
-$_POST['Value'] = str_replace('_','.',array_keys($_GET)[0]);
14
+$_POST['Value'] = str_replace('_', '.', array_keys($_GET)[0]);
15 15
 $_POST['genere'] = 'Spam IP';
16 16
 require_once('result.php');
17 17
 ?>
Please login to merge, or discard this patch.
contrib/ipImap/function.php 4 patches
Doc Comments   +23 added lines patch added patch discarded remove patch
@@ -1,4 +1,7 @@  discard block
 block discarded – undo
1 1
 <?php
2
+/**
3
+ * @param string $header
4
+ */
2 5
 function getIP($header,$mxserver,$msa) {
3 6
 /* Get submission server's IP from header's mail */
4 7
 /* Each line must end with /r/n			 */
@@ -28,11 +31,24 @@  discard block
 block discarded – undo
28 31
 	return array($ip,$host,$dateR,$dateC['date'],$mid['mid']);
29 32
 }
30 33
 
34
+/**
35
+ * @param string|false $ip
36
+ * @param string $hostname
37
+ * @param string $dateC
38
+ * @param string|null $msgid
39
+ * @param string|false $dateL
40
+ */
31 41
 function updateReport ($ip,$uid,$ipcount,$uidcount,$hostname,$dateC,$msgid,$dateL) {
32 42
 
33 43
 	return sprintf ('<tr><td nowrap>%s</td><td nowrap>%s</td><td>%s</td><td>%s</td><td>%u</td><td>%u</td><td>%s</td><td>%s</td></tr>'."\n",$dateL,$dateC,$uid,$ip,$uidcount,$ipcount,$hostname,htmlentities($msgid) );
34 44
 }
35 45
 
46
+/**
47
+ * @param string $dateC
48
+ * @param string|null $msgid
49
+ * @param false|string $dateL
50
+ * @param string $text
51
+ */
36 52
 function updatebadReport ( $uid,$dateC,$msgid,$dateL,$text ) {
37 53
 	return sprintf ('<tr><td nowrap>%s</td><td nowrap>%s</td><td>%s</td><td>%s</td><td nowrap>%s</td></tr>'."\n",$dateL,$dateC,$uid,htmlentities($msgid),$text );
38 54
 }
@@ -84,6 +100,9 @@  discard block
 block discarded – undo
84 100
 }
85 101
 
86 102
 
103
+/**
104
+ * @param null|mysqli $myconn
105
+ */
87 106
 function summaryReportAndList ($cf,$myconn,$tables,$category,$ipvet) {
88 107
 	$nips = $ipvet['count'];
89 108
 
@@ -154,6 +173,10 @@  discard block
 block discarded – undo
154 173
 }
155 174
 
156 175
 
176
+/**
177
+ * @param string $message_id
178
+ * @param string $date
179
+ */
157 180
 function splunksearch ($service,$message_id,$date) {
158 181
 
159 182
 	// Run a blocking search
Please login to merge, or discard this patch.
Indentation   +125 added lines, -125 removed lines patch added patch discarded remove patch
@@ -12,14 +12,14 @@  discard block
 block discarded – undo
12 12
 #			print "Examine ".$received[0][$i]."\n";
13 13
 			if ( preg_match($msa,$received['host'][$i]) )
14 14
 				$dateR = $received['date'][$i];
15
-        		foreach ($mxserver as $mx) {
16
-        			if (!$ip)
15
+				foreach ($mxserver as $mx) {
16
+					if (!$ip)
17 17
 					if ($mx == $received['host'][$i]) {
18 18
 						$host = $received['host'][$i];
19 19
 						$ip = $received['ip'][$i];
20
-                    			}
21
-                	}
22
-        	}
20
+								}
21
+					}
22
+			}
23 23
 	}
24 24
 	if ( preg_match ('/\r\nDate:\s(?P<date>.*)\r\n/',$header,$dateC) != 1)
25 25
 		$dateC['date'] = 'Not found';
@@ -39,15 +39,15 @@  discard block
 block discarded – undo
39 39
 
40 40
 
41 41
 function summaryBadReport ($uidvet) {
42
-        $nuid = $uidvet['count'];
43
-        if ( empty($uidvet) ) return NULL;
44
-        $return = '<hr><h3>Statistics by UID</h3><table><tr><th>UID</th><th>Learned times</th></tr>'."\n";
42
+		$nuid = $uidvet['count'];
43
+		if ( empty($uidvet) ) return NULL;
44
+		$return = '<hr><h3>Statistics by UID</h3><table><tr><th>UID</th><th>Learned times</th></tr>'."\n";
45 45
 
46
-        /* Remove count index */
47
-        $uids = array_keys($uidvet['uid']);
46
+		/* Remove count index */
47
+		$uids = array_keys($uidvet['uid']);
48 48
 	$totlearn = 0;
49 49
 
50
-        foreach ( $uids as $uid ) {
50
+		foreach ( $uids as $uid ) {
51 51
 		$totlearn += $uidvet['uid']["$uid"]['count'];; 
52 52
 		$return .= sprintf ('<tr><td>%s</td><td>%u</td></tr>',$uid,$uidvet['uid']["$uid"]['count']);
53 53
 	}
@@ -60,26 +60,26 @@  discard block
 block discarded – undo
60 60
 
61 61
 function array_msort($array, $cols)
62 62
 {
63
-    $colarr = array();
64
-    foreach ($cols as $col => $order) {
65
-        $colarr[$col] = array();
66
-        foreach ($array as $k => $row) { $colarr[$col]['_'.$k] = strtolower($row[$col]); }
67
-    }
68
-    $eval = 'array_multisort(';
69
-    foreach ($cols as $col => $order) {
70
-        $eval .= '$colarr[\''.$col.'\'],'.$order.',';
71
-    }
72
-    $eval = substr($eval,0,-1).');';
73
-    eval($eval);
74
-    $ret = array();
75
-    foreach ($colarr as $col => $arr) {
76
-        foreach ($arr as $k => $v) {
77
-            $k = substr($k,1);
78
-            if (!isset($ret[$k])) $ret[$k] = $array[$k];
79
-            if (isset ($array[$k][$col])) $ret[$k][$col] = $array[$k][$col];
80
-        }
81
-    }
82
-    return $ret;
63
+	$colarr = array();
64
+	foreach ($cols as $col => $order) {
65
+		$colarr[$col] = array();
66
+		foreach ($array as $k => $row) { $colarr[$col]['_'.$k] = strtolower($row[$col]); }
67
+	}
68
+	$eval = 'array_multisort(';
69
+	foreach ($cols as $col => $order) {
70
+		$eval .= '$colarr[\''.$col.'\'],'.$order.',';
71
+	}
72
+	$eval = substr($eval,0,-1).');';
73
+	eval($eval);
74
+	$ret = array();
75
+	foreach ($colarr as $col => $arr) {
76
+		foreach ($arr as $k => $v) {
77
+			$k = substr($k,1);
78
+			if (!isset($ret[$k])) $ret[$k] = $array[$k];
79
+			if (isset ($array[$k][$col])) $ret[$k][$col] = $array[$k][$col];
80
+		}
81
+	}
82
+	return $ret;
83 83
 
84 84
 }
85 85
 
@@ -94,8 +94,8 @@  discard block
 block discarded – undo
94 94
 
95 95
 	foreach ( $ips as $ip ) {
96 96
 		if ( $ip == 'count' ) continue;
97
-                $nlearn = $ipvet['ip']["$ip"]['count'];
98
-                unset($ipvet['ip']["$ip"]['count']);
97
+				$nlearn = $ipvet['ip']["$ip"]['count'];
98
+				unset($ipvet['ip']["$ip"]['count']);
99 99
 		$quantity = $cf['quantity']["$category"]; /* In searchAndList this value is passed by reference and modified */
100 100
 		$nuid = count($ipvet['ip']["$ip"]);
101 101
 		if ( !$cf['onlyReport'] ) {
@@ -123,9 +123,9 @@  discard block
 block discarded – undo
123 123
 		$return .='<tr><td rowspan="'.$nuid.'">'.$ip.'</td>';
124 124
 		$return .= sprintf ('<td>%s</td><td rowspan="'.$nuid.'">%u</td><td rowspan="'.$nuid.'" '.$nowlist["$listed"]['style'].'>%s</td></tr>',$ipvet['ip']["$ip"][0],$nlearn,$nowlist["$listed"]['name']);
125 125
 		$rowuid=NULL;
126
-                for ($j=1;$j<$nuid;$j++) $rowuid .= '<tr><td>%s</td></tr>';
126
+				for ($j=1;$j<$nuid;$j++) $rowuid .= '<tr><td>%s</td></tr>';
127 127
 		array_shift($ipvet['ip']["$ip"]);
128
-                $return .= vsprintf ($rowuid,$ipvet['ip']["$ip"]);
128
+				$return .= vsprintf ($rowuid,$ipvet['ip']["$ip"]);
129 129
 
130 130
 	}
131 131
 	$return .= sprintf ('<tr><th title="unique ips">%u</th><th title="unique uids">%u</th><th>%u</th></table>',$ipvet['ip']['count'],$ipvet['uid']['count'],$nips);
@@ -135,20 +135,20 @@  discard block
 block discarded – undo
135 135
 	/* Not used for listing purpose, but useful to you! */
136 136
 	$return .= '<h3>Statistics by UID</h3><table><tr><th>UID</th><th>IP learned</th><th>Learned times</th></tr>'."\n";
137 137
 	$uids = array_keys($ipvet['uid']);
138
-        foreach ( $uids as $uid ) {
138
+		foreach ( $uids as $uid ) {
139 139
 		if ( $uid == 'count' ) continue;	
140
-	        $nlearn = $ipvet['uid']["$uid"]['count'];
141
-	        unset ( $ipvet['uid']["$uid"]['count'] );
140
+			$nlearn = $ipvet['uid']["$uid"]['count'];
141
+			unset ( $ipvet['uid']["$uid"]['count'] );
142 142
 		$nip = count($ipvet['uid']["$uid"]);
143 143
 		$return .='<tr><td rowspan="'.$nip.'">'.$uid.'</td>';
144 144
 		$return .= sprintf ('<td>%s</td><td rowspan="'.$nip.'">%u</td></tr>',$ipvet['uid']["$uid"][0],$nlearn);
145
-                $rowuid=NULL;
146
-                for ($j=1;$j<$nip;$j++) $rowuid .= '<tr><td>%s</td></tr>';
147
-                array_shift($ipvet['uid']["$uid"]);
148
-                $return .= vsprintf ($rowuid,$ipvet['uid']["$uid"]);
145
+				$rowuid=NULL;
146
+				for ($j=1;$j<$nip;$j++) $rowuid .= '<tr><td>%s</td></tr>';
147
+				array_shift($ipvet['uid']["$uid"]);
148
+				$return .= vsprintf ($rowuid,$ipvet['uid']["$uid"]);
149 149
 
150
-        }
151
-        $return .= sprintf ('<tr><th title="unique uids">%u</th><th title="unique ips">%u</th><th>%u</th></table>',$ipvet['uid']['count'],$ipvet['ip']['count'],$nips);	
150
+		}
151
+		$return .= sprintf ('<tr><th title="unique uids">%u</th><th title="unique ips">%u</th><th>%u</th></table>',$ipvet['uid']['count'],$ipvet['ip']['count'],$nips);	
152 152
 
153 153
 
154 154
 	return $return;
@@ -176,50 +176,50 @@  discard block
 block discarded – undo
176 176
 	*/
177 177
 
178 178
 	// A one shot search
179
-        $searchParams = array(
180
-                'earliest_time' => date("c",strtotime ($date)-120),
181
-                'latest_time' => date("c",strtotime ($date)+60)
182
-        );
179
+		$searchParams = array(
180
+				'earliest_time' => date("c",strtotime ($date)-120),
181
+				'latest_time' => date("c",strtotime ($date)+60)
182
+		);
183 183
 
184
-        // Run a oneshot search that returns the job's results
185
-        $resultsStream = $service->oneshotSearch($searchQueryBlocking, $searchParams);
186
-        $resultSearch = new Splunk_ResultsReader($resultsStream);
184
+		// Run a oneshot search that returns the job's results
185
+		$resultsStream = $service->oneshotSearch($searchQueryBlocking, $searchParams);
186
+		$resultSearch = new Splunk_ResultsReader($resultsStream);
187 187
 
188 188
 	// Use the built-in XML parser to display the job results
189 189
 	foreach ($resultSearch as $result)
190 190
 	  {
191
-	    if ($result instanceof Splunk_ResultsFieldOrder)
192
-	    {
193
-	      // More than one field attribute returned by search
194
-	      // You must redefine the search
195
-	      if ( count($result->getFieldNames()) > 1 ) return FALSE;
196
-	    }
197
-	    else if ($result instanceof Splunk_ResultsMessage)
198
-	    {
199
-	      // I don't want messages in my search
200
-	      return FALSE;
201
-	    }
202
-	    else if (is_array($result))
203
-	    {
204
-	      // Process a row
205
-	      foreach ($result as $key => $valueOrValues)
206
-	        {
207
-	         if (is_array($valueOrValues))
208
-	          {
209
-	            return FALSE;
210
-	          }
211
-	         else
212
-	          {
213
-	            return $valueOrValues;
214
-	            #print "  {$key} => {$value}\r\n";
215
-	          }
216
-	        }
217
-	    }
218
-	    else
219
-	    {
220
-	      #print "Unknow result type";
221
-	      return FALSE;
222
-	    }
191
+		if ($result instanceof Splunk_ResultsFieldOrder)
192
+		{
193
+		  // More than one field attribute returned by search
194
+		  // You must redefine the search
195
+		  if ( count($result->getFieldNames()) > 1 ) return FALSE;
196
+		}
197
+		else if ($result instanceof Splunk_ResultsMessage)
198
+		{
199
+		  // I don't want messages in my search
200
+		  return FALSE;
201
+		}
202
+		else if (is_array($result))
203
+		{
204
+		  // Process a row
205
+		  foreach ($result as $key => $valueOrValues)
206
+			{
207
+			 if (is_array($valueOrValues))
208
+			  {
209
+				return FALSE;
210
+			  }
211
+			 else
212
+			  {
213
+				return $valueOrValues;
214
+				#print "  {$key} => {$value}\r\n";
215
+			  }
216
+			}
217
+		}
218
+		else
219
+		{
220
+		  #print "Unknow result type";
221
+		  return FALSE;
222
+		}
223 223
 	  }
224 224
 }
225 225
 
@@ -228,26 +228,26 @@  discard block
 block discarded – undo
228 228
 	$file = dirname(__FILE__) . '/' . $cf['reportFile']["$type"];
229 229
 	$fileb= dirname(__FILE__) . '/' . $cf['badreportFile']["$type"];
230 230
 	$m_mail = imap_open('{'.$cf['mailhost'].':143/imap/novalidate-cert/authuser='.$cf['authuser'].'}'.$cf['folder']["$type"], $cf['account'],$cf['authpassword'], OP_READONLY)
231
-        	or syslog (LOG_EMERG, $cf['user'].': Error in IMAP connection to <'.$cf['mailhost'].'>: ' . imap_last_error());
231
+			or syslog (LOG_EMERG, $cf['user'].': Error in IMAP connection to <'.$cf['mailhost'].'>: ' . imap_last_error());
232 232
 	if ( !$m_mail ) exit(254);
233 233
 		
234 234
 
235 235
 	syslog (LOG_INFO,$cf['user'].': Successfully connected to <'.$cf['mailhost'].">; Reading $type messages of last ".$cf['oldestday'].' days...');
236 236
 	//get all messages
237 237
 	$dateTh = date ( "d-M-Y", strToTime ( '-'.$cf['oldestday'].' days' ) );
238
-        $dateN  = date ( "d-M-Y", strToTime ( "now" ) );
239
-        $m_search=imap_search ($m_mail, "SINCE \"$dateTh\" BEFORE \"$dateN\"" );
238
+		$dateN  = date ( "d-M-Y", strToTime ( "now" ) );
239
+		$m_search=imap_search ($m_mail, "SINCE \"$dateTh\" BEFORE \"$dateN\"" );
240 240
 
241 241
 
242 242
 	// Order results starting from newest message
243 243
 	if ( empty($m_search) ) {
244 244
 		syslog (LOG_INFO,$cf['user'].": No mail found in $type folder. No reports written for $type.");
245
-	        if ( $ierr = imap_errors() )
246
-	                foreach ( $ierr as $thiserr )
247
-	                        syslog (LOG_ERR, $cf['user'].": IMAP Error: $thiserr");
248
-	        if ( $ierr = imap_alerts() )
249
-	                foreach ( $ierr as $thiserr )
250
-	                        syslog (LOG_ALERT, $cf['user'].": IMAP Alert: $thiserr");
245
+			if ( $ierr = imap_errors() )
246
+					foreach ( $ierr as $thiserr )
247
+							syslog (LOG_ERR, $cf['user'].": IMAP Error: $thiserr");
248
+			if ( $ierr = imap_alerts() )
249
+					foreach ( $ierr as $thiserr )
250
+							syslog (LOG_ALERT, $cf['user'].": IMAP Alert: $thiserr");
251 251
 		imap_close( $m_mail );
252 252
 		if ( file_exists( $file ) ) unlink ($file);
253 253
 		if ( file_exists( $fileb ) ) unlink ($fileb);
@@ -280,16 +280,16 @@  discard block
 block discarded – undo
280 280
 	$uidbad['count'] = 0;
281 281
 	$uidbad['uid'] = array();
282 282
 
283
-        // loop for each message
283
+		// loop for each message
284 284
 	foreach ($m_search as $onem) {
285 285
 
286
-	        //get imap header info for obj thang
287
-	        //$headers = imap_headerinfo($m_mail, $onem);
288
-	        //$head = imap_fetchheader($m_mail, $headers->Msgno);
286
+			//get imap header info for obj thang
287
+			//$headers = imap_headerinfo($m_mail, $onem);
288
+			//$head = imap_fetchheader($m_mail, $headers->Msgno);
289 289
 		$head = imap_fetchheader($m_mail, $onem );
290
-	        //$obj = imap_rfc822_parse_headers( $head);
290
+			//$obj = imap_rfc822_parse_headers( $head);
291 291
 
292
-	        list ($ip,$host,$dateReceived,$dateClient,$mid) =  getIP( $head,$cf['mx'],$cf['msalearn'] );
292
+			list ($ip,$host,$dateReceived,$dateClient,$mid) =  getIP( $head,$cf['mx'],$cf['msalearn'] );
293 293
 		if (empty($mid)) {
294 294
 			$uid='NA';
295 295
 			syslog (LOG_ERR, $cf['user'].": Error retrieving data for empty Message-ID.");
@@ -304,11 +304,11 @@  discard block
 block discarded – undo
304 304
 				}
305 305
 		}
306 306
 
307
-	        /* Update count of each ip */
308
-	        if ($host and ($uid!='NA') and ($uid!='unauthenticated') and ($uid!='unknown')) { /* IP is received by MX servers  and learned by valid uid */
307
+			/* Update count of each ip */
308
+			if ($host and ($uid!='NA') and ($uid!='unauthenticated') and ($uid!='unknown')) { /* IP is received by MX servers  and learned by valid uid */
309 309
 			$ipuid['count']++;					//number of right messages
310 310
 
311
-	                if (in_array($uid,array_keys($ipuid['uid']))) {
311
+					if (in_array($uid,array_keys($ipuid['uid']))) {
312 312
 				$ipuid['uid']["$uid"]['count']++;		//number of learn by this uid
313 313
 				if (!in_array($ip,$ipuid['uid']["$uid"])) 
314 314
 					$ipuid['uid']["$uid"][]=$ip;		//ips learned by this uid
@@ -319,29 +319,29 @@  discard block
 block discarded – undo
319 319
 				$ipuid['uid']['count']++;                	//number of unique uids
320 320
 			}
321 321
 
322
-                        if (in_array($ip,array_keys($ipuid['ip']))) {
323
-                                $ipuid['ip']["$ip"]['count']++;			//number of time this ip appears in different messages
322
+						if (in_array($ip,array_keys($ipuid['ip']))) {
323
+								$ipuid['ip']["$ip"]['count']++;			//number of time this ip appears in different messages
324 324
 				if (!in_array($uid,$ipuid['ip']["$ip"]))
325 325
 					$ipuid['ip']["$ip"][]=$uid;		//uids that learned this ip
326 326
 			}
327
-                        else {
328
-                                $ipuid['ip']["$ip"]['count'] = 1;
327
+						else {
328
+								$ipuid['ip']["$ip"]['count'] = 1;
329 329
 				$ipuid['ip']["$ip"][]=$uid;
330 330
 				$ipuid['ip']['count']++;			//number of unique ips
331
-                        }
331
+						}
332 332
 
333
-	        	/* Update HTML report */
334
-	        	fwrite($fp,updateReport ( $ip,$uid,$ipuid['ip']["$ip"]['count'],$ipuid['uid']["$uid"]['count'],$host,$dateClient,$mid,$dateReceived) );
333
+				/* Update HTML report */
334
+				fwrite($fp,updateReport ( $ip,$uid,$ipuid['ip']["$ip"]['count'],$ipuid['uid']["$uid"]['count'],$host,$dateClient,$mid,$dateReceived) );
335 335
 		}
336
-	        else {	/* Bad learn */
336
+			else {	/* Bad learn */
337 337
 			
338
-                        if (in_array($uid,array_keys($uidbad['uid']))) 
339
-                                $uidbad['uid']["$uid"]['count']++;               //number of bad learn by this uid
340
-                        else {
341
-                                $uidbad['uid']["$uid"]['count'] = 1;
338
+						if (in_array($uid,array_keys($uidbad['uid']))) 
339
+								$uidbad['uid']["$uid"]['count']++;               //number of bad learn by this uid
340
+						else {
341
+								$uidbad['uid']["$uid"]['count'] = 1;
342 342
 				$uidbad['uid']["$uid"][]=$uid;
343
-                                $uidbad['count']++;                       //numeber of unique bad uids
344
-                        }
343
+								$uidbad['count']++;                       //numeber of unique bad uids
344
+						}
345 345
 			/* The reason of bad report */
346 346
 			if ($host === FALSE) $reason = 'This mail was not received by recognized MX host';
347 347
 			if ($dateReceived === FALSE) $reason = 'This mail was not submitted to recognized MSA for learn';
@@ -363,17 +363,17 @@  discard block
 block discarded – undo
363 363
 	fwrite($fp, '</table>');
364 364
 	fwrite($fp, '<hr><h2>Summary Report</h2><h5>Listing policy: ip must be learned at least '.$cf['thresholdip']["$type"].' times from at least '.$cf['thresholduid']["$type"].' different valid uids.</h5>' );
365 365
 
366
-        /* Make MYSQL connection */
366
+		/* Make MYSQL connection */
367 367
 	if ( $cf['onlyReport'] )
368 368
 		$mysqli = NULL;
369 369
 	else {
370
-        	$mysqli = new mysqli($myconnArray['dbhost'], $myconnArray['userdb'], $myconnArray['pwd'], $myconnArray['db'], $myconnArray['dbport']);
371
-        	if ($mysqli->connect_error) {
372
-                	syslog (LOG_EMERG, $cf['user'].': Connect Error (' . $mysqli->connect_errno . ') '
373
-                	. $mysqli->connect_error);
374
-                	exit (254);
375
-        	}
376
-        	syslog(LOG_INFO, $cf['user'].': Successfully mysql connected to ' . $mysqli->host_info) ;
370
+			$mysqli = new mysqli($myconnArray['dbhost'], $myconnArray['userdb'], $myconnArray['pwd'], $myconnArray['db'], $myconnArray['dbport']);
371
+			if ($mysqli->connect_error) {
372
+					syslog (LOG_EMERG, $cf['user'].': Connect Error (' . $mysqli->connect_errno . ') '
373
+					. $mysqli->connect_error);
374
+					exit (254);
375
+			}
376
+			syslog(LOG_INFO, $cf['user'].': Successfully mysql connected to ' . $mysqli->host_info) ;
377 377
 	}
378 378
 	/***********************/
379 379
 
@@ -393,8 +393,8 @@  discard block
 block discarded – undo
393 393
 		foreach ( $ierr as $thiserr )
394 394
 			syslog (LOG_ERR, $cf['user'].": IMAP Error: $thiserr");
395 395
 	if ( $ierr = imap_alerts() )
396
-                foreach ( $ierr as $thiserr )
397
-                        syslog (LOG_ALERT, $cf['user'].": IMAP Alert: $thiserr");
396
+				foreach ( $ierr as $thiserr )
397
+						syslog (LOG_ALERT, $cf['user'].": IMAP Alert: $thiserr");
398 398
 	imap_close($m_mail);
399 399
 }
400 400
 ?>
Please login to merge, or discard this patch.
Spacing   +132 added lines, -132 removed lines patch added patch discarded remove patch
@@ -1,5 +1,5 @@  discard block
 block discarded – undo
1 1
 <?php
2
-function getIP($header,$mxserver,$msa) {
2
+function getIP($header, $mxserver, $msa) {
3 3
 /* Get submission server's IP from header's mail */
4 4
 /* Each line must end with /r/n			 */
5 5
 /* IP is the first one written by your mxserver	 */
@@ -7,10 +7,10 @@  discard block
 block discarded – undo
7 7
 	$ip = FALSE;
8 8
 	$host = FALSE;
9 9
 	$dateR = FALSE;
10
-	if ( preg_match_all('/^Received:\sfrom(?:.|\r\n\s)*?[\[\(]\s*(?P<ip>\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})[\]\)](?:.|\r\n\s)+\s+by(?:\s|\r\n\s+)(?P<host>\S+).*(?:\s|\r\n\s\s)+.*;\s+(?P<date>.*)/m',$header,$received) ) {
11
-		for ($i = count($received[0])-1;$i>=0;$i--) {
10
+	if (preg_match_all('/^Received:\sfrom(?:.|\r\n\s)*?[\[\(]\s*(?P<ip>\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})[\]\)](?:.|\r\n\s)+\s+by(?:\s|\r\n\s+)(?P<host>\S+).*(?:\s|\r\n\s\s)+.*;\s+(?P<date>.*)/m', $header, $received)) {
11
+		for ($i = count($received[0])-1; $i>=0; $i--) {
12 12
 #			print "Examine ".$received[0][$i]."\n";
13
-			if ( preg_match($msa,$received['host'][$i]) )
13
+			if (preg_match($msa, $received['host'][$i]))
14 14
 				$dateR = $received['date'][$i];
15 15
         		foreach ($mxserver as $mx) {
16 16
         			if (!$ip)
@@ -21,38 +21,38 @@  discard block
 block discarded – undo
21 21
                 	}
22 22
         	}
23 23
 	}
24
-	if ( preg_match ('/\r\nDate:\s(?P<date>.*)\r\n/',$header,$dateC) != 1)
24
+	if (preg_match('/\r\nDate:\s(?P<date>.*)\r\n/', $header, $dateC) != 1)
25 25
 		$dateC['date'] = 'Not found';
26
-	if ( preg_match ('/\r\nMessage\-I(?:D|d):\s(?P<mid>.*)\r\n/',$header,$mid) != 1)
26
+	if (preg_match('/\r\nMessage\-I(?:D|d):\s(?P<mid>.*)\r\n/', $header, $mid) != 1)
27 27
 		$mid['mid'] = NULL;
28
-	return array($ip,$host,$dateR,$dateC['date'],$mid['mid']);
28
+	return array($ip, $host, $dateR, $dateC['date'], $mid['mid']);
29 29
 }
30 30
 
31
-function updateReport ($ip,$uid,$ipcount,$uidcount,$hostname,$dateC,$msgid,$dateL) {
31
+function updateReport($ip, $uid, $ipcount, $uidcount, $hostname, $dateC, $msgid, $dateL) {
32 32
 
33
-	return sprintf ('<tr><td nowrap>%s</td><td nowrap>%s</td><td>%s</td><td>%s</td><td>%u</td><td>%u</td><td>%s</td><td>%s</td></tr>'."\n",$dateL,$dateC,$uid,$ip,$uidcount,$ipcount,$hostname,htmlentities($msgid) );
33
+	return sprintf('<tr><td nowrap>%s</td><td nowrap>%s</td><td>%s</td><td>%s</td><td>%u</td><td>%u</td><td>%s</td><td>%s</td></tr>'."\n", $dateL, $dateC, $uid, $ip, $uidcount, $ipcount, $hostname, htmlentities($msgid));
34 34
 }
35 35
 
36
-function updatebadReport ( $uid,$dateC,$msgid,$dateL,$text ) {
37
-	return sprintf ('<tr><td nowrap>%s</td><td nowrap>%s</td><td>%s</td><td>%s</td><td nowrap>%s</td></tr>'."\n",$dateL,$dateC,$uid,htmlentities($msgid),$text );
36
+function updatebadReport($uid, $dateC, $msgid, $dateL, $text) {
37
+	return sprintf('<tr><td nowrap>%s</td><td nowrap>%s</td><td>%s</td><td>%s</td><td nowrap>%s</td></tr>'."\n", $dateL, $dateC, $uid, htmlentities($msgid), $text);
38 38
 }
39 39
 
40 40
 
41
-function summaryBadReport ($uidvet) {
41
+function summaryBadReport($uidvet) {
42 42
         $nuid = $uidvet['count'];
43
-        if ( empty($uidvet) ) return NULL;
43
+        if (empty($uidvet)) return NULL;
44 44
         $return = '<hr><h3>Statistics by UID</h3><table><tr><th>UID</th><th>Learned times</th></tr>'."\n";
45 45
 
46 46
         /* Remove count index */
47 47
         $uids = array_keys($uidvet['uid']);
48 48
 	$totlearn = 0;
49 49
 
50
-        foreach ( $uids as $uid ) {
51
-		$totlearn += $uidvet['uid']["$uid"]['count'];; 
52
-		$return .= sprintf ('<tr><td>%s</td><td>%u</td></tr>',$uid,$uidvet['uid']["$uid"]['count']);
50
+        foreach ($uids as $uid) {
51
+		$totlearn += $uidvet['uid']["$uid"]['count']; ; 
52
+		$return .= sprintf('<tr><td>%s</td><td>%u</td></tr>', $uid, $uidvet['uid']["$uid"]['count']);
53 53
 	}
54
-	$return .= sprintf ('<tr><th>%s</th><th>%u</th></tr></table>','TOT',$totlearn);
55
-	$return .= sprintf ('<p>%s : %u</p>','Unique UID',$nuid);
54
+	$return .= sprintf('<tr><th>%s</th><th>%u</th></tr></table>', 'TOT', $totlearn);
55
+	$return .= sprintf('<p>%s : %u</p>', 'Unique UID', $nuid);
56 56
 
57 57
 	return $return;
58 58
 }
@@ -69,12 +69,12 @@  discard block
 block discarded – undo
69 69
     foreach ($cols as $col => $order) {
70 70
         $eval .= '$colarr[\''.$col.'\'],'.$order.',';
71 71
     }
72
-    $eval = substr($eval,0,-1).');';
72
+    $eval = substr($eval, 0, -1).');';
73 73
     eval($eval);
74 74
     $ret = array();
75 75
     foreach ($colarr as $col => $arr) {
76 76
         foreach ($arr as $k => $v) {
77
-            $k = substr($k,1);
77
+            $k = substr($k, 1);
78 78
             if (!isset($ret[$k])) $ret[$k] = $array[$k];
79 79
             if (isset ($array[$k][$col])) $ret[$k][$col] = $array[$k][$col];
80 80
         }
@@ -84,29 +84,29 @@  discard block
 block discarded – undo
84 84
 }
85 85
 
86 86
 
87
-function summaryReportAndList ($cf,$myconn,$tables,$category,$ipvet) {
87
+function summaryReportAndList($cf, $myconn, $tables, $category, $ipvet) {
88 88
 	$nips = $ipvet['count'];
89 89
 
90
-	if ( empty($ipvet) ) return NULL;
90
+	if (empty($ipvet)) return NULL;
91 91
 	$return = '<h3>Statistics by IP</h3><table><tr><th>IP</th><th>Learned by</th><th>Learned times</th><th title="This field doesn\'t say if this ip is currently listed, but it says if this IP has listed now!">Listed Now</th></tr>'."\n";
92 92
 	
93 93
 	$ips = array_keys($ipvet['ip']);
94 94
 
95
-	foreach ( $ips as $ip ) {
96
-		if ( $ip == 'count' ) continue;
95
+	foreach ($ips as $ip) {
96
+		if ($ip == 'count') continue;
97 97
                 $nlearn = $ipvet['ip']["$ip"]['count'];
98 98
                 unset($ipvet['ip']["$ip"]['count']);
99 99
 		$quantity = $cf['quantity']["$category"]; /* In searchAndList this value is passed by reference and modified */
100 100
 		$nuid = count($ipvet['ip']["$ip"]);
101
-		if ( !$cf['onlyReport'] ) {
102
-			if ( ($nlearn >= $cf['thresholdip']["$category"])&&($nuid >= $cf['thresholduid']["$category"]) ) {
101
+		if (!$cf['onlyReport']) {
102
+			if (($nlearn>=$cf['thresholdip']["$category"]) && ($nuid>=$cf['thresholduid']["$category"])) {
103 103
 				$reason = "The IP <$ip> has been listed because was marked $nlearn times as $category by $nuid different accounts during last ".$cf['oldestday'].' days.';
104
-				$listed = searchAndList ($myconn,$cf['user'],$tables,$cf['list']["$category"],$ip,$cf['unit']["$category"],$quantity,$reason);
104
+				$listed = searchAndList($myconn, $cf['user'], $tables, $cf['list']["$category"], $ip, $cf['unit']["$category"], $quantity, $reason);
105 105
 			}
106 106
 			else $listed = FALSE;
107 107
 		}
108 108
 		else $listed = FALSE;
109
-		$nowlist = array( TRUE =>  array(
109
+		$nowlist = array(TRUE =>  array(
110 110
 					'style' => 'id=\'ipfound\'',
111 111
 					'name'  => 'YES',
112 112
 				  ),
@@ -120,45 +120,45 @@  discard block
 block discarded – undo
120 120
 				  )
121 121
 		);
122 122
 		
123
-		$return .='<tr><td rowspan="'.$nuid.'">'.$ip.'</td>';
124
-		$return .= sprintf ('<td>%s</td><td rowspan="'.$nuid.'">%u</td><td rowspan="'.$nuid.'" '.$nowlist["$listed"]['style'].'>%s</td></tr>',$ipvet['ip']["$ip"][0],$nlearn,$nowlist["$listed"]['name']);
125
-		$rowuid=NULL;
126
-                for ($j=1;$j<$nuid;$j++) $rowuid .= '<tr><td>%s</td></tr>';
123
+		$return .= '<tr><td rowspan="'.$nuid.'">'.$ip.'</td>';
124
+		$return .= sprintf('<td>%s</td><td rowspan="'.$nuid.'">%u</td><td rowspan="'.$nuid.'" '.$nowlist["$listed"]['style'].'>%s</td></tr>', $ipvet['ip']["$ip"][0], $nlearn, $nowlist["$listed"]['name']);
125
+		$rowuid = NULL;
126
+                for ($j = 1; $j<$nuid; $j++) $rowuid .= '<tr><td>%s</td></tr>';
127 127
 		array_shift($ipvet['ip']["$ip"]);
128
-                $return .= vsprintf ($rowuid,$ipvet['ip']["$ip"]);
128
+                $return .= vsprintf($rowuid, $ipvet['ip']["$ip"]);
129 129
 
130 130
 	}
131
-	$return .= sprintf ('<tr><th title="unique ips">%u</th><th title="unique uids">%u</th><th>%u</th></table>',$ipvet['ip']['count'],$ipvet['uid']['count'],$nips);
131
+	$return .= sprintf('<tr><th title="unique ips">%u</th><th title="unique uids">%u</th><th>%u</th></table>', $ipvet['ip']['count'], $ipvet['uid']['count'], $nips);
132 132
 
133 133
 
134 134
 	/* Statistics by UID */
135 135
 	/* Not used for listing purpose, but useful to you! */
136 136
 	$return .= '<h3>Statistics by UID</h3><table><tr><th>UID</th><th>IP learned</th><th>Learned times</th></tr>'."\n";
137 137
 	$uids = array_keys($ipvet['uid']);
138
-        foreach ( $uids as $uid ) {
139
-		if ( $uid == 'count' ) continue;	
138
+        foreach ($uids as $uid) {
139
+		if ($uid == 'count') continue;	
140 140
 	        $nlearn = $ipvet['uid']["$uid"]['count'];
141
-	        unset ( $ipvet['uid']["$uid"]['count'] );
141
+	        unset ($ipvet['uid']["$uid"]['count']);
142 142
 		$nip = count($ipvet['uid']["$uid"]);
143
-		$return .='<tr><td rowspan="'.$nip.'">'.$uid.'</td>';
144
-		$return .= sprintf ('<td>%s</td><td rowspan="'.$nip.'">%u</td></tr>',$ipvet['uid']["$uid"][0],$nlearn);
145
-                $rowuid=NULL;
146
-                for ($j=1;$j<$nip;$j++) $rowuid .= '<tr><td>%s</td></tr>';
143
+		$return .= '<tr><td rowspan="'.$nip.'">'.$uid.'</td>';
144
+		$return .= sprintf('<td>%s</td><td rowspan="'.$nip.'">%u</td></tr>', $ipvet['uid']["$uid"][0], $nlearn);
145
+                $rowuid = NULL;
146
+                for ($j = 1; $j<$nip; $j++) $rowuid .= '<tr><td>%s</td></tr>';
147 147
                 array_shift($ipvet['uid']["$uid"]);
148
-                $return .= vsprintf ($rowuid,$ipvet['uid']["$uid"]);
148
+                $return .= vsprintf($rowuid, $ipvet['uid']["$uid"]);
149 149
 
150 150
         }
151
-        $return .= sprintf ('<tr><th title="unique uids">%u</th><th title="unique ips">%u</th><th>%u</th></table>',$ipvet['uid']['count'],$ipvet['ip']['count'],$nips);	
151
+        $return .= sprintf('<tr><th title="unique uids">%u</th><th title="unique ips">%u</th><th>%u</th></table>', $ipvet['uid']['count'], $ipvet['ip']['count'], $nips);	
152 152
 
153 153
 
154 154
 	return $return;
155 155
 }
156 156
 
157 157
 
158
-function splunksearch ($service,$message_id,$date) {
158
+function splunksearch($service, $message_id, $date) {
159 159
 
160 160
 	// Run a blocking search
161
-	$searchQueryBlocking = 'search (message_id="'. addslashes( $message_id ) .
161
+	$searchQueryBlocking = 'search (message_id="'.addslashes($message_id).
162 162
 				'" OR sasl_username) | transaction message_id queue_id maxspan=3m maxpause=2m | search sasl_username message_id=* | table sasl_username';
163 163
 
164 164
 	/* Doesn't work on Splunk 6.6 for HTTP exceptions
@@ -177,8 +177,8 @@  discard block
 block discarded – undo
177 177
 
178 178
 	// A one shot search
179 179
         $searchParams = array(
180
-                'earliest_time' => date("c",strtotime ($date)-120),
181
-                'latest_time' => date("c",strtotime ($date)+60)
180
+                'earliest_time' => date("c", strtotime($date)-120),
181
+                'latest_time' => date("c", strtotime($date)+60)
182 182
         );
183 183
 
184 184
         // Run a oneshot search that returns the job's results
@@ -192,7 +192,7 @@  discard block
 block discarded – undo
192 192
 	    {
193 193
 	      // More than one field attribute returned by search
194 194
 	      // You must redefine the search
195
-	      if ( count($result->getFieldNames()) > 1 ) return FALSE;
195
+	      if (count($result->getFieldNames())>1) return FALSE;
196 196
 	    }
197 197
 	    else if ($result instanceof Splunk_ResultsMessage)
198 198
 	    {
@@ -224,51 +224,51 @@  discard block
 block discarded – undo
224 224
 }
225 225
 
226 226
 
227
-function imapReport ($cf,$myconnArray,$splunkconn,$tables,$type) {
228
-	$file = dirname(__FILE__) . '/' . $cf['reportFile']["$type"];
229
-	$fileb= dirname(__FILE__) . '/' . $cf['badreportFile']["$type"];
230
-	$m_mail = imap_open('{'.$cf['mailhost'].':143/imap/novalidate-cert/authuser='.$cf['authuser'].'}'.$cf['folder']["$type"], $cf['account'],$cf['authpassword'], OP_READONLY)
231
-        	or syslog (LOG_EMERG, $cf['user'].': Error in IMAP connection to <'.$cf['mailhost'].'>: ' . imap_last_error());
232
-	if ( !$m_mail ) exit(254);
227
+function imapReport($cf, $myconnArray, $splunkconn, $tables, $type) {
228
+	$file = dirname(__FILE__).'/'.$cf['reportFile']["$type"];
229
+	$fileb = dirname(__FILE__).'/'.$cf['badreportFile']["$type"];
230
+	$m_mail = imap_open('{'.$cf['mailhost'].':143/imap/novalidate-cert/authuser='.$cf['authuser'].'}'.$cf['folder']["$type"], $cf['account'], $cf['authpassword'], OP_READONLY)
231
+        	or syslog(LOG_EMERG, $cf['user'].': Error in IMAP connection to <'.$cf['mailhost'].'>: '.imap_last_error());
232
+	if (!$m_mail) exit(254);
233 233
 		
234 234
 
235
-	syslog (LOG_INFO,$cf['user'].': Successfully connected to <'.$cf['mailhost'].">; Reading $type messages of last ".$cf['oldestday'].' days...');
235
+	syslog(LOG_INFO, $cf['user'].': Successfully connected to <'.$cf['mailhost'].">; Reading $type messages of last ".$cf['oldestday'].' days...');
236 236
 	//get all messages
237
-	$dateTh = date ( "d-M-Y", strToTime ( '-'.$cf['oldestday'].' days' ) );
238
-        $dateN  = date ( "d-M-Y", strToTime ( "now" ) );
239
-        $m_search=imap_search ($m_mail, "SINCE \"$dateTh\" BEFORE \"$dateN\"" );
237
+	$dateTh = date("d-M-Y", strToTime('-'.$cf['oldestday'].' days'));
238
+        $dateN = date("d-M-Y", strToTime("now"));
239
+        $m_search = imap_search($m_mail, "SINCE \"$dateTh\" BEFORE \"$dateN\"");
240 240
 
241 241
 
242 242
 	// Order results starting from newest message
243
-	if ( empty($m_search) ) {
244
-		syslog (LOG_INFO,$cf['user'].": No mail found in $type folder. No reports written for $type.");
245
-	        if ( $ierr = imap_errors() )
246
-	                foreach ( $ierr as $thiserr )
247
-	                        syslog (LOG_ERR, $cf['user'].": IMAP Error: $thiserr");
248
-	        if ( $ierr = imap_alerts() )
249
-	                foreach ( $ierr as $thiserr )
250
-	                        syslog (LOG_ALERT, $cf['user'].": IMAP Alert: $thiserr");
251
-		imap_close( $m_mail );
252
-		if ( file_exists( $file ) ) unlink ($file);
253
-		if ( file_exists( $fileb ) ) unlink ($fileb);
243
+	if (empty($m_search)) {
244
+		syslog(LOG_INFO, $cf['user'].": No mail found in $type folder. No reports written for $type.");
245
+	        if ($ierr = imap_errors())
246
+	                foreach ($ierr as $thiserr)
247
+	                        syslog(LOG_ERR, $cf['user'].": IMAP Error: $thiserr");
248
+	        if ($ierr = imap_alerts())
249
+	                foreach ($ierr as $thiserr)
250
+	                        syslog(LOG_ALERT, $cf['user'].": IMAP Alert: $thiserr");
251
+		imap_close($m_mail);
252
+		if (file_exists($file)) unlink($file);
253
+		if (file_exists($fileb)) unlink($fileb);
254 254
 		return FALSE;
255 255
 	}
256
-	$nmes = count ($m_search);
257
-	syslog (LOG_INFO,$cf['user'].": Found $nmes mail in $type folder.");
256
+	$nmes = count($m_search);
257
+	syslog(LOG_INFO, $cf['user'].": Found $nmes mail in $type folder.");
258 258
 	if ($nmes>0) rsort($m_search);
259 259
 
260 260
 	// Create report file
261 261
 
262 262
 	$fp = fopen($file, 'w');
263
-	$fpb= fopen($fileb, 'w');
264
-	$lastup = "Last Update: " . date ("d F Y H:i", time());
265
-	fwrite( $fp, file_get_contents(dirname(__FILE__) . '/' . $cf['reportTemplateHeader']) );
266
-	fwrite( $fp,"<h1> Report of IP sending $type</h1><h5>$lastup</h5><h2>Detailed Report</h2>" );
267
-	if ($cf['onlyReport']) fwrite( $fp,'<p>None of the below IP has been listed because listing is not active in configuration.</p>');
268
-	fwrite( $fp,'<table><tr><th title="taken from Received header" nowrap>Date of Learn</th><th title="taken from Date header" nowrap>Date of Write</th><th nowrap>UID</th><th nowrap>IP</th><th title="How many times this uid learns">#UID</th><th title="Number of times this learned IP appears in different mails">#IP</th><th nowrap>Received by</th><th>Message-Id</th></tr>' );
269
-	fwrite( $fpb,file_get_contents(dirname(__FILE__) . '/' . $cf['reportTemplateHeader']) );
270
-	fwrite( $fpb,"<h1> Report of bad reported $type mails</h1><h5>$lastup</h5><h2>Detailed Report</h2>" );
271
-	fwrite( $fpb,'<table><tr><th title="taken from Received header" nowrap>Date Learn</th><th title="taken from Date header" nowrap>Date Received</th><th nowrap>UID</th><th>Message-Id</th><th title="Why is this a bad report?">Reason</th></tr>' );
263
+	$fpb = fopen($fileb, 'w');
264
+	$lastup = "Last Update: ".date("d F Y H:i", time());
265
+	fwrite($fp, file_get_contents(dirname(__FILE__).'/'.$cf['reportTemplateHeader']));
266
+	fwrite($fp, "<h1> Report of IP sending $type</h1><h5>$lastup</h5><h2>Detailed Report</h2>");
267
+	if ($cf['onlyReport']) fwrite($fp, '<p>None of the below IP has been listed because listing is not active in configuration.</p>');
268
+	fwrite($fp, '<table><tr><th title="taken from Received header" nowrap>Date of Learn</th><th title="taken from Date header" nowrap>Date of Write</th><th nowrap>UID</th><th nowrap>IP</th><th title="How many times this uid learns">#UID</th><th title="Number of times this learned IP appears in different mails">#IP</th><th nowrap>Received by</th><th>Message-Id</th></tr>');
269
+	fwrite($fpb, file_get_contents(dirname(__FILE__).'/'.$cf['reportTemplateHeader']));
270
+	fwrite($fpb, "<h1> Report of bad reported $type mails</h1><h5>$lastup</h5><h2>Detailed Report</h2>");
271
+	fwrite($fpb, '<table><tr><th title="taken from Received header" nowrap>Date Learn</th><th title="taken from Date header" nowrap>Date Received</th><th nowrap>UID</th><th>Message-Id</th><th title="Why is this a bad report?">Reason</th></tr>');
272 272
 
273 273
 	$ipuid = array();
274 274
 	$ipuid['count'] = 0;
@@ -286,69 +286,69 @@  discard block
 block discarded – undo
286 286
 	        //get imap header info for obj thang
287 287
 	        //$headers = imap_headerinfo($m_mail, $onem);
288 288
 	        //$head = imap_fetchheader($m_mail, $headers->Msgno);
289
-		$head = imap_fetchheader($m_mail, $onem );
289
+		$head = imap_fetchheader($m_mail, $onem);
290 290
 	        //$obj = imap_rfc822_parse_headers( $head);
291 291
 
292
-	        list ($ip,$host,$dateReceived,$dateClient,$mid) =  getIP( $head,$cf['mx'],$cf['msalearn'] );
292
+	        list ($ip, $host, $dateReceived, $dateClient, $mid) = getIP($head, $cf['mx'], $cf['msalearn']);
293 293
 		if (empty($mid)) {
294
-			$uid='NA';
295
-			syslog (LOG_ERR, $cf['user'].": Error retrieving data for empty Message-ID.");
296
-		} else {
294
+			$uid = 'NA';
295
+			syslog(LOG_ERR, $cf['user'].": Error retrieving data for empty Message-ID.");
296
+		}else {
297 297
 			if ($dateReceived === FALSE) {
298
-				$uid='unauthenticated';
299
-				syslog (LOG_ERR, $cf['user'].": Error retrieving date for $mid. Maybe this mail was not submitted to Learner MSA");
300
-			} else  
301
-				if ( !($uid = splunksearch ($splunkconn, trim($mid,'<>'), $dateReceived)) ) {
302
-					syslog (LOG_ERR, $cf['user'].": Error retrieving uid from Splunk log for $mid.");
303
-					$uid='unknown';
298
+				$uid = 'unauthenticated';
299
+				syslog(LOG_ERR, $cf['user'].": Error retrieving date for $mid. Maybe this mail was not submitted to Learner MSA");
300
+			}else  
301
+				if (!($uid = splunksearch($splunkconn, trim($mid, '<>'), $dateReceived))) {
302
+					syslog(LOG_ERR, $cf['user'].": Error retrieving uid from Splunk log for $mid.");
303
+					$uid = 'unknown';
304 304
 				}
305 305
 		}
306 306
 
307 307
 	        /* Update count of each ip */
308
-	        if ($host and ($uid!='NA') and ($uid!='unauthenticated') and ($uid!='unknown')) { /* IP is received by MX servers  and learned by valid uid */
309
-			$ipuid['count']++;					//number of right messages
308
+	        if ($host and ($uid != 'NA') and ($uid != 'unauthenticated') and ($uid != 'unknown')) { /* IP is received by MX servers  and learned by valid uid */
309
+			$ipuid['count']++; //number of right messages
310 310
 
311
-	                if (in_array($uid,array_keys($ipuid['uid']))) {
312
-				$ipuid['uid']["$uid"]['count']++;		//number of learn by this uid
313
-				if (!in_array($ip,$ipuid['uid']["$uid"])) 
314
-					$ipuid['uid']["$uid"][]=$ip;		//ips learned by this uid
311
+	                if (in_array($uid, array_keys($ipuid['uid']))) {
312
+				$ipuid['uid']["$uid"]['count']++; //number of learn by this uid
313
+				if (!in_array($ip, $ipuid['uid']["$uid"])) 
314
+					$ipuid['uid']["$uid"][] = $ip; //ips learned by this uid
315 315
 			}
316 316
 			else {
317 317
 				$ipuid['uid']["$uid"]['count'] = 1;
318
-				$ipuid['uid']["$uid"][]=$ip;
319
-				$ipuid['uid']['count']++;                	//number of unique uids
318
+				$ipuid['uid']["$uid"][] = $ip;
319
+				$ipuid['uid']['count']++; //number of unique uids
320 320
 			}
321 321
 
322
-                        if (in_array($ip,array_keys($ipuid['ip']))) {
323
-                                $ipuid['ip']["$ip"]['count']++;			//number of time this ip appears in different messages
324
-				if (!in_array($uid,$ipuid['ip']["$ip"]))
325
-					$ipuid['ip']["$ip"][]=$uid;		//uids that learned this ip
322
+                        if (in_array($ip, array_keys($ipuid['ip']))) {
323
+                                $ipuid['ip']["$ip"]['count']++; //number of time this ip appears in different messages
324
+				if (!in_array($uid, $ipuid['ip']["$ip"]))
325
+					$ipuid['ip']["$ip"][] = $uid; //uids that learned this ip
326 326
 			}
327 327
                         else {
328 328
                                 $ipuid['ip']["$ip"]['count'] = 1;
329
-				$ipuid['ip']["$ip"][]=$uid;
330
-				$ipuid['ip']['count']++;			//number of unique ips
329
+				$ipuid['ip']["$ip"][] = $uid;
330
+				$ipuid['ip']['count']++; //number of unique ips
331 331
                         }
332 332
 
333 333
 	        	/* Update HTML report */
334
-	        	fwrite($fp,updateReport ( $ip,$uid,$ipuid['ip']["$ip"]['count'],$ipuid['uid']["$uid"]['count'],$host,$dateClient,$mid,$dateReceived) );
334
+	        	fwrite($fp, updateReport($ip, $uid, $ipuid['ip']["$ip"]['count'], $ipuid['uid']["$uid"]['count'], $host, $dateClient, $mid, $dateReceived));
335 335
 		}
336 336
 	        else {	/* Bad learn */
337 337
 			
338
-                        if (in_array($uid,array_keys($uidbad['uid']))) 
339
-                                $uidbad['uid']["$uid"]['count']++;               //number of bad learn by this uid
338
+                        if (in_array($uid, array_keys($uidbad['uid']))) 
339
+                                $uidbad['uid']["$uid"]['count']++; //number of bad learn by this uid
340 340
                         else {
341 341
                                 $uidbad['uid']["$uid"]['count'] = 1;
342
-				$uidbad['uid']["$uid"][]=$uid;
343
-                                $uidbad['count']++;                       //numeber of unique bad uids
342
+				$uidbad['uid']["$uid"][] = $uid;
343
+                                $uidbad['count']++; //numeber of unique bad uids
344 344
                         }
345 345
 			/* The reason of bad report */
346 346
 			if ($host === FALSE) $reason = 'This mail was not received by recognized MX host';
347 347
 			if ($dateReceived === FALSE) $reason = 'This mail was not submitted to recognized MSA for learn';
348
-			if ($uid=='unknown') $reason = 'The uid of this mail was not found in splunk log';
348
+			if ($uid == 'unknown') $reason = 'The uid of this mail was not found in splunk log';
349 349
 			if (!isset($reason)) $reason = '?';
350 350
 				
351
-			fwrite( $fpb,updatebadReport ( $uid,$dateClient,$mid,$dateReceived,$reason ) );
351
+			fwrite($fpb, updatebadReport($uid, $dateClient, $mid, $dateReceived, $reason));
352 352
 		}
353 353
 	}
354 354
 
@@ -356,45 +356,45 @@  discard block
 block discarded – undo
356 356
 	//close report file and mailbox
357 357
 
358 358
 	/* Summary Report */
359
-	$ipuid['ip'] = array_msort( $ipuid['ip'], array('count'=>SORT_DESC) );
360
-	$ipuid['uid'] = array_msort( $ipuid['uid'], array('count'=>SORT_DESC) );
361
-	$uidbad['uid'] = array_msort( $uidbad['uid'], array('count'=>SORT_DESC) );
359
+	$ipuid['ip'] = array_msort($ipuid['ip'], array('count'=>SORT_DESC));
360
+	$ipuid['uid'] = array_msort($ipuid['uid'], array('count'=>SORT_DESC));
361
+	$uidbad['uid'] = array_msort($uidbad['uid'], array('count'=>SORT_DESC));
362 362
 	
363 363
 	fwrite($fp, '</table>');
364
-	fwrite($fp, '<hr><h2>Summary Report</h2><h5>Listing policy: ip must be learned at least '.$cf['thresholdip']["$type"].' times from at least '.$cf['thresholduid']["$type"].' different valid uids.</h5>' );
364
+	fwrite($fp, '<hr><h2>Summary Report</h2><h5>Listing policy: ip must be learned at least '.$cf['thresholdip']["$type"].' times from at least '.$cf['thresholduid']["$type"].' different valid uids.</h5>');
365 365
 
366 366
         /* Make MYSQL connection */
367
-	if ( $cf['onlyReport'] )
367
+	if ($cf['onlyReport'])
368 368
 		$mysqli = NULL;
369 369
 	else {
370 370
         	$mysqli = new mysqli($myconnArray['dbhost'], $myconnArray['userdb'], $myconnArray['pwd'], $myconnArray['db'], $myconnArray['dbport']);
371 371
         	if ($mysqli->connect_error) {
372
-                	syslog (LOG_EMERG, $cf['user'].': Connect Error (' . $mysqli->connect_errno . ') '
372
+                	syslog(LOG_EMERG, $cf['user'].': Connect Error ('.$mysqli->connect_errno.') '
373 373
                 	. $mysqli->connect_error);
374 374
                 	exit (254);
375 375
         	}
376
-        	syslog(LOG_INFO, $cf['user'].': Successfully mysql connected to ' . $mysqli->host_info) ;
376
+        	syslog(LOG_INFO, $cf['user'].': Successfully mysql connected to '.$mysqli->host_info);
377 377
 	}
378 378
 	/***********************/
379 379
 
380
-	fwrite($fp, summaryReportAndList ($cf,$mysqli,$tables,$type,$ipuid) );
381
-	if ( !$cf['onlyReport'] )
380
+	fwrite($fp, summaryReportAndList($cf, $mysqli, $tables, $type, $ipuid));
381
+	if (!$cf['onlyReport'])
382 382
 		$mysqli->close();
383
-	fwrite($fp,file_get_contents(dirname(__FILE__) . '/' . $cf['reportTemplateFooter']));
383
+	fwrite($fp, file_get_contents(dirname(__FILE__).'/'.$cf['reportTemplateFooter']));
384 384
 	fclose($fp);
385 385
 
386 386
 	fwrite($fpb, '</table>');
387
-	fwrite( $fpb,summaryBadReport( $uidbad ) );
388
-	fwrite($fpb,file_get_contents(dirname(__FILE__) . '/' . $cf['reportTemplateFooter']));
387
+	fwrite($fpb, summaryBadReport($uidbad));
388
+	fwrite($fpb, file_get_contents(dirname(__FILE__).'/'.$cf['reportTemplateFooter']));
389 389
 	fclose($fpb);
390
-	syslog (LOG_INFO,$cf['user'].': Report files written. Listing job for '.$type.' terminated.');
391
-
392
-	if ( $ierr = imap_errors() )
393
-		foreach ( $ierr as $thiserr )
394
-			syslog (LOG_ERR, $cf['user'].": IMAP Error: $thiserr");
395
-	if ( $ierr = imap_alerts() )
396
-                foreach ( $ierr as $thiserr )
397
-                        syslog (LOG_ALERT, $cf['user'].": IMAP Alert: $thiserr");
390
+	syslog(LOG_INFO, $cf['user'].': Report files written. Listing job for '.$type.' terminated.');
391
+
392
+	if ($ierr = imap_errors())
393
+		foreach ($ierr as $thiserr)
394
+			syslog(LOG_ERR, $cf['user'].": IMAP Error: $thiserr");
395
+	if ($ierr = imap_alerts())
396
+                foreach ($ierr as $thiserr)
397
+                        syslog(LOG_ALERT, $cf['user'].": IMAP Alert: $thiserr");
398 398
 	imap_close($m_mail);
399 399
 }
400 400
 ?>
Please login to merge, or discard this patch.
Braces   +107 added lines, -61 removed lines patch added patch discarded remove patch
@@ -10,21 +10,25 @@  discard block
 block discarded – undo
10 10
 	if ( preg_match_all('/^Received:\sfrom(?:.|\r\n\s)*?[\[\(]\s*(?P<ip>\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})[\]\)](?:.|\r\n\s)+\s+by(?:\s|\r\n\s+)(?P<host>\S+).*(?:\s|\r\n\s\s)+.*;\s+(?P<date>.*)/m',$header,$received) ) {
11 11
 		for ($i = count($received[0])-1;$i>=0;$i--) {
12 12
 #			print "Examine ".$received[0][$i]."\n";
13
-			if ( preg_match($msa,$received['host'][$i]) )
14
-				$dateR = $received['date'][$i];
13
+			if ( preg_match($msa,$received['host'][$i]) ) {
14
+							$dateR = $received['date'][$i];
15
+			}
15 16
         		foreach ($mxserver as $mx) {
16
-        			if (!$ip)
17
-					if ($mx == $received['host'][$i]) {
17
+        			if (!$ip) {
18
+        								if ($mx == $received['host'][$i]) {
18 19
 						$host = $received['host'][$i];
20
+        			}
19 21
 						$ip = $received['ip'][$i];
20 22
                     			}
21 23
                 	}
22 24
         	}
23 25
 	}
24
-	if ( preg_match ('/\r\nDate:\s(?P<date>.*)\r\n/',$header,$dateC) != 1)
25
-		$dateC['date'] = 'Not found';
26
-	if ( preg_match ('/\r\nMessage\-I(?:D|d):\s(?P<mid>.*)\r\n/',$header,$mid) != 1)
27
-		$mid['mid'] = NULL;
26
+	if ( preg_match ('/\r\nDate:\s(?P<date>.*)\r\n/',$header,$dateC) != 1) {
27
+			$dateC['date'] = 'Not found';
28
+	}
29
+	if ( preg_match ('/\r\nMessage\-I(?:D|d):\s(?P<mid>.*)\r\n/',$header,$mid) != 1) {
30
+			$mid['mid'] = NULL;
31
+	}
28 32
 	return array($ip,$host,$dateR,$dateC['date'],$mid['mid']);
29 33
 }
30 34
 
@@ -40,7 +44,9 @@  discard block
 block discarded – undo
40 44
 
41 45
 function summaryBadReport ($uidvet) {
42 46
         $nuid = $uidvet['count'];
43
-        if ( empty($uidvet) ) return NULL;
47
+        if ( empty($uidvet) ) {
48
+        	return NULL;
49
+        }
44 50
         $return = '<hr><h3>Statistics by UID</h3><table><tr><th>UID</th><th>Learned times</th></tr>'."\n";
45 51
 
46 52
         /* Remove count index */
@@ -75,8 +81,12 @@  discard block
 block discarded – undo
75 81
     foreach ($colarr as $col => $arr) {
76 82
         foreach ($arr as $k => $v) {
77 83
             $k = substr($k,1);
78
-            if (!isset($ret[$k])) $ret[$k] = $array[$k];
79
-            if (isset ($array[$k][$col])) $ret[$k][$col] = $array[$k][$col];
84
+            if (!isset($ret[$k])) {
85
+            	$ret[$k] = $array[$k];
86
+            }
87
+            if (isset ($array[$k][$col])) {
88
+            	$ret[$k][$col] = $array[$k][$col];
89
+            }
80 90
         }
81 91
     }
82 92
     return $ret;
@@ -87,13 +97,17 @@  discard block
 block discarded – undo
87 97
 function summaryReportAndList ($cf,$myconn,$tables,$category,$ipvet) {
88 98
 	$nips = $ipvet['count'];
89 99
 
90
-	if ( empty($ipvet) ) return NULL;
100
+	if ( empty($ipvet) ) {
101
+		return NULL;
102
+	}
91 103
 	$return = '<h3>Statistics by IP</h3><table><tr><th>IP</th><th>Learned by</th><th>Learned times</th><th title="This field doesn\'t say if this ip is currently listed, but it says if this IP has listed now!">Listed Now</th></tr>'."\n";
92 104
 	
93 105
 	$ips = array_keys($ipvet['ip']);
94 106
 
95 107
 	foreach ( $ips as $ip ) {
96
-		if ( $ip == 'count' ) continue;
108
+		if ( $ip == 'count' ) {
109
+			continue;
110
+		}
97 111
                 $nlearn = $ipvet['ip']["$ip"]['count'];
98 112
                 unset($ipvet['ip']["$ip"]['count']);
99 113
 		$quantity = $cf['quantity']["$category"]; /* In searchAndList this value is passed by reference and modified */
@@ -102,10 +116,12 @@  discard block
 block discarded – undo
102 116
 			if ( ($nlearn >= $cf['thresholdip']["$category"])&&($nuid >= $cf['thresholduid']["$category"]) ) {
103 117
 				$reason = "The IP <$ip> has been listed because was marked $nlearn times as $category by $nuid different accounts during last ".$cf['oldestday'].' days.';
104 118
 				$listed = searchAndList ($myconn,$cf['user'],$tables,$cf['list']["$category"],$ip,$cf['unit']["$category"],$quantity,$reason);
119
+			} else {
120
+				$listed = FALSE;
105 121
 			}
106
-			else $listed = FALSE;
122
+		} else {
123
+			$listed = FALSE;
107 124
 		}
108
-		else $listed = FALSE;
109 125
 		$nowlist = array( TRUE =>  array(
110 126
 					'style' => 'id=\'ipfound\'',
111 127
 					'name'  => 'YES',
@@ -123,7 +139,9 @@  discard block
 block discarded – undo
123 139
 		$return .='<tr><td rowspan="'.$nuid.'">'.$ip.'</td>';
124 140
 		$return .= sprintf ('<td>%s</td><td rowspan="'.$nuid.'">%u</td><td rowspan="'.$nuid.'" '.$nowlist["$listed"]['style'].'>%s</td></tr>',$ipvet['ip']["$ip"][0],$nlearn,$nowlist["$listed"]['name']);
125 141
 		$rowuid=NULL;
126
-                for ($j=1;$j<$nuid;$j++) $rowuid .= '<tr><td>%s</td></tr>';
142
+                for ($j=1;$j<$nuid;$j++) {
143
+                	$rowuid .= '<tr><td>%s</td></tr>';
144
+                }
127 145
 		array_shift($ipvet['ip']["$ip"]);
128 146
                 $return .= vsprintf ($rowuid,$ipvet['ip']["$ip"]);
129 147
 
@@ -136,14 +154,18 @@  discard block
 block discarded – undo
136 154
 	$return .= '<h3>Statistics by UID</h3><table><tr><th>UID</th><th>IP learned</th><th>Learned times</th></tr>'."\n";
137 155
 	$uids = array_keys($ipvet['uid']);
138 156
         foreach ( $uids as $uid ) {
139
-		if ( $uid == 'count' ) continue;	
157
+		if ( $uid == 'count' ) {
158
+			continue;
159
+		}
140 160
 	        $nlearn = $ipvet['uid']["$uid"]['count'];
141 161
 	        unset ( $ipvet['uid']["$uid"]['count'] );
142 162
 		$nip = count($ipvet['uid']["$uid"]);
143 163
 		$return .='<tr><td rowspan="'.$nip.'">'.$uid.'</td>';
144 164
 		$return .= sprintf ('<td>%s</td><td rowspan="'.$nip.'">%u</td></tr>',$ipvet['uid']["$uid"][0],$nlearn);
145 165
                 $rowuid=NULL;
146
-                for ($j=1;$j<$nip;$j++) $rowuid .= '<tr><td>%s</td></tr>';
166
+                for ($j=1;$j<$nip;$j++) {
167
+                	$rowuid .= '<tr><td>%s</td></tr>';
168
+                }
147 169
                 array_shift($ipvet['uid']["$uid"]);
148 170
                 $return .= vsprintf ($rowuid,$ipvet['uid']["$uid"]);
149 171
 
@@ -192,14 +214,14 @@  discard block
 block discarded – undo
192 214
 	    {
193 215
 	      // More than one field attribute returned by search
194 216
 	      // You must redefine the search
195
-	      if ( count($result->getFieldNames()) > 1 ) return FALSE;
196
-	    }
197
-	    else if ($result instanceof Splunk_ResultsMessage)
217
+	      if ( count($result->getFieldNames()) > 1 ) {
218
+	      	return FALSE;
219
+	      }
220
+	    } else if ($result instanceof Splunk_ResultsMessage)
198 221
 	    {
199 222
 	      // I don't want messages in my search
200 223
 	      return FALSE;
201
-	    }
202
-	    else if (is_array($result))
224
+	    } else if (is_array($result))
203 225
 	    {
204 226
 	      // Process a row
205 227
 	      foreach ($result as $key => $valueOrValues)
@@ -207,15 +229,13 @@  discard block
 block discarded – undo
207 229
 	         if (is_array($valueOrValues))
208 230
 	          {
209 231
 	            return FALSE;
210
-	          }
211
-	         else
232
+	          } else
212 233
 	          {
213 234
 	            return $valueOrValues;
214 235
 	            #print "  {$key} => {$value}\r\n";
215 236
 	          }
216 237
 	        }
217
-	    }
218
-	    else
238
+	    } else
219 239
 	    {
220 240
 	      #print "Unknow result type";
221 241
 	      return FALSE;
@@ -229,7 +249,9 @@  discard block
 block discarded – undo
229 249
 	$fileb= dirname(__FILE__) . '/' . $cf['badreportFile']["$type"];
230 250
 	$m_mail = imap_open('{'.$cf['mailhost'].':143/imap/novalidate-cert/authuser='.$cf['authuser'].'}'.$cf['folder']["$type"], $cf['account'],$cf['authpassword'], OP_READONLY)
231 251
         	or syslog (LOG_EMERG, $cf['user'].': Error in IMAP connection to <'.$cf['mailhost'].'>: ' . imap_last_error());
232
-	if ( !$m_mail ) exit(254);
252
+	if ( !$m_mail ) {
253
+		exit(254);
254
+	}
233 255
 		
234 256
 
235 257
 	syslog (LOG_INFO,$cf['user'].': Successfully connected to <'.$cf['mailhost'].">; Reading $type messages of last ".$cf['oldestday'].' days...');
@@ -242,20 +264,28 @@  discard block
 block discarded – undo
242 264
 	// Order results starting from newest message
243 265
 	if ( empty($m_search) ) {
244 266
 		syslog (LOG_INFO,$cf['user'].": No mail found in $type folder. No reports written for $type.");
245
-	        if ( $ierr = imap_errors() )
246
-	                foreach ( $ierr as $thiserr )
267
+	        if ( $ierr = imap_errors() ) {
268
+	        	                foreach ( $ierr as $thiserr )
247 269
 	                        syslog (LOG_ERR, $cf['user'].": IMAP Error: $thiserr");
248
-	        if ( $ierr = imap_alerts() )
249
-	                foreach ( $ierr as $thiserr )
270
+	        }
271
+	        if ( $ierr = imap_alerts() ) {
272
+	        	                foreach ( $ierr as $thiserr )
250 273
 	                        syslog (LOG_ALERT, $cf['user'].": IMAP Alert: $thiserr");
274
+	        }
251 275
 		imap_close( $m_mail );
252
-		if ( file_exists( $file ) ) unlink ($file);
253
-		if ( file_exists( $fileb ) ) unlink ($fileb);
276
+		if ( file_exists( $file ) ) {
277
+			unlink ($file);
278
+		}
279
+		if ( file_exists( $fileb ) ) {
280
+			unlink ($fileb);
281
+		}
254 282
 		return FALSE;
255 283
 	}
256 284
 	$nmes = count ($m_search);
257 285
 	syslog (LOG_INFO,$cf['user'].": Found $nmes mail in $type folder.");
258
-	if ($nmes>0) rsort($m_search);
286
+	if ($nmes>0) {
287
+		rsort($m_search);
288
+	}
259 289
 
260 290
 	// Create report file
261 291
 
@@ -264,7 +294,9 @@  discard block
 block discarded – undo
264 294
 	$lastup = "Last Update: " . date ("d F Y H:i", time());
265 295
 	fwrite( $fp, file_get_contents(dirname(__FILE__) . '/' . $cf['reportTemplateHeader']) );
266 296
 	fwrite( $fp,"<h1> Report of IP sending $type</h1><h5>$lastup</h5><h2>Detailed Report</h2>" );
267
-	if ($cf['onlyReport']) fwrite( $fp,'<p>None of the below IP has been listed because listing is not active in configuration.</p>');
297
+	if ($cf['onlyReport']) {
298
+		fwrite( $fp,'<p>None of the below IP has been listed because listing is not active in configuration.</p>');
299
+	}
268 300
 	fwrite( $fp,'<table><tr><th title="taken from Received header" nowrap>Date of Learn</th><th title="taken from Date header" nowrap>Date of Write</th><th nowrap>UID</th><th nowrap>IP</th><th title="How many times this uid learns">#UID</th><th title="Number of times this learned IP appears in different mails">#IP</th><th nowrap>Received by</th><th>Message-Id</th></tr>' );
269 301
 	fwrite( $fpb,file_get_contents(dirname(__FILE__) . '/' . $cf['reportTemplateHeader']) );
270 302
 	fwrite( $fpb,"<h1> Report of bad reported $type mails</h1><h5>$lastup</h5><h2>Detailed Report</h2>" );
@@ -310,10 +342,11 @@  discard block
 block discarded – undo
310 342
 
311 343
 	                if (in_array($uid,array_keys($ipuid['uid']))) {
312 344
 				$ipuid['uid']["$uid"]['count']++;		//number of learn by this uid
313
-				if (!in_array($ip,$ipuid['uid']["$uid"])) 
314
-					$ipuid['uid']["$uid"][]=$ip;		//ips learned by this uid
315
-			}
316
-			else {
345
+				if (!in_array($ip,$ipuid['uid']["$uid"])) {
346
+									$ipuid['uid']["$uid"][]=$ip;
347
+				}
348
+				//ips learned by this uid
349
+			} else {
317 350
 				$ipuid['uid']["$uid"]['count'] = 1;
318 351
 				$ipuid['uid']["$uid"][]=$ip;
319 352
 				$ipuid['uid']['count']++;                	//number of unique uids
@@ -321,10 +354,11 @@  discard block
 block discarded – undo
321 354
 
322 355
                         if (in_array($ip,array_keys($ipuid['ip']))) {
323 356
                                 $ipuid['ip']["$ip"]['count']++;			//number of time this ip appears in different messages
324
-				if (!in_array($uid,$ipuid['ip']["$ip"]))
325
-					$ipuid['ip']["$ip"][]=$uid;		//uids that learned this ip
326
-			}
327
-                        else {
357
+				if (!in_array($uid,$ipuid['ip']["$ip"])) {
358
+									$ipuid['ip']["$ip"][]=$uid;
359
+				}
360
+				//uids that learned this ip
361
+			} else {
328 362
                                 $ipuid['ip']["$ip"]['count'] = 1;
329 363
 				$ipuid['ip']["$ip"][]=$uid;
330 364
 				$ipuid['ip']['count']++;			//number of unique ips
@@ -332,21 +366,30 @@  discard block
 block discarded – undo
332 366
 
333 367
 	        	/* Update HTML report */
334 368
 	        	fwrite($fp,updateReport ( $ip,$uid,$ipuid['ip']["$ip"]['count'],$ipuid['uid']["$uid"]['count'],$host,$dateClient,$mid,$dateReceived) );
335
-		}
336
-	        else {	/* Bad learn */
369
+		} else {	/* Bad learn */
337 370
 			
338
-                        if (in_array($uid,array_keys($uidbad['uid']))) 
339
-                                $uidbad['uid']["$uid"]['count']++;               //number of bad learn by this uid
371
+                        if (in_array($uid,array_keys($uidbad['uid']))) {
372
+                                                        $uidbad['uid']["$uid"]['count']++;
373
+                        }
374
+                        //number of bad learn by this uid
340 375
                         else {
341 376
                                 $uidbad['uid']["$uid"]['count'] = 1;
342 377
 				$uidbad['uid']["$uid"][]=$uid;
343 378
                                 $uidbad['count']++;                       //numeber of unique bad uids
344 379
                         }
345 380
 			/* The reason of bad report */
346
-			if ($host === FALSE) $reason = 'This mail was not received by recognized MX host';
347
-			if ($dateReceived === FALSE) $reason = 'This mail was not submitted to recognized MSA for learn';
348
-			if ($uid=='unknown') $reason = 'The uid of this mail was not found in splunk log';
349
-			if (!isset($reason)) $reason = '?';
381
+			if ($host === FALSE) {
382
+				$reason = 'This mail was not received by recognized MX host';
383
+			}
384
+			if ($dateReceived === FALSE) {
385
+				$reason = 'This mail was not submitted to recognized MSA for learn';
386
+			}
387
+			if ($uid=='unknown') {
388
+				$reason = 'The uid of this mail was not found in splunk log';
389
+			}
390
+			if (!isset($reason)) {
391
+				$reason = '?';
392
+			}
350 393
 				
351 394
 			fwrite( $fpb,updatebadReport ( $uid,$dateClient,$mid,$dateReceived,$reason ) );
352 395
 		}
@@ -364,9 +407,9 @@  discard block
 block discarded – undo
364 407
 	fwrite($fp, '<hr><h2>Summary Report</h2><h5>Listing policy: ip must be learned at least '.$cf['thresholdip']["$type"].' times from at least '.$cf['thresholduid']["$type"].' different valid uids.</h5>' );
365 408
 
366 409
         /* Make MYSQL connection */
367
-	if ( $cf['onlyReport'] )
368
-		$mysqli = NULL;
369
-	else {
410
+	if ( $cf['onlyReport'] ) {
411
+			$mysqli = NULL;
412
+	} else {
370 413
         	$mysqli = new mysqli($myconnArray['dbhost'], $myconnArray['userdb'], $myconnArray['pwd'], $myconnArray['db'], $myconnArray['dbport']);
371 414
         	if ($mysqli->connect_error) {
372 415
                 	syslog (LOG_EMERG, $cf['user'].': Connect Error (' . $mysqli->connect_errno . ') '
@@ -378,8 +421,9 @@  discard block
 block discarded – undo
378 421
 	/***********************/
379 422
 
380 423
 	fwrite($fp, summaryReportAndList ($cf,$mysqli,$tables,$type,$ipuid) );
381
-	if ( !$cf['onlyReport'] )
382
-		$mysqli->close();
424
+	if ( !$cf['onlyReport'] ) {
425
+			$mysqli->close();
426
+	}
383 427
 	fwrite($fp,file_get_contents(dirname(__FILE__) . '/' . $cf['reportTemplateFooter']));
384 428
 	fclose($fp);
385 429
 
@@ -389,12 +433,14 @@  discard block
 block discarded – undo
389 433
 	fclose($fpb);
390 434
 	syslog (LOG_INFO,$cf['user'].': Report files written. Listing job for '.$type.' terminated.');
391 435
 
392
-	if ( $ierr = imap_errors() )
393
-		foreach ( $ierr as $thiserr )
436
+	if ( $ierr = imap_errors() ) {
437
+			foreach ( $ierr as $thiserr )
394 438
 			syslog (LOG_ERR, $cf['user'].": IMAP Error: $thiserr");
395
-	if ( $ierr = imap_alerts() )
396
-                foreach ( $ierr as $thiserr )
439
+	}
440
+	if ( $ierr = imap_alerts() ) {
441
+	                foreach ( $ierr as $thiserr )
397 442
                         syslog (LOG_ALERT, $cf['user'].": IMAP Alert: $thiserr");
443
+	}
398 444
 	imap_close($m_mail);
399 445
 }
400 446
 ?>
Please login to merge, or discard this patch.
function.php 4 patches
Doc Comments   +8 added lines patch added patch discarded remove patch
@@ -205,6 +205,11 @@  discard block
 block discarded – undo
205 205
 }
206 206
 
207 207
 
208
+/**
209
+ * @param integer $id
210
+ * @param string $what
211
+ * @param boolean $lock
212
+ */
208 213
 function ask($myconn,$id,$what,$alltables,$typedesc,$value,$lock,$user,$adm) {
209 214
 
210 215
 	$whynot=NULL;
@@ -404,6 +409,9 @@  discard block
 block discarded – undo
404 409
 }
405 410
 
406 411
 
412
+/**
413
+ * @param string $reason
414
+ */
407 415
 function searchAndList ($myconn,$loguser,$tables,$typedesc,$value,$unit,&$quantity,$reason) {
408 416
 
409 417
 /* Search and list value */
Please login to merge, or discard this patch.
Indentation   +136 added lines, -136 removed lines patch added patch discarded remove patch
@@ -4,8 +4,8 @@  discard block
 block discarded – undo
4 4
 
5 5
 function username() {
6 6
 	if (isset ($_SERVER['REMOTE_USER'])) $user = $_SERVER['REMOTE_USER'];
7
-        	else if (isset ($_SERVER['USER'])) $user = $_SERVER['USER'];
8
-                	else $user='unknown';
7
+			else if (isset ($_SERVER['USER'])) $user = $_SERVER['USER'];
8
+					else $user='unknown';
9 9
 	return $user;
10 10
 }
11 11
 
@@ -35,7 +35,7 @@  discard block
 block discarded – undo
35 35
 
36 36
 	  case 'network':
37 37
 		list($sub['net'],$sub['mask'])=explode('/',$value);
38
-                $query= sprintf("INSERT INTO `$table` (
38
+				$query= sprintf("INSERT INTO `$table` (
39 39
                         `$type` ,
40 40
 			`netmask`,
41 41
                         `date` ,
@@ -48,10 +48,10 @@  discard block
 block discarded – undo
48 48
                         INET_ATON( '%s' ) , INET_ATON( '%s' ) ,
49 49
                         CURRENT_TIMESTAMP , TIMESTAMPADD(%s,%d,CURRENT_TIMESTAMP), '1', '%s', '%s'
50 50
                 )" ,$sub['net'],$sub['mask'],$expUnit,$expQ,$user,$myreason);
51
-                break;
51
+				break;
52 52
 
53 53
 	  default:
54
-                $query= sprintf("INSERT INTO `$table` (
54
+				$query= sprintf("INSERT INTO `$table` (
55 55
                         `$type` ,
56 56
                         `date` ,
57 57
                         `exp` ,
@@ -66,8 +66,8 @@  discard block
 block discarded – undo
66 66
 	}
67 67
 
68 68
 	if ($myconn->query($query) === TRUE) {
69
-	    syslog(LOG_INFO, "$user: $type <$value> successfully listed on <$table> for $expQ $expUnit.");
70
-	    $result=TRUE;
69
+		syslog(LOG_INFO, "$user: $type <$value> successfully listed on <$table> for $expQ $expUnit.");
70
+		$result=TRUE;
71 71
 	}
72 72
 	else syslog(LOG_ERR, "$user: Error: ".$myconn->error);
73 73
 	return $result;
@@ -77,9 +77,9 @@  discard block
 block discarded – undo
77 77
 
78 78
 	$result=FALSE;
79 79
 
80
-        switch ($type) {
80
+		switch ($type) {
81 81
 	  case 'ip':
82
-                $query= sprintf("UPDATE `$table` SET
82
+				$query= sprintf("UPDATE `$table` SET
83 83
 			`active` = '1',
84 84
 			`user` = '%s',
85 85
 			`exp` = TIMESTAMPADD(%s,%d,CURRENT_TIMESTAMP),
@@ -87,9 +87,9 @@  discard block
 block discarded – undo
87 87
 			`reason` = '%s'
88 88
 			WHERE `$table`.`$type` = INET_ATON('%s') LIMIT 1" ,$user,$expUnit,$expQ,$myreason,$value);
89 89
 		break;
90
-          case 'network':
90
+		  case 'network':
91 91
 		list($sub['net'],$sub['mask'])=explode('/',$value);
92
-                $query= sprintf("UPDATE `$table` SET
92
+				$query= sprintf("UPDATE `$table` SET
93 93
                         `active` = '1',
94 94
                         `user` = '%s',
95 95
                         `exp` = TIMESTAMPADD(%s,%d,CURRENT_TIMESTAMP),
@@ -98,7 +98,7 @@  discard block
 block discarded – undo
98 98
                         WHERE (`$table`.`$type` = INET_ATON('%s') AND `$table`.`netmask` = INET_ATON('%s')) LIMIT 1" ,$user,$expUnit,$expQ,$myreason,$sub['net'],$sub['mask']);
99 99
 		break;
100 100
 	  default:
101
-                $query= sprintf("UPDATE `$table` SET
101
+				$query= sprintf("UPDATE `$table` SET
102 102
                         `active` = '1',
103 103
                         `user` = '%s',
104 104
                         `exp` = TIMESTAMPADD(%s,%d,CURRENT_TIMESTAMP),
@@ -107,18 +107,18 @@  discard block
 block discarded – undo
107 107
 			WHERE `$table`.`$type` = '%s' LIMIT 1" ,$user,$expUnit,$expQ,$myreason,$value);
108 108
 	}
109 109
 
110
-        if ($myconn->query($query) === TRUE) {
111
-            syslog(LOG_INFO, "$user: relist $type <$value> on <$table> for $expQ $expUnit.");
110
+		if ($myconn->query($query) === TRUE) {
111
+			syslog(LOG_INFO, "$user: relist $type <$value> on <$table> for $expQ $expUnit.");
112 112
 		$result=TRUE;
113
-        }
114
-        else syslog (LOG_ERR, "$user: Error: ". $myconn->error);
113
+		}
114
+		else syslog (LOG_ERR, "$user: Error: ". $myconn->error);
115 115
 	return $result;
116 116
 }
117 117
 
118 118
 function remove ($myconn,$user,$value,$type,$table) {
119 119
 
120
-        switch ($type) {
121
-          case 'ip':
120
+		switch ($type) {
121
+		  case 'ip':
122 122
 		$query = sprintf("DELETE FROM `$table` WHERE
123 123
                         `$table`.`$type` = INET_ATON('%s') LIMIT 1", $value);
124 124
 		break;
@@ -134,18 +134,18 @@  discard block
 block discarded – undo
134 134
 	}
135 135
 
136 136
 
137
-        if ($return=$myconn->query($query) === TRUE) 
138
-            syslog(LOG_INFO, "$user: permanently DELETED $type <$value> from <$table>.");
139
-        else syslog(LOG_ERR, "$user: Error: ". $myconn->error);
137
+		if ($return=$myconn->query($query) === TRUE) 
138
+			syslog(LOG_INFO, "$user: permanently DELETED $type <$value> from <$table>.");
139
+		else syslog(LOG_ERR, "$user: Error: ". $myconn->error);
140 140
 
141
-        return $return;
141
+		return $return;
142 142
 }
143 143
 
144 144
 
145 145
 function changestatus ($myconn,$user,$value,$status,$type,$table) {
146 146
 
147 147
 	switch ($type) {
148
-          case 'ip':
148
+		  case 'ip':
149 149
 		$query= sprintf("UPDATE `$table` SET `active` = '$status', `user` = '%s' WHERE `$table`.`$type` = INET_ATON('%s') LIMIT 1" ,$user, $value);
150 150
 		break;
151 151
 	  case 'network':
@@ -156,16 +156,16 @@  discard block
 block discarded – undo
156 156
 		$query= sprintf("UPDATE `$table` SET `active` = '$status', `user` = '%s' WHERE `$table`.`$type` = '%s' LIMIT 1" ,$user, $value);
157 157
 	}
158 158
 
159
-        if ($return=$myconn->query($query) === TRUE) {
160
-            syslog(LOG_INFO, "$user: change status of $type <$value>. The status is now <$status>");
161
-        }
162
-        else syslog(LOG_ERR, "$user: Error: ". $myconn->error);
159
+		if ($return=$myconn->query($query) === TRUE) {
160
+			syslog(LOG_INFO, "$user: change status of $type <$value>. The status is now <$status>");
161
+		}
162
+		else syslog(LOG_ERR, "$user: Error: ". $myconn->error);
163 163
 	return $return;	
164 164
 }
165 165
 
166 166
 
167 167
 function expire ($myconn,$user,$tables,$expireTime) {
168
-        $return=TRUE;
168
+		$return=TRUE;
169 169
 	$log=array();
170 170
 	$desc = array_keys($tables);
171 171
 	foreach ($desc as $tdesc) { 
@@ -175,11 +175,11 @@  discard block
 block discarded – undo
175 175
 		/* END OF QUERY */
176 176
 		$log[0] = 'expired for';
177 177
 		$log[1] = 'disabled for';
178
-        	if ($myconn->multi_query($query)) {
178
+			if ($myconn->multi_query($query)) {
179 179
 			$j = 0;
180 180
 			do {
181
-		    		$numdel = $myconn->affected_rows;
182
-	            		syslog(LOG_INFO, "Expire job - <$user> Permanently DELETED $numdel records ".$log[$j]." $expireTime YEARS from <".$tables["$tdesc"]['name'].'>.');
181
+					$numdel = $myconn->affected_rows;
182
+						syslog(LOG_INFO, "Expire job - <$user> Permanently DELETED $numdel records ".$log[$j]." $expireTime YEARS from <".$tables["$tdesc"]['name'].'>.');
183 183
 				$j++;
184 184
 
185 185
 			} while ($myconn->next_result());
@@ -191,7 +191,7 @@  discard block
 block discarded – undo
191 191
 	}
192 192
 	if ( !($return) ) syslog(LOG_EMERG, 'End of Expire job with error. See above logs. SQL Connection terminated');
193 193
 	else  syslog(LOG_INFO, 'Successfully End of Expire job. SQL Connection successfully terminated.');
194
-        return $return;
194
+		return $return;
195 195
 }
196 196
 
197 197
 
@@ -233,7 +233,7 @@  discard block
 block discarded – undo
233 233
 		if ( $entry->num_rows ) {
234 234
 			if ( $entry->num_rows == 1 ) {
235 235
 				$riga = $entry->fetch_array(MYSQLI_ASSOC);
236
-                        	if (isListed($riga)) {
236
+							if (isListed($riga)) {
237 237
 					$warn = "<$value> is already present in <$listdep> list!";
238 238
 					$entry->free();
239 239
 					return FALSE;
@@ -250,28 +250,28 @@  discard block
 block discarded – undo
250 250
 function searchentry ($myconn,$value,$tablelist) {
251 251
 /* Make a MYSQL query and return result */
252 252
 
253
-        $type = $tablelist['field'];
254
-        $table = $tablelist['name'];
255
-
256
-        if ($value == 'ALL') $query = 'select * from '.$table;
257
-        else {
258
-                switch ($type) {
259
-                  case 'ip':
260
-                        $query= "select * from $table where $type =  INET_ATON('$value')";
261
-                        break;
262
-                  case 'network':
263
-                        list($sub['net'],$sub['mask'])=explode('/',$value);
264
-                        $query= 'select * from '.$table.' where (((inet_aton(\''.$sub['net'].'\') | (~ inet_aton(\''.$sub['mask'].'\'))) & netmask) = network)';
265
-                        break;
266
-                  default:
267
-                        $query= "select * from $table where $type = '$value'";
268
-                }
269
-        }
253
+		$type = $tablelist['field'];
254
+		$table = $tablelist['name'];
255
+
256
+		if ($value == 'ALL') $query = 'select * from '.$table;
257
+		else {
258
+				switch ($type) {
259
+				  case 'ip':
260
+						$query= "select * from $table where $type =  INET_ATON('$value')";
261
+						break;
262
+				  case 'network':
263
+						list($sub['net'],$sub['mask'])=explode('/',$value);
264
+						$query= 'select * from '.$table.' where (((inet_aton(\''.$sub['net'].'\') | (~ inet_aton(\''.$sub['mask'].'\'))) & netmask) = network)';
265
+						break;
266
+				  default:
267
+						$query= "select * from $table where $type = '$value'";
268
+				}
269
+		}
270 270
 
271 271
 	$result = $myconn->query($query);
272 272
 	if($result === false)
273 273
 		syslog(LOG_EMERG, "ALERT: Query <$query> failed: ".$myconn->error);
274
-        return $result;
274
+		return $result;
275 275
 }
276 276
 
277 277
 function countListed ($myconn,$table) {
@@ -286,10 +286,10 @@  discard block
 block discarded – undo
286 286
 
287 287
 
288 288
 function isFull($myconn,$typedesc,$alltables) {
289
-        if (isset($alltables["$typedesc"]['limit'])) {
290
-                if ( countListed($myconn,$alltables["$typedesc"]['name']) >= $alltables["$typedesc"]['limit'] ) 
291
-                        return TRUE;
292
-        }
289
+		if (isset($alltables["$typedesc"]['limit'])) {
290
+				if ( countListed($myconn,$alltables["$typedesc"]['name']) >= $alltables["$typedesc"]['limit'] ) 
291
+						return TRUE;
292
+		}
293 293
 	return FALSE;
294 294
 }
295 295
 
@@ -302,14 +302,14 @@  discard block
 block discarded – undo
302 302
 	if ($result) {
303 303
 		printf("<pre>Your request for $type &lt;$value&gt; returned %d items.\n</pre>", $result->num_rows);
304 304
 
305
-        /* Check for limit in number of listed items */
305
+		/* Check for limit in number of listed items */
306 306
 	$full = isFull($myconn,$typedesc,$tables);
307 307
 	if ($full) print '<p>'.htmlspecialchars("$typedesc has reached maximum value of ".$tables["$typedesc"]['limit'].' listed items.').'</p>';
308 308
 
309 309
 		if ($result->num_rows) {
310 310
 			print '<table><thead><tr><th>'.$type.'</th><th title="The date this object has been listed for the first time">DateAdd</th><th>DateMod</th><th>Exp</th><th>Status</th><th title="Number of times this object has been listed">#List</th><th>Authored by</th><th width="250">Reason</th><th>Action</th></tr></thead><tfoot><tr></tr></tfoot><tbody>'."\n";
311 311
 			$i=0;
312
-        		while ($riga = $result->fetch_array(MYSQLI_ASSOC)) {
312
+				while ($riga = $result->fetch_array(MYSQLI_ASSOC)) {
313 313
 				if (isListed($riga)) {
314 314
 					if ($tables["$typedesc"]['bl']) $listed='Listed';
315 315
 					else $listed='WhiteListed';
@@ -328,9 +328,9 @@  discard block
 block discarded – undo
328 328
 					$element = $riga["$type"];
329 329
 				}
330 330
 
331
-                		printf ("<tr id=id$i><td id='status$listed'>%s</td><td id='status$listed'>%s</td><td id='status$listed'>%s</td><td id='status$listed'>%s</td><td id='status$listed'>%s</td><td id='status$listed'>%s</td><td id='status$listed'>%s</td><td id='status$listed'>%s</td><td>%s</td></tr>\n", $element, $riga['date'], $riga['datemod'], $riga['exp'], $riga['active'], $riga['nlist'], $riga['user'],htmlspecialchars($riga['reason']),ask($myconn,$i,$listed,$tables,$typedesc,$element,$full,$user,$adm));
331
+						printf ("<tr id=id$i><td id='status$listed'>%s</td><td id='status$listed'>%s</td><td id='status$listed'>%s</td><td id='status$listed'>%s</td><td id='status$listed'>%s</td><td id='status$listed'>%s</td><td id='status$listed'>%s</td><td id='status$listed'>%s</td><td>%s</td></tr>\n", $element, $riga['date'], $riga['datemod'], $riga['exp'], $riga['active'], $riga['nlist'], $riga['user'],htmlspecialchars($riga['reason']),ask($myconn,$i,$listed,$tables,$typedesc,$element,$full,$user,$adm));
332 332
 				$i++;
333
-        		}
333
+				}
334 334
 			print '</tbody></table>';
335 335
 		}
336 336
 		else {
@@ -348,15 +348,15 @@  discard block
 block discarded – undo
348 348
 
349 349
 function sendEmailWarn($tplf,$from,$to,$sbj,$emailListed,$intervalToExpire,$detail) {
350 350
 	$now = time();
351
-        setlocale (LC_TIME, 'it_IT');
352
-        $date = date("r",$now);
351
+		setlocale (LC_TIME, 'it_IT');
352
+		$date = date("r",$now);
353 353
 	$messageID = md5(uniqid($now,1)) . '@' . $_SERVER["HOSTNAME"];
354 354
 	$mua = 'PHP/' . phpversion();
355 355
 
356 356
 	/* Parsing headers */
357 357
 	if (!file_exists($tplf['header'])) {
358
-    		syslog(LOG_ERR, 'Sending email... template file <'.$tplf['header'].'> not found!');
359
-    		exit;
358
+			syslog(LOG_ERR, 'Sending email... template file <'.$tplf['header'].'> not found!');
359
+			exit;
360 360
 	}
361 361
 
362 362
 	$head_tmpl = file_get_contents($tplf['header']);
@@ -365,35 +365,35 @@  discard block
 block discarded – undo
365 365
 	$headers = str_replace($arr_tpl_vars, $arr_tpl_data, $head_tmpl);
366 366
 	$headers = preg_replace( '/\r|\n/', "\r\n", $headers );
367 367
 
368
-        /* Parsing body */
368
+		/* Parsing body */
369 369
 
370
-        if (!file_exists($tplf['body'])) {
371
-                syslog(LOG_ERR, 'Sending email... template file <'.$tplf['body'].'> not found!');
372
-                exit;
373
-        }
370
+		if (!file_exists($tplf['body'])) {
371
+				syslog(LOG_ERR, 'Sending email... template file <'.$tplf['body'].'> not found!');
372
+				exit;
373
+		}
374 374
 
375
-        $body_tmpl = file_get_contents($tplf['body']);
376
-        $arr_tpl_vars = array('{emailListed}','{expInterval}','{reason}');
377
-        $arr_tpl_data = array($emailListed,$intervalToExpire,$detail);
378
-        $body = str_replace($arr_tpl_vars, $arr_tpl_data, $body_tmpl);
379
-        $body = preg_replace( "/\r|\n/", "\r\n", $body );
375
+		$body_tmpl = file_get_contents($tplf['body']);
376
+		$arr_tpl_vars = array('{emailListed}','{expInterval}','{reason}');
377
+		$arr_tpl_data = array($emailListed,$intervalToExpire,$detail);
378
+		$body = str_replace($arr_tpl_vars, $arr_tpl_data, $body_tmpl);
379
+		$body = preg_replace( "/\r|\n/", "\r\n", $body );
380 380
 	$body = wordwrap ( $body, 75 , "\r\n" );	
381 381
 
382 382
 	/* Send the mail! */
383
-        if ( strlen(ini_get("safe_mode"))< 1) {
384
-                $old_mailfrom = ini_get("sendmail_from");
385
-                ini_set("sendmail_from", $from);
386
-                $params = sprintf("-oi -f %s", '<>');
387
-                if (!(mail($to,$sbj, $body,$headers,$params))) $flag=FALSE;
388
-                else $flag=TRUE;
389
-                if (isset($old_mailfrom))
390
-                        ini_set("sendmail_from", $old_mailfrom);
391
-        }
392
-        else {
393
-                if (!(mail($to,$sbj, $body,$headers))) $flag=FALSE;
394
-                else $flag=TRUE;
395
-        }
396
-        return $flag;
383
+		if ( strlen(ini_get("safe_mode"))< 1) {
384
+				$old_mailfrom = ini_get("sendmail_from");
385
+				ini_set("sendmail_from", $from);
386
+				$params = sprintf("-oi -f %s", '<>');
387
+				if (!(mail($to,$sbj, $body,$headers,$params))) $flag=FALSE;
388
+				else $flag=TRUE;
389
+				if (isset($old_mailfrom))
390
+						ini_set("sendmail_from", $old_mailfrom);
391
+		}
392
+		else {
393
+				if (!(mail($to,$sbj, $body,$headers))) $flag=FALSE;
394
+				else $flag=TRUE;
395
+		}
396
+		return $flag;
397 397
 }
398 398
 
399 399
 function emailToNotify($notify_file,$dom) {
@@ -407,59 +407,59 @@  discard block
 block discarded – undo
407 407
 function searchAndList ($myconn,$loguser,$tables,$typedesc,$value,$unit,&$quantity,$reason) {
408 408
 
409 409
 /* Search and list value */
410
-        $type = $tables["$typedesc"]['field'];
411
-        $table = $tables["$typedesc"]['name'];
412
-        $result = searchentry ($myconn,$value,$tables["$typedesc"]);
413
-
414
-        /* Manage abnormal conditions */
415
-        /* Value already present in db more than once. This is absurd. Panic! */
416
-        if ($result->num_rows > 1) {
417
-                syslog(LOG_EMERG,"$loguser: PANIC! Select for $type '$value' returned ". $result->num_rows ." items instead of one. Abnormal. Contact a sysadmin or a developer.");
418
-                $result->free();
419
-                return FALSE;
420
-        }
421
-
422
-        /* Value already present in db or not present: to list anyway */
423
-        if ($result->num_rows >= 0) {
424
-                /* First, check for limit in number of listed items */
425
-                if (isFull($myconn,$typedesc,$tables)) {
426
-                        syslog(LOG_EMERG,"$loguser: $typedesc has reached maximum value of ".$tables["$typedesc"]['limit'].' listed items. Abnormal exit.');
427
-                        $result->free();
428
-                        return FALSE;
429
-                }
430
-                /* Second, check if the (re)list would be consistent now */
431
-                if (! consistentListing($myconn,$tables,$typedesc,$value,$whynot) ) {
432
-                        syslog(LOG_ERR, $loguser.': '.$whynot);
433
-                        $result->free();
434
-                        return FALSE;
435
-                }
436
-        }
437
-        /* End of abnormal conditions */
438
-
439
-
440
-        /* Finally, here I can list the value! */
410
+		$type = $tables["$typedesc"]['field'];
411
+		$table = $tables["$typedesc"]['name'];
412
+		$result = searchentry ($myconn,$value,$tables["$typedesc"]);
413
+
414
+		/* Manage abnormal conditions */
415
+		/* Value already present in db more than once. This is absurd. Panic! */
416
+		if ($result->num_rows > 1) {
417
+				syslog(LOG_EMERG,"$loguser: PANIC! Select for $type '$value' returned ". $result->num_rows ." items instead of one. Abnormal. Contact a sysadmin or a developer.");
418
+				$result->free();
419
+				return FALSE;
420
+		}
421
+
422
+		/* Value already present in db or not present: to list anyway */
423
+		if ($result->num_rows >= 0) {
424
+				/* First, check for limit in number of listed items */
425
+				if (isFull($myconn,$typedesc,$tables)) {
426
+						syslog(LOG_EMERG,"$loguser: $typedesc has reached maximum value of ".$tables["$typedesc"]['limit'].' listed items. Abnormal exit.');
427
+						$result->free();
428
+						return FALSE;
429
+				}
430
+				/* Second, check if the (re)list would be consistent now */
431
+				if (! consistentListing($myconn,$tables,$typedesc,$value,$whynot) ) {
432
+						syslog(LOG_ERR, $loguser.': '.$whynot);
433
+						$result->free();
434
+						return FALSE;
435
+				}
436
+		}
437
+		/* End of abnormal conditions */
438
+
439
+
440
+		/* Finally, here I can list the value! */
441 441
 	$thisentry = $result->fetch_array(MYSQLI_ASSOC);
442
-        switch ($result->num_rows) {
443
-                /* Relist value if already present */
444
-                case 1:
445
-                        /* Entry already listed */
446
-                        if ( isListed($thisentry) ) {
447
-                                syslog(LOG_INFO, $loguser.': '.$value.' already listed. Nothing to do.');
448
-                                $result->free();
449
-                                return FALSE;
450
-                        }
451
-
452
-                        /* Entry delisted */
453
-                        $result->free();
442
+		switch ($result->num_rows) {
443
+				/* Relist value if already present */
444
+				case 1:
445
+						/* Entry already listed */
446
+						if ( isListed($thisentry) ) {
447
+								syslog(LOG_INFO, $loguser.': '.$value.' already listed. Nothing to do.');
448
+								$result->free();
449
+								return FALSE;
450
+						}
451
+
452
+						/* Entry delisted */
453
+						$result->free();
454 454
 			$quantity *= $thisentry['nlist'];
455
-                        return relist ($myconn,$loguser,$value,$type,$table,$unit,$quantity,$reason);
455
+						return relist ($myconn,$loguser,$value,$type,$table,$unit,$quantity,$reason);
456 456
 
457 457
 
458
-                /* First time list value */
459
-                case 0:
460
-                        $result->free();
461
-                        return addtolist ($myconn,$loguser,$value,$type,$table,$unit,$quantity,$reason);
462
-        }
458
+				/* First time list value */
459
+				case 0:
460
+						$result->free();
461
+						return addtolist ($myconn,$loguser,$value,$type,$table,$unit,$quantity,$reason);
462
+		}
463 463
 }
464 464
 
465 465
 
Please login to merge, or discard this patch.
Spacing   +104 added lines, -104 removed lines patch added patch discarded remove patch
@@ -1,25 +1,25 @@  discard block
 block discarded – undo
1 1
 <?php
2 2
 
3
-$version='1.9d';
3
+$version = '1.9d';
4 4
 
5 5
 function username() {
6 6
 	if (isset ($_SERVER['REMOTE_USER'])) $user = $_SERVER['REMOTE_USER'];
7 7
         	else if (isset ($_SERVER['USER'])) $user = $_SERVER['USER'];
8
-                	else $user='unknown';
8
+                	else $user = 'unknown';
9 9
 	return $user;
10 10
 }
11 11
 
12 12
 
13
-function addtolist ($myconn,$user,$value,$type,$table,$expUnit,$expQ,$myreason) {
13
+function addtolist($myconn, $user, $value, $type, $table, $expUnit, $expQ, $myreason) {
14 14
 // See MySQL manual for $expQ and $expUnit at
15 15
 // https://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_timestampadd
16 16
 
17
-	$result=FALSE;
18
-	$sub=array();
17
+	$result = FALSE;
18
+	$sub = array();
19 19
 
20 20
 	switch ($type) {
21 21
 	  case 'ip':
22
-		$query= sprintf("INSERT INTO `$table` (
22
+		$query = sprintf("INSERT INTO `$table` (
23 23
 			`$type` ,
24 24
 			`date` ,
25 25
 			`exp` ,
@@ -30,12 +30,12 @@  discard block
 block discarded – undo
30 30
 		VALUES (
31 31
 			INET_ATON( '%s' ) ,
32 32
 			CURRENT_TIMESTAMP , TIMESTAMPADD(%s,%d,CURRENT_TIMESTAMP), '1', '%s', '%s'
33
-		)" ,$value,$expUnit,$expQ,$user,$myreason);
33
+		)", $value, $expUnit, $expQ, $user, $myreason);
34 34
 		break;
35 35
 
36 36
 	  case 'network':
37
-		list($sub['net'],$sub['mask'])=explode('/',$value);
38
-                $query= sprintf("INSERT INTO `$table` (
37
+		list($sub['net'], $sub['mask']) = explode('/', $value);
38
+                $query = sprintf("INSERT INTO `$table` (
39 39
                         `$type` ,
40 40
 			`netmask`,
41 41
                         `date` ,
@@ -47,11 +47,11 @@  discard block
 block discarded – undo
47 47
                 VALUES (
48 48
                         INET_ATON( '%s' ) , INET_ATON( '%s' ) ,
49 49
                         CURRENT_TIMESTAMP , TIMESTAMPADD(%s,%d,CURRENT_TIMESTAMP), '1', '%s', '%s'
50
-                )" ,$sub['net'],$sub['mask'],$expUnit,$expQ,$user,$myreason);
50
+                )", $sub['net'], $sub['mask'], $expUnit, $expQ, $user, $myreason);
51 51
                 break;
52 52
 
53 53
 	  default:
54
-                $query= sprintf("INSERT INTO `$table` (
54
+                $query = sprintf("INSERT INTO `$table` (
55 55
                         `$type` ,
56 56
                         `date` ,
57 57
                         `exp` ,
@@ -62,60 +62,60 @@  discard block
 block discarded – undo
62 62
                 VALUES (
63 63
                         '%s' ,
64 64
                         CURRENT_TIMESTAMP , TIMESTAMPADD(%s,%d,CURRENT_TIMESTAMP), '1', '%s', '%s'
65
-                )" ,$value,$expUnit,$expQ,$user,$myreason);
65
+                )", $value, $expUnit, $expQ, $user, $myreason);
66 66
 	}
67 67
 
68 68
 	if ($myconn->query($query) === TRUE) {
69 69
 	    syslog(LOG_INFO, "$user: $type <$value> successfully listed on <$table> for $expQ $expUnit.");
70
-	    $result=TRUE;
70
+	    $result = TRUE;
71 71
 	}
72 72
 	else syslog(LOG_ERR, "$user: Error: ".$myconn->error);
73 73
 	return $result;
74 74
 }
75 75
 
76
-function relist ($myconn,$user,$value,$type,$table,$expUnit,$expQ,$myreason) {
76
+function relist($myconn, $user, $value, $type, $table, $expUnit, $expQ, $myreason) {
77 77
 
78
-	$result=FALSE;
78
+	$result = FALSE;
79 79
 
80 80
         switch ($type) {
81 81
 	  case 'ip':
82
-                $query= sprintf("UPDATE `$table` SET
82
+                $query = sprintf("UPDATE `$table` SET
83 83
 			`active` = '1',
84 84
 			`user` = '%s',
85 85
 			`exp` = TIMESTAMPADD(%s,%d,CURRENT_TIMESTAMP),
86 86
 			`nlist` = `nlist` + 1,
87 87
 			`reason` = '%s'
88
-			WHERE `$table`.`$type` = INET_ATON('%s') LIMIT 1" ,$user,$expUnit,$expQ,$myreason,$value);
88
+			WHERE `$table`.`$type` = INET_ATON('%s') LIMIT 1", $user, $expUnit, $expQ, $myreason, $value);
89 89
 		break;
90 90
           case 'network':
91
-		list($sub['net'],$sub['mask'])=explode('/',$value);
92
-                $query= sprintf("UPDATE `$table` SET
91
+		list($sub['net'], $sub['mask']) = explode('/', $value);
92
+                $query = sprintf("UPDATE `$table` SET
93 93
                         `active` = '1',
94 94
                         `user` = '%s',
95 95
                         `exp` = TIMESTAMPADD(%s,%d,CURRENT_TIMESTAMP),
96 96
                         `nlist` = `nlist` + 1,
97 97
                         `reason` = '%s'
98
-                        WHERE (`$table`.`$type` = INET_ATON('%s') AND `$table`.`netmask` = INET_ATON('%s')) LIMIT 1" ,$user,$expUnit,$expQ,$myreason,$sub['net'],$sub['mask']);
98
+                        WHERE (`$table`.`$type` = INET_ATON('%s') AND `$table`.`netmask` = INET_ATON('%s')) LIMIT 1", $user, $expUnit, $expQ, $myreason, $sub['net'], $sub['mask']);
99 99
 		break;
100 100
 	  default:
101
-                $query= sprintf("UPDATE `$table` SET
101
+                $query = sprintf("UPDATE `$table` SET
102 102
                         `active` = '1',
103 103
                         `user` = '%s',
104 104
                         `exp` = TIMESTAMPADD(%s,%d,CURRENT_TIMESTAMP),
105 105
                         `nlist` = `nlist` + 1,
106 106
                         `reason` = '%s'
107
-			WHERE `$table`.`$type` = '%s' LIMIT 1" ,$user,$expUnit,$expQ,$myreason,$value);
107
+			WHERE `$table`.`$type` = '%s' LIMIT 1", $user, $expUnit, $expQ, $myreason, $value);
108 108
 	}
109 109
 
110 110
         if ($myconn->query($query) === TRUE) {
111 111
             syslog(LOG_INFO, "$user: relist $type <$value> on <$table> for $expQ $expUnit.");
112
-		$result=TRUE;
112
+		$result = TRUE;
113 113
         }
114
-        else syslog (LOG_ERR, "$user: Error: ". $myconn->error);
114
+        else syslog(LOG_ERR, "$user: Error: ".$myconn->error);
115 115
 	return $result;
116 116
 }
117 117
 
118
-function remove ($myconn,$user,$value,$type,$table) {
118
+function remove($myconn, $user, $value, $type, $table) {
119 119
 
120 120
         switch ($type) {
121 121
           case 'ip':
@@ -123,10 +123,10 @@  discard block
 block discarded – undo
123 123
                         `$table`.`$type` = INET_ATON('%s') LIMIT 1", $value);
124 124
 		break;
125 125
 	  case 'network':
126
-		list($sub['net'],$sub['mask'])=explode('/',$value);
126
+		list($sub['net'], $sub['mask']) = explode('/', $value);
127 127
 		$query = sprintf("DELETE FROM `$table` WHERE
128 128
 			`$table`.`$type` = INET_ATON('%s') AND `$table`.`netmask` = INET_ATON('%s') LIMIT 1",
129
-			$sub['net'],$sub['mask']);
129
+			$sub['net'], $sub['mask']);
130 130
 		break;
131 131
 	  default:
132 132
 		$query = sprintf("DELETE FROM `$table` WHERE
@@ -134,39 +134,39 @@  discard block
 block discarded – undo
134 134
 	}
135 135
 
136 136
 
137
-        if ($return=$myconn->query($query) === TRUE) 
137
+        if ($return = $myconn->query($query) === TRUE) 
138 138
             syslog(LOG_INFO, "$user: permanently DELETED $type <$value> from <$table>.");
139
-        else syslog(LOG_ERR, "$user: Error: ". $myconn->error);
139
+        else syslog(LOG_ERR, "$user: Error: ".$myconn->error);
140 140
 
141 141
         return $return;
142 142
 }
143 143
 
144 144
 
145
-function changestatus ($myconn,$user,$value,$status,$type,$table) {
145
+function changestatus($myconn, $user, $value, $status, $type, $table) {
146 146
 
147 147
 	switch ($type) {
148 148
           case 'ip':
149
-		$query= sprintf("UPDATE `$table` SET `active` = '$status', `user` = '%s' WHERE `$table`.`$type` = INET_ATON('%s') LIMIT 1" ,$user, $value);
149
+		$query = sprintf("UPDATE `$table` SET `active` = '$status', `user` = '%s' WHERE `$table`.`$type` = INET_ATON('%s') LIMIT 1", $user, $value);
150 150
 		break;
151 151
 	  case 'network':
152
-		list($sub['net'],$sub['mask'])=explode('/',$value);
153
-		$query= sprintf("UPDATE `$table` SET `active` = '$status', `user` = '%s' WHERE (`$table`.`$type` = INET_ATON('%s') AND `$table`.`netmask` = INET_ATON('%s')) LIMIT 1" ,$user, $sub['net'],$sub['mask']);
152
+		list($sub['net'], $sub['mask']) = explode('/', $value);
153
+		$query = sprintf("UPDATE `$table` SET `active` = '$status', `user` = '%s' WHERE (`$table`.`$type` = INET_ATON('%s') AND `$table`.`netmask` = INET_ATON('%s')) LIMIT 1", $user, $sub['net'], $sub['mask']);
154 154
 		break;
155 155
 	  default:
156
-		$query= sprintf("UPDATE `$table` SET `active` = '$status', `user` = '%s' WHERE `$table`.`$type` = '%s' LIMIT 1" ,$user, $value);
156
+		$query = sprintf("UPDATE `$table` SET `active` = '$status', `user` = '%s' WHERE `$table`.`$type` = '%s' LIMIT 1", $user, $value);
157 157
 	}
158 158
 
159
-        if ($return=$myconn->query($query) === TRUE) {
159
+        if ($return = $myconn->query($query) === TRUE) {
160 160
             syslog(LOG_INFO, "$user: change status of $type <$value>. The status is now <$status>");
161 161
         }
162
-        else syslog(LOG_ERR, "$user: Error: ". $myconn->error);
162
+        else syslog(LOG_ERR, "$user: Error: ".$myconn->error);
163 163
 	return $return;	
164 164
 }
165 165
 
166 166
 
167
-function expire ($myconn,$user,$tables,$expireTime) {
168
-        $return=TRUE;
169
-	$log=array();
167
+function expire($myconn, $user, $tables, $expireTime) {
168
+        $return = TRUE;
169
+	$log = array();
170 170
 	$desc = array_keys($tables);
171 171
 	foreach ($desc as $tdesc) { 
172 172
 		/* QUERY */
@@ -185,11 +185,11 @@  discard block
 block discarded – undo
185 185
 			} while ($myconn->next_result());
186 186
 		}
187 187
 		else {
188
-			syslog(LOG_ERR, "Expire job - Error: ". $myconn->error);
188
+			syslog(LOG_ERR, "Expire job - Error: ".$myconn->error);
189 189
 			$return = FALSE;
190 190
 		}
191 191
 	}
192
-	if ( !($return) ) syslog(LOG_EMERG, 'End of Expire job with error. See above logs. SQL Connection terminated');
192
+	if (!($return)) syslog(LOG_EMERG, 'End of Expire job with error. See above logs. SQL Connection terminated');
193 193
 	else  syslog(LOG_INFO, 'Successfully End of Expire job. SQL Connection successfully terminated.');
194 194
         return $return;
195 195
 }
@@ -197,22 +197,22 @@  discard block
 block discarded – undo
197 197
 
198 198
 function isListed($row) {
199 199
 
200
-	$exp=new DateTime($row['exp']);
201
-	$now=new DateTime('NOW');
202
-	if (($exp > $now) and ($row['active'])) return true;
200
+	$exp = new DateTime($row['exp']);
201
+	$now = new DateTime('NOW');
202
+	if (($exp>$now) and ($row['active'])) return true;
203 203
 	else return false;
204 204
 
205 205
 }
206 206
 
207 207
 
208
-function ask($myconn,$id,$what,$alltables,$typedesc,$value,$lock,$user,$adm) {
208
+function ask($myconn, $id, $what, $alltables, $typedesc, $value, $lock, $user, $adm) {
209 209
 
210
-	$whynot=NULL;
210
+	$whynot = NULL;
211 211
 	switch ($what) {
212 212
 		case 'Ok':
213 213
 			if ($lock) return NULL;
214
-			if (in_array($user,array_keys($adm)))
215
-				if ( consistentListing($myconn,$alltables,$typedesc,$value,$whynot) ) return require('relistButton.php');
214
+			if (in_array($user, array_keys($adm)))
215
+				if (consistentListing($myconn, $alltables, $typedesc, $value, $whynot)) return require('relistButton.php');
216 216
 			return htmlspecialchars($whynot);
217 217
 		case 'Listed':
218 218
 		case 'WhiteListed':
@@ -221,17 +221,17 @@  discard block
 block discarded – undo
221 221
 }
222 222
 
223 223
 
224
-function consistentListing($myconn,$alltables,$typed,$value,&$warn) {
224
+function consistentListing($myconn, $alltables, $typed, $value, &$warn) {
225 225
 /* Check if there are no pending mislisting */
226 226
 	$warn = NULL;
227 227
 	foreach ($alltables["$typed"]['depend'] as $listdep) {
228
-		if ($alltables["$typed"]['field'] != $alltables["$listdep"]['field'] ) {
228
+		if ($alltables["$typed"]['field'] != $alltables["$listdep"]['field']) {
229 229
 			$warn = "Config ERROR: <$typed> and <$listdep> are of different types! I can't check consistency!";
230 230
 			return FALSE;
231 231
 		}
232
-		$entry = searchentry($myconn,$value,$alltables["$listdep"]);
233
-		if ( $entry->num_rows ) {
234
-			if ( $entry->num_rows == 1 ) {
232
+		$entry = searchentry($myconn, $value, $alltables["$listdep"]);
233
+		if ($entry->num_rows) {
234
+			if ($entry->num_rows == 1) {
235 235
 				$riga = $entry->fetch_array(MYSQLI_ASSOC);
236 236
                         	if (isListed($riga)) {
237 237
 					$warn = "<$value> is already present in <$listdep> list!";
@@ -239,7 +239,7 @@  discard block
 block discarded – undo
239 239
 					return FALSE;
240 240
 				}
241 241
 			}
242
-			if ( $entry->num_rows > 1 ) {$warn = "<$value> seems to be present more than once in <$listdep>. Contact a sysadmin NOW!";}
242
+			if ($entry->num_rows>1) {$warn = "<$value> seems to be present more than once in <$listdep>. Contact a sysadmin NOW!"; }
243 243
 		}
244 244
 		$entry->free();
245 245
 	}
@@ -247,7 +247,7 @@  discard block
 block discarded – undo
247 247
 	return TRUE;
248 248
 }
249 249
 
250
-function searchentry ($myconn,$value,$tablelist) {
250
+function searchentry($myconn, $value, $tablelist) {
251 251
 /* Make a MYSQL query and return result */
252 252
 
253 253
         $type = $tablelist['field'];
@@ -257,24 +257,24 @@  discard block
 block discarded – undo
257 257
         else {
258 258
                 switch ($type) {
259 259
                   case 'ip':
260
-                        $query= "select * from $table where $type =  INET_ATON('$value')";
260
+                        $query = "select * from $table where $type =  INET_ATON('$value')";
261 261
                         break;
262 262
                   case 'network':
263
-                        list($sub['net'],$sub['mask'])=explode('/',$value);
264
-                        $query= 'select * from '.$table.' where (((inet_aton(\''.$sub['net'].'\') | (~ inet_aton(\''.$sub['mask'].'\'))) & netmask) = network)';
263
+                        list($sub['net'], $sub['mask']) = explode('/', $value);
264
+                        $query = 'select * from '.$table.' where (((inet_aton(\''.$sub['net'].'\') | (~ inet_aton(\''.$sub['mask'].'\'))) & netmask) = network)';
265 265
                         break;
266 266
                   default:
267
-                        $query= "select * from $table where $type = '$value'";
267
+                        $query = "select * from $table where $type = '$value'";
268 268
                 }
269 269
         }
270 270
 
271 271
 	$result = $myconn->query($query);
272
-	if($result === false)
272
+	if ($result === false)
273 273
 		syslog(LOG_EMERG, "ALERT: Query <$query> failed: ".$myconn->error);
274 274
         return $result;
275 275
 }
276 276
 
277
-function countListed ($myconn,$table) {
277
+function countListed($myconn, $table) {
278 278
 /* Return number of current listed items into a rbl table */
279 279
 	$query = "SELECT COUNT(*) as `count` FROM `$table` WHERE (`active`=1 AND TIMESTAMPDIFF(MICROSECOND,NOW(),`exp`)>0) GROUP BY `active` ORDER BY `count` DESC LIMIT 1";
280 280
 	$row = $myconn->query($query);
@@ -285,37 +285,37 @@  discard block
 block discarded – undo
285 285
 }
286 286
 
287 287
 
288
-function isFull($myconn,$typedesc,$alltables) {
288
+function isFull($myconn, $typedesc, $alltables) {
289 289
         if (isset($alltables["$typedesc"]['limit'])) {
290
-                if ( countListed($myconn,$alltables["$typedesc"]['name']) >= $alltables["$typedesc"]['limit'] ) 
290
+                if (countListed($myconn, $alltables["$typedesc"]['name'])>=$alltables["$typedesc"]['limit']) 
291 291
                         return TRUE;
292 292
         }
293 293
 	return FALSE;
294 294
 }
295 295
 
296
-function rlookup ($myconn,$user,$adm,$value,$typedesc,$tables) {
296
+function rlookup($myconn, $user, $adm, $value, $typedesc, $tables) {
297 297
 
298 298
 	$type = $tables["$typedesc"]['field'];
299
-	$whynot=NULL;
299
+	$whynot = NULL;
300 300
 
301
-	$result = searchentry ($myconn,$value,$tables["$typedesc"]);
301
+	$result = searchentry($myconn, $value, $tables["$typedesc"]);
302 302
 	if ($result) {
303 303
 		printf("<pre>Your request for $type &lt;$value&gt; returned %d items.\n</pre>", $result->num_rows);
304 304
 
305 305
         /* Check for limit in number of listed items */
306
-	$full = isFull($myconn,$typedesc,$tables);
306
+	$full = isFull($myconn, $typedesc, $tables);
307 307
 	if ($full) print '<p>'.htmlspecialchars("$typedesc has reached maximum value of ".$tables["$typedesc"]['limit'].' listed items.').'</p>';
308 308
 
309 309
 		if ($result->num_rows) {
310 310
 			print '<table><thead><tr><th>'.$type.'</th><th title="The date this object has been listed for the first time">DateAdd</th><th>DateMod</th><th>Exp</th><th>Status</th><th title="Number of times this object has been listed">#List</th><th>Authored by</th><th width="250">Reason</th><th>Action</th></tr></thead><tfoot><tr></tr></tfoot><tbody>'."\n";
311
-			$i=0;
311
+			$i = 0;
312 312
         		while ($riga = $result->fetch_array(MYSQLI_ASSOC)) {
313 313
 				if (isListed($riga)) {
314
-					if ($tables["$typedesc"]['bl']) $listed='Listed';
315
-					else $listed='WhiteListed';
314
+					if ($tables["$typedesc"]['bl']) $listed = 'Listed';
315
+					else $listed = 'WhiteListed';
316 316
 				}	
317 317
 				else
318
-					$listed='Ok';
318
+					$listed = 'Ok';
319 319
 
320 320
 				switch ($type) {
321 321
 				  case 'ip':
@@ -328,15 +328,15 @@  discard block
 block discarded – undo
328 328
 					$element = $riga["$type"];
329 329
 				}
330 330
 
331
-                		printf ("<tr id=id$i><td id='status$listed'>%s</td><td id='status$listed'>%s</td><td id='status$listed'>%s</td><td id='status$listed'>%s</td><td id='status$listed'>%s</td><td id='status$listed'>%s</td><td id='status$listed'>%s</td><td id='status$listed'>%s</td><td>%s</td></tr>\n", $element, $riga['date'], $riga['datemod'], $riga['exp'], $riga['active'], $riga['nlist'], $riga['user'],htmlspecialchars($riga['reason']),ask($myconn,$i,$listed,$tables,$typedesc,$element,$full,$user,$adm));
331
+                		printf("<tr id=id$i><td id='status$listed'>%s</td><td id='status$listed'>%s</td><td id='status$listed'>%s</td><td id='status$listed'>%s</td><td id='status$listed'>%s</td><td id='status$listed'>%s</td><td id='status$listed'>%s</td><td id='status$listed'>%s</td><td>%s</td></tr>\n", $element, $riga['date'], $riga['datemod'], $riga['exp'], $riga['active'], $riga['nlist'], $riga['user'], htmlspecialchars($riga['reason']), ask($myconn, $i, $listed, $tables, $typedesc, $element, $full, $user, $adm));
332 332
 				$i++;
333 333
         		}
334 334
 			print '</tbody></table>';
335 335
 		}
336 336
 		else {
337 337
 			print "<pre>$type &lt;$value&gt; is not listed!\n</pre>";
338
-			if ( in_array($user,array_keys($adm)) AND ($value != 'ALL') )
339
-				if ( (!$full) AND (consistentListing($myconn,$tables,$typedesc,$value,$whynot)) ) require_once('listForm.php');
338
+			if (in_array($user, array_keys($adm)) AND ($value != 'ALL'))
339
+				if ((!$full) AND (consistentListing($myconn, $tables, $typedesc, $value, $whynot))) require_once('listForm.php');
340 340
 									else print '<p>'.htmlspecialchars($whynot).'</p>';
341 341
 				
342 342
 		}
@@ -346,12 +346,12 @@  discard block
 block discarded – undo
346 346
 }
347 347
 
348 348
 
349
-function sendEmailWarn($tplf,$from,$to,$sbj,$emailListed,$intervalToExpire,$detail) {
349
+function sendEmailWarn($tplf, $from, $to, $sbj, $emailListed, $intervalToExpire, $detail) {
350 350
 	$now = time();
351
-        setlocale (LC_TIME, 'it_IT');
352
-        $date = date("r",$now);
353
-	$messageID = md5(uniqid($now,1)) . '@' . $_SERVER["HOSTNAME"];
354
-	$mua = 'PHP/' . phpversion();
351
+        setlocale(LC_TIME, 'it_IT');
352
+        $date = date("r", $now);
353
+	$messageID = md5(uniqid($now, 1)).'@'.$_SERVER["HOSTNAME"];
354
+	$mua = 'PHP/'.phpversion();
355 355
 
356 356
 	/* Parsing headers */
357 357
 	if (!file_exists($tplf['header'])) {
@@ -360,10 +360,10 @@  discard block
 block discarded – undo
360 360
 	}
361 361
 
362 362
 	$head_tmpl = file_get_contents($tplf['header']);
363
-	$arr_tpl_vars = array('{from}','{to}','{date}','{messageID}','{mua}');
364
-	$arr_tpl_data = array($from,$to,$date,$messageID,$mua);
363
+	$arr_tpl_vars = array('{from}', '{to}', '{date}', '{messageID}', '{mua}');
364
+	$arr_tpl_data = array($from, $to, $date, $messageID, $mua);
365 365
 	$headers = str_replace($arr_tpl_vars, $arr_tpl_data, $head_tmpl);
366
-	$headers = preg_replace( '/\r|\n/', "\r\n", $headers );
366
+	$headers = preg_replace('/\r|\n/', "\r\n", $headers);
367 367
 
368 368
         /* Parsing body */
369 369
 
@@ -373,62 +373,62 @@  discard block
 block discarded – undo
373 373
         }
374 374
 
375 375
         $body_tmpl = file_get_contents($tplf['body']);
376
-        $arr_tpl_vars = array('{emailListed}','{expInterval}','{reason}');
377
-        $arr_tpl_data = array($emailListed,$intervalToExpire,$detail);
376
+        $arr_tpl_vars = array('{emailListed}', '{expInterval}', '{reason}');
377
+        $arr_tpl_data = array($emailListed, $intervalToExpire, $detail);
378 378
         $body = str_replace($arr_tpl_vars, $arr_tpl_data, $body_tmpl);
379
-        $body = preg_replace( "/\r|\n/", "\r\n", $body );
380
-	$body = wordwrap ( $body, 75 , "\r\n" );	
379
+        $body = preg_replace("/\r|\n/", "\r\n", $body);
380
+	$body = wordwrap($body, 75, "\r\n");	
381 381
 
382 382
 	/* Send the mail! */
383
-        if ( strlen(ini_get("safe_mode"))< 1) {
383
+        if (strlen(ini_get("safe_mode"))<1) {
384 384
                 $old_mailfrom = ini_get("sendmail_from");
385 385
                 ini_set("sendmail_from", $from);
386 386
                 $params = sprintf("-oi -f %s", '<>');
387
-                if (!(mail($to,$sbj, $body,$headers,$params))) $flag=FALSE;
388
-                else $flag=TRUE;
387
+                if (!(mail($to, $sbj, $body, $headers, $params))) $flag = FALSE;
388
+                else $flag = TRUE;
389 389
                 if (isset($old_mailfrom))
390 390
                         ini_set("sendmail_from", $old_mailfrom);
391 391
         }
392 392
         else {
393
-                if (!(mail($to,$sbj, $body,$headers))) $flag=FALSE;
394
-                else $flag=TRUE;
393
+                if (!(mail($to, $sbj, $body, $headers))) $flag = FALSE;
394
+                else $flag = TRUE;
395 395
         }
396 396
         return $flag;
397 397
 }
398 398
 
399
-function emailToNotify($notify_file,$dom) {
399
+function emailToNotify($notify_file, $dom) {
400 400
 	$ini_array = parse_ini_file($notify_file);
401
-	if (in_array($dom,array_keys($ini_array)))
401
+	if (in_array($dom, array_keys($ini_array)))
402 402
 		return $ini_array["$dom"];
403 403
 	else return FALSE;
404 404
 }
405 405
 
406 406
 
407
-function searchAndList ($myconn,$loguser,$tables,$typedesc,$value,$unit,&$quantity,$reason) {
407
+function searchAndList($myconn, $loguser, $tables, $typedesc, $value, $unit, &$quantity, $reason) {
408 408
 
409 409
 /* Search and list value */
410 410
         $type = $tables["$typedesc"]['field'];
411 411
         $table = $tables["$typedesc"]['name'];
412
-        $result = searchentry ($myconn,$value,$tables["$typedesc"]);
412
+        $result = searchentry($myconn, $value, $tables["$typedesc"]);
413 413
 
414 414
         /* Manage abnormal conditions */
415 415
         /* Value already present in db more than once. This is absurd. Panic! */
416
-        if ($result->num_rows > 1) {
417
-                syslog(LOG_EMERG,"$loguser: PANIC! Select for $type '$value' returned ". $result->num_rows ." items instead of one. Abnormal. Contact a sysadmin or a developer.");
416
+        if ($result->num_rows>1) {
417
+                syslog(LOG_EMERG, "$loguser: PANIC! Select for $type '$value' returned ".$result->num_rows." items instead of one. Abnormal. Contact a sysadmin or a developer.");
418 418
                 $result->free();
419 419
                 return FALSE;
420 420
         }
421 421
 
422 422
         /* Value already present in db or not present: to list anyway */
423
-        if ($result->num_rows >= 0) {
423
+        if ($result->num_rows>=0) {
424 424
                 /* First, check for limit in number of listed items */
425
-                if (isFull($myconn,$typedesc,$tables)) {
426
-                        syslog(LOG_EMERG,"$loguser: $typedesc has reached maximum value of ".$tables["$typedesc"]['limit'].' listed items. Abnormal exit.');
425
+                if (isFull($myconn, $typedesc, $tables)) {
426
+                        syslog(LOG_EMERG, "$loguser: $typedesc has reached maximum value of ".$tables["$typedesc"]['limit'].' listed items. Abnormal exit.');
427 427
                         $result->free();
428 428
                         return FALSE;
429 429
                 }
430 430
                 /* Second, check if the (re)list would be consistent now */
431
-                if (! consistentListing($myconn,$tables,$typedesc,$value,$whynot) ) {
431
+                if (!consistentListing($myconn, $tables, $typedesc, $value, $whynot)) {
432 432
                         syslog(LOG_ERR, $loguser.': '.$whynot);
433 433
                         $result->free();
434 434
                         return FALSE;
@@ -443,7 +443,7 @@  discard block
 block discarded – undo
443 443
                 /* Relist value if already present */
444 444
                 case 1:
445 445
                         /* Entry already listed */
446
-                        if ( isListed($thisentry) ) {
446
+                        if (isListed($thisentry)) {
447 447
                                 syslog(LOG_INFO, $loguser.': '.$value.' already listed. Nothing to do.');
448 448
                                 $result->free();
449 449
                                 return FALSE;
@@ -452,13 +452,13 @@  discard block
 block discarded – undo
452 452
                         /* Entry delisted */
453 453
                         $result->free();
454 454
 			$quantity *= $thisentry['nlist'];
455
-                        return relist ($myconn,$loguser,$value,$type,$table,$unit,$quantity,$reason);
455
+                        return relist($myconn, $loguser, $value, $type, $table, $unit, $quantity, $reason);
456 456
 
457 457
 
458 458
                 /* First time list value */
459 459
                 case 0:
460 460
                         $result->free();
461
-                        return addtolist ($myconn,$loguser,$value,$type,$table,$unit,$quantity,$reason);
461
+                        return addtolist($myconn, $loguser, $value, $type, $table, $unit, $quantity, $reason);
462 462
         }
463 463
 }
464 464
 
Please login to merge, or discard this patch.
Braces   +84 added lines, -49 removed lines patch added patch discarded remove patch
@@ -3,9 +3,13 @@  discard block
 block discarded – undo
3 3
 $version='1.9d';
4 4
 
5 5
 function username() {
6
-	if (isset ($_SERVER['REMOTE_USER'])) $user = $_SERVER['REMOTE_USER'];
7
-        	else if (isset ($_SERVER['USER'])) $user = $_SERVER['USER'];
8
-                	else $user='unknown';
6
+	if (isset ($_SERVER['REMOTE_USER'])) {
7
+		$user = $_SERVER['REMOTE_USER'];
8
+	} else if (isset ($_SERVER['USER'])) {
9
+        		$user = $_SERVER['USER'];
10
+        	} else {
11
+                		$user='unknown';
12
+                	}
9 13
 	return $user;
10 14
 }
11 15
 
@@ -68,8 +72,9 @@  discard block
 block discarded – undo
68 72
 	if ($myconn->query($query) === TRUE) {
69 73
 	    syslog(LOG_INFO, "$user: $type <$value> successfully listed on <$table> for $expQ $expUnit.");
70 74
 	    $result=TRUE;
75
+	} else {
76
+		syslog(LOG_ERR, "$user: Error: ".$myconn->error);
71 77
 	}
72
-	else syslog(LOG_ERR, "$user: Error: ".$myconn->error);
73 78
 	return $result;
74 79
 }
75 80
 
@@ -110,8 +115,9 @@  discard block
 block discarded – undo
110 115
         if ($myconn->query($query) === TRUE) {
111 116
             syslog(LOG_INFO, "$user: relist $type <$value> on <$table> for $expQ $expUnit.");
112 117
 		$result=TRUE;
118
+        } else {
119
+        	syslog (LOG_ERR, "$user: Error: ". $myconn->error);
113 120
         }
114
-        else syslog (LOG_ERR, "$user: Error: ". $myconn->error);
115 121
 	return $result;
116 122
 }
117 123
 
@@ -134,9 +140,11 @@  discard block
 block discarded – undo
134 140
 	}
135 141
 
136 142
 
137
-        if ($return=$myconn->query($query) === TRUE) 
138
-            syslog(LOG_INFO, "$user: permanently DELETED $type <$value> from <$table>.");
139
-        else syslog(LOG_ERR, "$user: Error: ". $myconn->error);
143
+        if ($return=$myconn->query($query) === TRUE) {
144
+                    syslog(LOG_INFO, "$user: permanently DELETED $type <$value> from <$table>.");
145
+        } else {
146
+        	syslog(LOG_ERR, "$user: Error: ". $myconn->error);
147
+        }
140 148
 
141 149
         return $return;
142 150
 }
@@ -158,8 +166,9 @@  discard block
 block discarded – undo
158 166
 
159 167
         if ($return=$myconn->query($query) === TRUE) {
160 168
             syslog(LOG_INFO, "$user: change status of $type <$value>. The status is now <$status>");
169
+        } else {
170
+        	syslog(LOG_ERR, "$user: Error: ". $myconn->error);
161 171
         }
162
-        else syslog(LOG_ERR, "$user: Error: ". $myconn->error);
163 172
 	return $return;	
164 173
 }
165 174
 
@@ -183,14 +192,16 @@  discard block
 block discarded – undo
183 192
 				$j++;
184 193
 
185 194
 			} while ($myconn->next_result());
186
-		}
187
-		else {
195
+		} else {
188 196
 			syslog(LOG_ERR, "Expire job - Error: ". $myconn->error);
189 197
 			$return = FALSE;
190 198
 		}
191 199
 	}
192
-	if ( !($return) ) syslog(LOG_EMERG, 'End of Expire job with error. See above logs. SQL Connection terminated');
193
-	else  syslog(LOG_INFO, 'Successfully End of Expire job. SQL Connection successfully terminated.');
200
+	if ( !($return) ) {
201
+		syslog(LOG_EMERG, 'End of Expire job with error. See above logs. SQL Connection terminated');
202
+	} else {
203
+		syslog(LOG_INFO, 'Successfully End of Expire job. SQL Connection successfully terminated.');
204
+	}
194 205
         return $return;
195 206
 }
196 207
 
@@ -199,8 +210,11 @@  discard block
 block discarded – undo
199 210
 
200 211
 	$exp=new DateTime($row['exp']);
201 212
 	$now=new DateTime('NOW');
202
-	if (($exp > $now) and ($row['active'])) return true;
203
-	else return false;
213
+	if (($exp > $now) and ($row['active'])) {
214
+		return true;
215
+	} else {
216
+		return false;
217
+	}
204 218
 
205 219
 }
206 220
 
@@ -210,9 +224,12 @@  discard block
 block discarded – undo
210 224
 	$whynot=NULL;
211 225
 	switch ($what) {
212 226
 		case 'Ok':
213
-			if ($lock) return NULL;
214
-			if (in_array($user,array_keys($adm)))
215
-				if ( consistentListing($myconn,$alltables,$typedesc,$value,$whynot) ) return require('relistButton.php');
227
+			if ($lock) {
228
+				return NULL;
229
+			}
230
+			if (in_array($user,array_keys($adm))) {
231
+							if ( consistentListing($myconn,$alltables,$typedesc,$value,$whynot) ) return require('relistButton.php');
232
+			}
216 233
 			return htmlspecialchars($whynot);
217 234
 		case 'Listed':
218 235
 		case 'WhiteListed':
@@ -253,8 +270,9 @@  discard block
 block discarded – undo
253 270
         $type = $tablelist['field'];
254 271
         $table = $tablelist['name'];
255 272
 
256
-        if ($value == 'ALL') $query = 'select * from '.$table;
257
-        else {
273
+        if ($value == 'ALL') {
274
+        	$query = 'select * from '.$table;
275
+        } else {
258 276
                 switch ($type) {
259 277
                   case 'ip':
260 278
                         $query= "select * from $table where $type =  INET_ATON('$value')";
@@ -269,8 +287,9 @@  discard block
 block discarded – undo
269 287
         }
270 288
 
271 289
 	$result = $myconn->query($query);
272
-	if($result === false)
273
-		syslog(LOG_EMERG, "ALERT: Query <$query> failed: ".$myconn->error);
290
+	if($result === false) {
291
+			syslog(LOG_EMERG, "ALERT: Query <$query> failed: ".$myconn->error);
292
+	}
274 293
         return $result;
275 294
 }
276 295
 
@@ -287,8 +306,9 @@  discard block
 block discarded – undo
287 306
 
288 307
 function isFull($myconn,$typedesc,$alltables) {
289 308
         if (isset($alltables["$typedesc"]['limit'])) {
290
-                if ( countListed($myconn,$alltables["$typedesc"]['name']) >= $alltables["$typedesc"]['limit'] ) 
291
-                        return TRUE;
309
+                if ( countListed($myconn,$alltables["$typedesc"]['name']) >= $alltables["$typedesc"]['limit'] ) {
310
+                                        return TRUE;
311
+                }
292 312
         }
293 313
 	return FALSE;
294 314
 }
@@ -304,18 +324,23 @@  discard block
 block discarded – undo
304 324
 
305 325
         /* Check for limit in number of listed items */
306 326
 	$full = isFull($myconn,$typedesc,$tables);
307
-	if ($full) print '<p>'.htmlspecialchars("$typedesc has reached maximum value of ".$tables["$typedesc"]['limit'].' listed items.').'</p>';
327
+	if ($full) {
328
+		print '<p>'.htmlspecialchars("$typedesc has reached maximum value of ".$tables["$typedesc"]['limit'].' listed items.').'</p>';
329
+	}
308 330
 
309 331
 		if ($result->num_rows) {
310 332
 			print '<table><thead><tr><th>'.$type.'</th><th title="The date this object has been listed for the first time">DateAdd</th><th>DateMod</th><th>Exp</th><th>Status</th><th title="Number of times this object has been listed">#List</th><th>Authored by</th><th width="250">Reason</th><th>Action</th></tr></thead><tfoot><tr></tr></tfoot><tbody>'."\n";
311 333
 			$i=0;
312 334
         		while ($riga = $result->fetch_array(MYSQLI_ASSOC)) {
313 335
 				if (isListed($riga)) {
314
-					if ($tables["$typedesc"]['bl']) $listed='Listed';
315
-					else $listed='WhiteListed';
316
-				}	
317
-				else
318
-					$listed='Ok';
336
+					if ($tables["$typedesc"]['bl']) {
337
+						$listed='Listed';
338
+					} else {
339
+						$listed='WhiteListed';
340
+					}
341
+				} else {
342
+									$listed='Ok';
343
+				}
319 344
 
320 345
 				switch ($type) {
321 346
 				  case 'ip':
@@ -332,18 +357,20 @@  discard block
 block discarded – undo
332 357
 				$i++;
333 358
         		}
334 359
 			print '</tbody></table>';
335
-		}
336
-		else {
360
+		} else {
337 361
 			print "<pre>$type &lt;$value&gt; is not listed!\n</pre>";
338
-			if ( in_array($user,array_keys($adm)) AND ($value != 'ALL') )
339
-				if ( (!$full) AND (consistentListing($myconn,$tables,$typedesc,$value,$whynot)) ) require_once('listForm.php');
340
-									else print '<p>'.htmlspecialchars($whynot).'</p>';
362
+			if ( in_array($user,array_keys($adm)) AND ($value != 'ALL') ) {
363
+							if ( (!$full) AND (consistentListing($myconn,$tables,$typedesc,$value,$whynot)) ) require_once('listForm.php');
364
+			} else {
365
+										print '<p>'.htmlspecialchars($whynot).'</p>';
366
+									}
341 367
 				
342 368
 		}
343 369
 		$result->free();
370
+	} else {
371
+		print '<pre>Query error or something wrong in DB schema'."\n</pre>";
372
+	}
344 373
 	}
345
-	else print '<pre>Query error or something wrong in DB schema'."\n</pre>";
346
-}
347 374
 
348 375
 
349 376
 function sendEmailWarn($tplf,$from,$to,$sbj,$emailListed,$intervalToExpire,$detail) {
@@ -384,24 +411,32 @@  discard block
 block discarded – undo
384 411
                 $old_mailfrom = ini_get("sendmail_from");
385 412
                 ini_set("sendmail_from", $from);
386 413
                 $params = sprintf("-oi -f %s", '<>');
387
-                if (!(mail($to,$sbj, $body,$headers,$params))) $flag=FALSE;
388
-                else $flag=TRUE;
389
-                if (isset($old_mailfrom))
390
-                        ini_set("sendmail_from", $old_mailfrom);
391
-        }
392
-        else {
393
-                if (!(mail($to,$sbj, $body,$headers))) $flag=FALSE;
394
-                else $flag=TRUE;
414
+                if (!(mail($to,$sbj, $body,$headers,$params))) {
415
+                	$flag=FALSE;
416
+                } else {
417
+                	$flag=TRUE;
418
+                }
419
+                if (isset($old_mailfrom)) {
420
+                                        ini_set("sendmail_from", $old_mailfrom);
421
+                }
422
+        } else {
423
+                if (!(mail($to,$sbj, $body,$headers))) {
424
+                	$flag=FALSE;
425
+                } else {
426
+                	$flag=TRUE;
427
+                }
395 428
         }
396 429
         return $flag;
397 430
 }
398 431
 
399 432
 function emailToNotify($notify_file,$dom) {
400 433
 	$ini_array = parse_ini_file($notify_file);
401
-	if (in_array($dom,array_keys($ini_array)))
402
-		return $ini_array["$dom"];
403
-	else return FALSE;
404
-}
434
+	if (in_array($dom,array_keys($ini_array))) {
435
+			return $ini_array["$dom"];
436
+	} else {
437
+		return FALSE;
438
+	}
439
+	}
405 440
 
406 441
 
407 442
 function searchAndList ($myconn,$loguser,$tables,$typedesc,$value,$unit,&$quantity,$reason) {
Please login to merge, or discard this patch.