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 ( f156e7...9e397c )
by Marco
02:06
created

function.php ➔ getPart()   B

Complexity

Conditions 7
Paths 7

Size

Total Lines 14
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 7
eloc 9
nc 7
nop 4
dl 0
loc 14
rs 8.2222
c 0
b 0
f 0
1
<?php
2
function getIP($header,$mxserver,$msa) {
3
/* Get submission server's IP from header's mail */
4
/* Each line must end with /r/n			 */
5
/* IP is the first one written by your mxserver	 */
6
7
	$ip = FALSE;
8
	$host = FALSE;
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--) {
12
#			print "Examine ".$received[0][$i]."\n";
13
			if ( preg_match($msa,$received['host'][$i]) )
14
				$dateR = $received['date'][$i];
15
        		foreach ($mxserver as $mx) {
16
        			if (!$ip)
17
					if ($mx == $received['host'][$i]) {
18
						$host = $received['host'][$i];
19
						$ip = $received['ip'][$i];
20
                    			}
21
                	}
22
        	}
23
	}
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;
28
	return array($ip,$host,$dateR,$dateC['date'],$mid['mid']);
29
}
30
31
function updateReport ($ip,$uid,$ipcount,$uidcount,$hostname,$dateC,$msgid,$dateL) {
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) );
34
}
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 );
38
}
39
40
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";
45
46
        /* Remove count index */
47
        $uids = array_keys($uidvet['uid']);
48
	$totlearn = 0;
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']);
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);
56
57
	return $return;
58
}
59
	
60
61
function array_msort($array, $cols)
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;
83
84
}
85
86
87
function summaryReportAndList ($cf,$myconn,$tables,$category,$vet,$key) {
88
	$nk = $vet['count'];
89
90
	if ( empty($vet) ) return NULL;
91
	
92
	$return = sprintf('<h3>Statistics by %s</h3><table><tr><th>%s</th><th>Learned by</th><th>Learned times</th><th title="This field doesn\'t say if this %s is currently listed, but it says if this %s has listed now!">Listed Now</th></tr>'."\n", strtoupper($key),strtoupper($key),$key,$key);
93
	
94
	$values = array_keys($vet["$key"]);
95
96
	foreach ( $values as $value ) {
97
		if ( $value == 'count' ) continue;
98
                $nlearn = $vet["$key"]["$value"]['count'];
99
                unset($vet["$key"]["$value"]['count']);
100
		$quantity = $cf["listing$key"]['quantity']["$category"]; /* In searchAndList this value is
101
										passed by reference and modified */
102
		$nuid = count($vet["$key"]["$value"]);
103
		if ( !$cf["listing$key"]['onlyReport']["$category"] ) {
104
			if ( ($nlearn >= $cf["listing$key"]['threshold']["$category"])&&($nuid >= $cf["listing$key"]['thresholduid']["$category"]) ) {
105
				$reason = sprintf(
106
				'The %s <%s> has been listed because was marked %u times as %s by %u different accounts during last %u days.',
107
				strtoupper($key),$value,$nlearn,$category,$nuid,$cf['imap']['oldestday']);
108
				$listed = searchAndList ($myconn,$cf['syslog']['user'],$tables,$cf["listing$key"]['list']["$category"],$value,$cf["listing$key"]['unit']["$category"],$quantity,$reason);
109
			}
110
			else $listed = FALSE;
111
		}
112
		else $listed = FALSE;
113
		$nowlist = array( TRUE =>  array(
114
					'style' => 'id=\'ipfound\'',
115
					'name'  => 'YES',
116
				  ),
117
				  FALSE => array(
118
					'style' => 'id=\'\'',
119
					'name' => 'No',
120
				  ),
121
				  NULL  => array(
122
					'style' => 'id=\'\'',
123
					'name' => 'No',
124
				  )
125
		);
126
		
127
		$return .='<tr><td rowspan="'.$nuid.'">'.$value.'</td>';
128
		$return .= sprintf ('<td>%s</td><td rowspan="'.$nuid.'">%u</td><td rowspan="'.$nuid.'" '.$nowlist["$listed"]['style'].'>%s</td></tr>',$vet["$key"]["$value"][0],$nlearn,$nowlist["$listed"]['name']);
129
		$rowuid=NULL;
130
                for ($j=1;$j<$nuid;$j++) $rowuid .= '<tr><td>%s</td></tr>';
131
		array_shift($vet["$key"]["$value"]);
132
                $return .= vsprintf ($rowuid,$vet["$key"]["$value"]);
133
134
	}
135
	$return .= sprintf ('<tr><th title="unique %s">%u</th><th title="unique uids">%u</th><th>%u</th></table>',$key,$vet["$key"]['count'],$vet['uid']['count'],$nk);
136
137
138
	/* Statistics by UID */
139
	/* Not used for listing purpose, but useful to you! */
140
	$return .= sprintf('<h3>Statistics by UID</h3><table><tr><th>UID</th><th>%s learned</th><th>Learned times</th></tr>'."\n",$key);
141
	$uids = array_keys($vet['uid']);
142
        foreach ( $uids as $uid ) {
143
		if ( $uid == 'count' ) continue;	
144
	        $nlearn = $vet['uid']["$uid"]['count'];
145
	        unset ( $vet['uid']["$uid"]['count'] );
146
		$nip = count($vet['uid']["$uid"]);
147
		$return .='<tr><td rowspan="'.$nip.'">'.$uid.'</td>';
148
		$return .= sprintf ('<td>%s</td><td rowspan="'.$nip.'">%u</td></tr>',$vet['uid']["$uid"][0],$nlearn);
149
                $rowuid=NULL;
150
                for ($j=1;$j<$nip;$j++) $rowuid .= '<tr><td>%s</td></tr>';
151
                array_shift($vet['uid']["$uid"]);
152
                $return .= vsprintf ($rowuid,$vet['uid']["$uid"]);
153
154
        }
155
        $return .= sprintf ('<tr><th title="unique uids">%u</th><th title="unique %s">%u</th><th>%u</th></table>',
156
			$vet['uid']['count'],$key,$vet["$key"]['count'],$nk);
157
158
159
	return $return;
160
}
161
162
163
function splunksearch ($service,$message_id,$date) {
164
165
	// Run a blocking search
166
	$searchQueryBlocking = 'search (message_id="'. addslashes( $message_id ) .
167
				'" OR sasl_username) | transaction message_id queue_id maxspan=3m maxpause=2m | search sasl_username message_id=* | table sasl_username';
168
169
	/* Doesn't work on Splunk 6.6 for HTTP exceptions
170
	// A blocking search returns the job when the search is done
171
	$job = $service->getJobs()->create($searchQueryBlocking, array(
172
	    'exec_mode' => 'blocking',
173
	    'earliest_time' => date("c",strtotime ($date)-120),
174
	    'latest_time' => date("c",strtotime ($date)+60)
175
	));
176
177
	if ($job['resultCount'] == 0) return FALSE;
178
179
	// Get job results
180
	$resultSearch = $job->getResults();
181
	*/
182
183
	// A one shot search
184
        $searchParams = array(
185
                'earliest_time' => date("c",strtotime ($date)-120),
186
                'latest_time' => date("c",strtotime ($date)+60)
187
        );
188
189
        // Run a oneshot search that returns the job's results
190
        $resultsStream = $service->oneshotSearch($searchQueryBlocking, $searchParams);
191
        $resultSearch = new Splunk_ResultsReader($resultsStream);
192
193
	// Use the built-in XML parser to display the job results
194
	foreach ($resultSearch as $result)
195
	  {
196
	    if ($result instanceof Splunk_ResultsFieldOrder)
0 ignored issues
show
Bug introduced by
The class Splunk_ResultsFieldOrder does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
197
	    {
198
	      // More than one field attribute returned by search
199
	      // You must redefine the search
200
	      if ( count($result->getFieldNames()) > 1 ) return FALSE;
201
	    }
202
	    else if ($result instanceof Splunk_ResultsMessage)
0 ignored issues
show
Bug introduced by
The class Splunk_ResultsMessage does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
203
	    {
204
	      // I don't want messages in my search
205
	      return FALSE;
206
	    }
207
	    else if (is_array($result))
208
	    {
209
	      // Process a row
210
	      foreach ($result as $key => $valueOrValues)
211
	        {
212
	         if (is_array($valueOrValues))
213
	          {
214
	            return FALSE;
215
	          }
216
	         else
217
	          {
218
	            return $valueOrValues;
219
	            #print "  {$key} => {$value}\r\n";
220
	          }
221
	        }
222
	    }
223
	    else
224
	    {
225
	      #print "Unknow result type";
226
	      return FALSE;
227
	    }
228
	  }
229
}
230
231
/*
232
        Function to read body taken from
233
        https://www.electrictoolbox.com/php-imap-message-body-attachments/
234
*/
235
236
function flattenParts($messageParts, $flattenedParts = array(), $prefix = '', $index = 1, $fullPrefix = true) {
237
238
        foreach($messageParts as $part) {
239
                $flattenedParts[$prefix.$index] = $part;
240
                if(isset($part->parts)) {
241
                        if($part->type == 2) {
242
                                $flattenedParts = flattenParts($part->parts, $flattenedParts, $prefix.$index.'.', 0, false);
243
                        }
244
                        elseif($fullPrefix) {
245
                                $flattenedParts = flattenParts($part->parts, $flattenedParts, $prefix.$index.'.');
246
                        }
247
                        else {
248
                                $flattenedParts = flattenParts($part->parts, $flattenedParts, $prefix);
249
                        }
250
                        unset($flattenedParts[$prefix.$index]->parts);
251
                }
252
                $index++;
253
        }
254
255
        return $flattenedParts;
256
257
}
258
259
function getPart($connection, $messageNumber, $partNumber, $encoding) {
260
261
        $data = imap_fetchbody($connection, $messageNumber, $partNumber);
262
        switch($encoding) {
263
                case 0: return $data; // 7BIT
0 ignored issues
show
Coding Style introduced by
The case body in a switch statement must start on the line following the statement.

According to the PSR-2, the body of a case statement must start on the line immediately following the case statement.

switch ($expr) {
case "A":
    doSomething(); //right
    break;
case "B":

    doSomethingElse(); //wrong
    break;

}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
Coding Style introduced by
Terminating statement must be on a line by itself

As per the PSR-2 coding standard, the break (or other terminating) statement must be on a line of its own.

switch ($expr) {
     case "A":
         doSomething();
         break; //wrong
     case "B":
         doSomething();
         break; //right
     case "C:":
         doSomething();
         return true; //right
 }

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
264
                case 1: return $data; // 8BIT
0 ignored issues
show
Coding Style introduced by
The case body in a switch statement must start on the line following the statement.

According to the PSR-2, the body of a case statement must start on the line immediately following the case statement.

switch ($expr) {
case "A":
    doSomething(); //right
    break;
case "B":

    doSomethingElse(); //wrong
    break;

}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
Coding Style introduced by
Terminating statement must be on a line by itself

As per the PSR-2 coding standard, the break (or other terminating) statement must be on a line of its own.

switch ($expr) {
     case "A":
         doSomething();
         break; //wrong
     case "B":
         doSomething();
         break; //right
     case "C:":
         doSomething();
         return true; //right
 }

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
265
                case 2: return $data; // BINARY
0 ignored issues
show
Coding Style introduced by
The case body in a switch statement must start on the line following the statement.

According to the PSR-2, the body of a case statement must start on the line immediately following the case statement.

switch ($expr) {
case "A":
    doSomething(); //right
    break;
case "B":

    doSomethingElse(); //wrong
    break;

}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
Coding Style introduced by
Terminating statement must be on a line by itself

As per the PSR-2 coding standard, the break (or other terminating) statement must be on a line of its own.

switch ($expr) {
     case "A":
         doSomething();
         break; //wrong
     case "B":
         doSomething();
         break; //right
     case "C:":
         doSomething();
         return true; //right
 }

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
266
                case 3: return base64_decode($data); // BASE64
0 ignored issues
show
Coding Style introduced by
The case body in a switch statement must start on the line following the statement.

According to the PSR-2, the body of a case statement must start on the line immediately following the case statement.

switch ($expr) {
case "A":
    doSomething(); //right
    break;
case "B":

    doSomethingElse(); //wrong
    break;

}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
Coding Style introduced by
Terminating statement must be on a line by itself

As per the PSR-2 coding standard, the break (or other terminating) statement must be on a line of its own.

switch ($expr) {
     case "A":
         doSomething();
         break; //wrong
     case "B":
         doSomething();
         break; //right
     case "C:":
         doSomething();
         return true; //right
 }

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
267
                case 4: return quoted_printable_decode($data); // QUOTED_PRINTABLE
0 ignored issues
show
Coding Style introduced by
The case body in a switch statement must start on the line following the statement.

According to the PSR-2, the body of a case statement must start on the line immediately following the case statement.

switch ($expr) {
case "A":
    doSomething(); //right
    break;
case "B":

    doSomethingElse(); //wrong
    break;

}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
Coding Style introduced by
Terminating statement must be on a line by itself

As per the PSR-2 coding standard, the break (or other terminating) statement must be on a line of its own.

switch ($expr) {
     case "A":
         doSomething();
         break; //wrong
     case "B":
         doSomething();
         break; //right
     case "C:":
         doSomething();
         return true; //right
 }

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
268
                case 5: return $data; // OTHER
0 ignored issues
show
Coding Style introduced by
The case body in a switch statement must start on the line following the statement.

According to the PSR-2, the body of a case statement must start on the line immediately following the case statement.

switch ($expr) {
case "A":
    doSomething(); //right
    break;
case "B":

    doSomethingElse(); //wrong
    break;

}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
Coding Style introduced by
Terminating statement must be on a line by itself

As per the PSR-2 coding standard, the break (or other terminating) statement must be on a line of its own.

switch ($expr) {
     case "A":
         doSomething();
         break; //wrong
     case "B":
         doSomething();
         break; //right
     case "C:":
         doSomething();
         return true; //right
 }

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
269
        }
270
271
272
}
273
/***********************************/
274
275
function getDomains ($text) {
276
	$pattern = '~[a-z]+://\S+~';
277
	$ret = array();
278
	$num_found = preg_match_all($pattern, $text, $out);
279
	if ( ($num_found !== FALSE) && ($num_found>0) ) {
280
		foreach ($out[0] as $url)
281
			$ret[] = parse_url($url, PHP_URL_HOST);
282
	}
283
	return array_values(array_unique($ret));
284
}
285
286
function parseURL ($connection,$messageNumber) {
287
	$message = '';
288
	$structure = imap_fetchstructure($connection, $messageNumber);
289
	if (isset($structure->parts)) {
290
		$flattenedParts = flattenParts($structure->parts);
291
		foreach($flattenedParts as $partNumber => $part) {
292
293
			switch($part->type) {
294
		
295
				case 0:
296
					// the HTML or plain text part of the email
297
					$message .= getPart($connection, $messageNumber, $partNumber, $part->encoding);
298
				break;
299
		
300
				case 1:
301
					// multi-part headers, can ignore
302
		
303
				break;
304
				case 2:
305
					// attached message headers, can ignore
306
				break;
307
			
308
				case 3: // application
309
				case 4: // audio
310
				case 5: // image
311
				case 6: // video
312
				case 7: // other
313
				break;
314
	
315
			}
316
	
317
		}
318
	}
319
	else
320
		$message = getPart($connection, $messageNumber, 1, $structure->encoding);
321
322
	if ( !empty($message) )
323
		return getDomains($message);
324
	return array();
325
}
326
327
function humanKey($key) {
328
	switch($key) {
329
		case 'ip':
330
			return 'ips';
331
		case 'dom':
332
			return 'domains';
333
	}
334
	return $key;
335
}
336
337
function writeFileHeader($f,$conf,$key,$type,$rtime) {
338
        fwrite( $f, file_get_contents(dirname(__FILE__) . '/' . $conf['report']['reportTemplateHeader']) );
339
        fwrite( $f,sprintf('<h1> Report of %s %s</h1><h5>%s</h5><h2>Detailed Report</h2>',$type, strtoupper(humanKey($key)),$rtime) );
340
        if ($conf["listing$key"]['onlyReport']["$type"]) {
341
                fwrite( $f,sprintf('<p>None of the below %s have been listed because listing is not active in configuration.</p>',
342
		strtoupper(humanKey($key))) );
343
		syslog(LOG_INFO, sprintf('%s: Report only for %s %s: no listing activated in configuration.',
344
			$conf['syslog']['user'],$type,humanKey($key))
345
		);
346
	}
347
        fwrite( $f,sprintf('<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>%s</th><th title="How many times this uid learns">#UID</th><th title="Number of times this learned %s appears in different mails">#%s</th><th nowrap>Received by</th><th>Message-Id</th></tr>',
348
	strtoupper($key),strtoupper($key),strtoupper($key)) );
349
}
350
351
352
function imapReport ($cf,$myconnArray,$splunkconn,$tables,$type) {
353
	$file = dirname(__FILE__) . '/' . $cf['report']['reportFile']["$type"];
354
	$filed = dirname(__FILE__) . '/' . $cf['report']['reportDomFile']["$type"];
355
	$fileb= dirname(__FILE__) . '/' . $cf['report']['badreportFile']["$type"];
356
	$m_mail = imap_open('{'.$cf['imap']['mailhost'].':143/imap/novalidate-cert/authuser='.$cf['imap']['authuser'].'}'.$cf['imap']['folder']["$type"], $cf['imap']['account'],$cf['imap']['authpassword'], OP_READONLY)
357
        	or syslog (LOG_EMERG, $cf['syslog']['user'].': Error in IMAP connection to <'.$cf['imap']['mailhost'].'>: ' . imap_last_error());
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as or instead of || is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
358
	if ( !$m_mail ) exit(254);
359
		
360
361
	syslog (LOG_INFO,$cf['syslog']['user'].': Successfully connected to <'.$cf['imap']['mailhost'].">; Reading $type messages of last ".$cf['imap']['oldestday'].' days...');
362
	//get all messages
363
	$dateTh = date ( "d-M-Y", strToTime ( '-'.$cf['imap']['oldestday'].' days' ) );
364
        $dateN  = date ( "d-M-Y", strToTime ( "now" ) );
365
        $m_search=imap_search ($m_mail, "SINCE \"$dateTh\" BEFORE \"$dateN\"" );
366
367
	// Order results starting from newest message
368
	if ( empty($m_search) ) {
369
		syslog (LOG_INFO,$cf['syslog']['user'].": No mail found in $type folder. No reports written for $type.");
370 View Code Duplication
	        if ( $ierr = imap_errors() )
371
	                foreach ( $ierr as $thiserr )
372
	                        syslog (LOG_ERR, $cf['syslog']['user'].": IMAP Error: $thiserr");
373 View Code Duplication
	        if ( $ierr = imap_alerts() )
374
	                foreach ( $ierr as $thiserr )
375
	                        syslog (LOG_ALERT, $cf['syslog']['user'].": IMAP Alert: $thiserr");
376
		imap_close( $m_mail );
377
		if ( file_exists( $file ) ) unlink ($file);
378
		if ( file_exists( $filed ) ) unlink ($filed);
379
		if ( file_exists( $fileb ) ) unlink ($fileb);
380
		return FALSE;
381
	}
382
	$nmes = count ($m_search);
383
	syslog (LOG_INFO,$cf['syslog']['user'].": Found $nmes mail in $type folder.");
384
	if ($nmes>0) rsort($m_search);
385
386
	// Create report file
387
388
	$fp = fopen($file, 'w');
389
	$fpd= fopen($filed, 'w');
390
	$fpb= fopen($fileb, 'w');
391
	$lastup = "Last Update: " . date ("d F Y H:i", time());
392
	writeFileHeader($fp,$cf,'ip',$type,$lastup);
393
	writeFileHeader($fpd,$cf,'dom',$type,$lastup);
394
395
	fwrite( $fpb,file_get_contents(dirname(__FILE__) . '/' . $cf['report']['reportTemplateHeader']) );
396
	fwrite( $fpb,"<h1> Report of bad reported $type mails</h1><h5>$lastup</h5><h2>Detailed Report</h2>" );
397
	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>' );
398
399
	$ipuid = array();
400
	$ipuid['count'] = 0;
401
	$ipuid['uid'] = array();
402
	$ipuid['ip'] = array();
403
	$ipuid['ip']['count'] = 0;
404
	$ipuid['uid']['count'] = 0;
405
	$domuid = array();
406
	$domuid['count'] = 0;
407
	$domuid['dom'] = array();
408
	$domuid['dom']['count'] = 0;
409
	$domuid['uid'] = array();
410
	$domuid['uid']['count'] = 0;
411
	$uidbad = array();
412
	$uidbad['count'] = 0;
413
	$uidbad['uid'] = array();
414
415
        // loop for each message
416
	foreach ($m_search as $onem) {
417
418
	        //get imap header info for obj thang
419
	        //$headers = imap_headerinfo($m_mail, $onem);
420
	        //$head = imap_fetchheader($m_mail, $headers->Msgno);
421
		$head = imap_fetchheader($m_mail, $onem );
422
	        //$obj = imap_rfc822_parse_headers( $head);
423
424
	        list ($ip,$host,$dateReceived,$dateClient,$mid) =  getIP( $head,$cf['mx_hostname']['mx'],$cf['msa']['msalearn'] );
425
		if (empty($mid)) {
426
			$uid='NA';
427
			syslog (LOG_ERR, $cf['syslog']['user'].": Error retrieving data for empty Message-ID.");
428
		} else {
429
			if ($dateReceived === FALSE) {
430
				$uid='unauthenticated';
431
				syslog (LOG_ERR, $cf['syslog']['user'].": Error retrieving date for $mid. Maybe this mail was not submitted to Learner MSA");
432
			} else  
433
				if ( !($uid = splunksearch ($splunkconn, trim($mid,'<>'), $dateReceived)) ) {
434
					syslog (LOG_ERR, $cf['syslog']['user'].": Error retrieving uid from Splunk log for $mid.");
435
					$uid='unknown';
436
				}
437
		}
438
439
		/* Extract domains url in body */
440
		$domains = parseURL ($m_mail,$onem);
441
442
	        /* Update count of each ip */
443
	        if ($host and ($uid!='NA') and ($uid!='unauthenticated') and ($uid!='unknown')) { /* IP is received by MX servers  and learned by valid uid */
444
			$ipuid['count']++;					//number of right messages
445
446 View Code Duplication
	                if (in_array($uid,array_keys($ipuid['uid']))) {
447
				$ipuid['uid']["$uid"]['count']++;		//number of learn by this uid
448
				if (!in_array($ip,$ipuid['uid']["$uid"])) 
449
					$ipuid['uid']["$uid"][]=$ip;		//ips learned by this uid
450
			}
451
			else {
452
				$ipuid['uid']["$uid"]['count'] = 1;
453
				$ipuid['uid']["$uid"][]=$ip;
454
				$ipuid['uid']['count']++;                	//number of unique uids
455
			}
456
457 View Code Duplication
                        if (in_array($ip,array_keys($ipuid['ip']))) {
458
                                $ipuid['ip']["$ip"]['count']++;			//number of time this ip appears in different messages
459
				if (!in_array($uid,$ipuid['ip']["$ip"]))
460
					$ipuid['ip']["$ip"][]=$uid;		//uids that learned this ip
461
			}
462
                        else {
463
                                $ipuid['ip']["$ip"]['count'] = 1;
464
				$ipuid['ip']["$ip"][]=$uid;
465
				$ipuid['ip']['count']++;			//number of unique ips
466
                        }
467
468
			foreach ($domains as $dom) {
469
				$domuid['count']++;
470 View Code Duplication
				if (in_array($uid,array_keys($domuid['uid']))) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
471
					$domuid['uid']["$uid"]['count']++;               //number of learn by this uid
472
					if (!in_array($dom,$domuid['uid']["$uid"]))
473
						$domuid['uid']["$uid"][]=$dom;		//domains learned by this uid
474
				}
475
				else {
476
					$domuid['uid']["$uid"]['count'] = 1;
477
					$domuid['uid']["$uid"][]=$dom;
478
					$domuid['uid']['count']++;			//number of unique uids
479
				}
480
481 View Code Duplication
				if (in_array($dom,array_keys($domuid['dom']))) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
482
					$domuid['dom']["$dom"]['count']++;	//number of learn with this domain
483
					if (!in_array($uid,$domuid['dom']["$dom"]))
484
						$domuid['dom']["$dom"][]=$uid;	//uids that learned this domain
485
				}
486
				else {
487
					$domuid['dom']["$dom"]['count'] = 1;
488
					$domuid['dom']["$dom"][]=$uid;
489
					$domuid['dom']['count']++;		//number of unique domains
490
				}
491
492
				fwrite($fpd,
493
					updateReport (
494
						$dom,$uid,$domuid['dom']["$dom"]['count'],
495
						$domuid['uid']["$uid"]['count'],$host,
496
						$dateClient,$mid,$dateReceived
497
					)
498
				);
499
			}
500
501
	        	/* Update HTML report */
502
	        	fwrite($fp,updateReport ( $ip,$uid,$ipuid['ip']["$ip"]['count'],$ipuid['uid']["$uid"]['count'],$host,$dateClient,$mid,$dateReceived) );
503
		}
504
	        else {	/* Bad learn */
505
			
506
                        if (in_array($uid,array_keys($uidbad['uid']))) 
507
                                $uidbad['uid']["$uid"]['count']++;               //number of bad learn by this uid
508
                        else {
509
                                $uidbad['uid']["$uid"]['count'] = 1;
510
				$uidbad['uid']["$uid"][]=$uid;
511
                                $uidbad['count']++;                       //numeber of unique bad uids
512
                        }
513
			/* The reason of bad report */
514
			if ($host === FALSE) $reason = 'This mail was not received by recognized MX host';
515
			if ($dateReceived === FALSE) $reason = 'This mail was not submitted to recognized MSA for learn';
516
			if ($uid=='unknown') $reason = 'The uid of this mail was not found in splunk log';
517
			if (!isset($reason)) $reason = '?';
518
				
519
			fwrite( $fpb,updatebadReport ( $uid,$dateClient,$mid,$dateReceived,$reason ) );
520
		}
521
	}
522
523
524
	//close report file and mailbox
525
526
	/* Summary Report */
527
	$ipuid['ip'] = array_msort( $ipuid['ip'], array('count'=>SORT_DESC) );
528
	$ipuid['uid'] = array_msort( $ipuid['uid'], array('count'=>SORT_DESC) );
529
	$domuid['dom'] = array_msort( $domuid['dom'], array('count'=>SORT_DESC) );
530
	$domuid['uid'] = array_msort( $domuid['uid'], array('count'=>SORT_DESC) );
531
	$uidbad['uid'] = array_msort( $uidbad['uid'], array('count'=>SORT_DESC) );
532
	
533
	fwrite($fp, '</table>');
534
	fwrite($fpd, '</table>');
535
	fwrite($fp, '<hr><h2>Summary Report</h2><h5>Listing policy: ip must be learned at least '.$cf['listingip']['threshold']["$type"].' times from at least '.$cf['listingip']['thresholduid']["$type"].' different valid uids.</h5>' );
536
	fwrite($fpd, '<hr><h2>Summary Report</h2><h5>Listing policy: domains must be learned at least '.$cf['listingdom']['threshold']["$type"].' times from at least '.$cf['listingdom']['thresholduid']["$type"].' different valid uids.</h5>' );
537
538
        /* Make MYSQL connection */
539
	if ( $cf['listingip']['onlyReport']["$type"] && $cf['listingdom']['onlyReport']["$type"] )
540
		$mysqli = NULL;
541
	else {
542
        	$mysqli = new mysqli($myconnArray['dbhost'], $myconnArray['userdb'], $myconnArray['pwd'], $myconnArray['db'], $myconnArray['dbport']);
543
        	if ($mysqli->connect_error) {
544
                	syslog (LOG_EMERG, $cf['syslog']['user'].': Connect Error (' . $mysqli->connect_errno . ') '
545
                	. $mysqli->connect_error);
546
                	exit (254);
547
        	}
548
        	syslog(LOG_INFO, $cf['syslog']['user'].': Successfully mysql connected to ' . $mysqli->host_info) ;
549
	}
550
	/***********************/
551
552
	fwrite($fp, summaryReportAndList ($cf,$mysqli,$tables,$type,$ipuid, 'ip') );
553
	fwrite($fp,file_get_contents(dirname(__FILE__) . '/' . $cf['report']['reportTemplateFooter']));
554
	fclose($fp);
555
556
	fwrite($fpd, summaryReportAndList ($cf,$mysqli,$tables,$type,$domuid, 'dom') );
557
	fwrite($fpd,file_get_contents(dirname(__FILE__) . '/' . $cf['report']['reportTemplateFooter']));
558
	fclose($fpd);
559
	
560
	if ( !($cf['listingip']['onlyReport']["$type"] && $cf['listingdom']['onlyReport']["$type"]) )
561
		$mysqli->close();
562
563
	fwrite($fpb, '</table>');
564
	fwrite( $fpb,summaryBadReport( $uidbad ) );
565
	fwrite($fpb,file_get_contents(dirname(__FILE__) . '/' . $cf['report']['reportTemplateFooter']));
566
	fclose($fpb);
567
	syslog (LOG_INFO,$cf['syslog']['user'].': Report files written. Listing job for '.$type.' terminated.');
568
569 View Code Duplication
	if ( $ierr = imap_errors() )
570
		foreach ( $ierr as $thiserr )
571
			syslog (LOG_ERR, $cf['syslog']['user'].": IMAP Error: $thiserr");
572 View Code Duplication
	if ( $ierr = imap_alerts() )
573
                foreach ( $ierr as $thiserr )
574
                        syslog (LOG_ALERT, $cf['syslog']['user'].": IMAP Alert: $thiserr");
575
	imap_close($m_mail);
576
}
577
?>
578