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 ( 7c40ab...39df4e )
by Marco
02:30
created

function.php ➔ checkSSL()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 9
nc 2
nop 0
dl 0
loc 10
rs 9.4285
c 0
b 0
f 0
1
<?php
0 ignored issues
show
Coding Style Compatibility introduced by
For compatibility and reusability of your code, PSR1 recommends that a file should introduce either new symbols (like classes, functions, etc.) or have side-effects (like outputting something, or including other files), but not both at the same time. The first symbol is defined on line 5 and the first side effect is on line 3.

The PSR-1: Basic Coding Standard recommends that a file should either introduce new symbols, that is classes, functions, constants or similar, or have side effects. Side effects are anything that executes logic, like for example printing output, changing ini settings or writing to a file.

The idea behind this recommendation is that merely auto-loading a class should not change the state of an application. It also promotes a cleaner style of programming and makes your code less prone to errors, because the logic is not spread out all over the place.

To learn more about the PSR-1, please see the PHP-FIG site on the PSR-1.

Loading history...
2
3
ini_set('error_log', 'syslog');
4
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';
9
	return $user;
10
}
11
12
function checkSSL() {
0 ignored issues
show
Coding Style introduced by
checkSSL uses the super-global variable $_SERVER which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
13
	if ( empty( $_SERVER['HTTPS'] ) )
14
		printf ('<div id="content">Ehi sysadmin! Your site is not secure. Please enable SSL on your server and configure a redirect, such as' .
15
			'<pre>' .
16
			htmlspecialchars('<VirtualHost *:80>' . "\n" .
17
			'  ServerName %s' . "\n" .
18
			'  Redirect permanent / https://%s/' . "\n" .
19
			'</VirtualHost>') .
20
			'</pre></div>', gethostname(), gethostname());
21
}
22
23
function myConnect($host, $user, $pass, $db, $port, $tablelist, $typedesc, $loguser) {
24
        $db = ( $tablelist["$typedesc"]['milter'] ) ? $tablelist["$typedesc"]['name'] : $db;
25
	$mysqli = new mysqli($host, $user, $pass, $db, $port);
26
        if ($mysqli->connect_error) {
27
           	syslog (LOG_EMERG, $loguser.': Connect Error to DB <'.$db.'> (' . $mysqli->connect_errno . ') '
28
                    		. $mysqli->connect_error);
29
		return FALSE;
30
	}
31
	syslog(LOG_INFO, $loguser.': Successfully MySQL connected at DB <'.$db.'> to ' . $mysqli->host_info) ;
32
	return $mysqli;
33
}
34
35
function addtolist ($myconn,$user,$value,$tabledesc,$expUnit,$expQ,$myreason,&$err) {
36
// See MySQL manual for $expQ and $expUnit at
37
// https://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_timestampadd
38
39
	$result=FALSE;
40
	$sub=array();
41
	$type = $tabledesc['field'];
42
	$milt = $tabledesc['milter'];
43
	$table = ($milt) ? milterTable($type) : $tabledesc['name'];
44
45
	switch ($type) {
46
	  case 'ip':
47
		$query= sprintf("INSERT INTO `$table` (
48
			`$type` ,
49
			`date` ,
50
			`exp` ,
51
			`active` ,
52
			`user` ,
53
			`reason`
54
		)
55
		VALUES (
56
			INET_ATON( '%s' ) ,
57
			CURRENT_TIMESTAMP , TIMESTAMPADD(%s,%d,CURRENT_TIMESTAMP), '1', '%s', '%s'
58
		)" ,$value,$expUnit,$expQ,$user,$myreason);
59
		break;
60
61
	  case 'network':
62
		if (!$milt) {
63
			if ( netOverlap($myconn, $tabledesc, $value, $overlappedNet, $user) ) {
64
				$err = "<$value> overlaps the existing network <$overlappedNet>";
65
				return FALSE;
66
			}
67
		}
68
		list($sub['net'],$sub['mask'])=explode('/',$value);
69
                $query= sprintf("INSERT INTO `$table` (
70
                        `$type` ,
71
			`netmask`,
72
                        `date` ,
73
                        `exp` ,
74
                        `active` ,
75
                        `user` ,
76
                        `reason`
77
                )
78
                VALUES (
79
                        INET_ATON( '%s' ) , INET_ATON( '%s' ) ,
80
                        CURRENT_TIMESTAMP , TIMESTAMPADD(%s,%d,CURRENT_TIMESTAMP), '1', '%s', '%s'
81
                )" ,$sub['net'],$sub['mask'],$expUnit,$expQ,$user,$myreason);
82
                break;
83
84
	  default:
85
                $query= sprintf("INSERT INTO `$table` (
86
                        `$type` ,
87
                        `date` ,
88
                        `exp` ,
89
                        `active` ,
90
                        `user` ,
91
                        `reason`
92
                )
93
                VALUES (
94
                        '%s' ,
95
                        CURRENT_TIMESTAMP , TIMESTAMPADD(%s,%d,CURRENT_TIMESTAMP), '1', '%s', '%s'
96
                )" ,$value,$expUnit,$expQ,$user,$myreason);
97
	}
98
99
	if ($myconn->query($query) === TRUE) {
100
	    syslog(LOG_INFO, "$user: $type <$value> successfully listed on <$table> for $expQ $expUnit.");
101
	    $result=TRUE;
102
	}
103
	else syslog(LOG_ERR, "$user: Error: ".$myconn->error);
104
	return $result;
105
}
106
107
function relist ($myconn,$user,$value,$type,$table,$expUnit,$expQ,$myreason, $exptime = 0) {
108
109
	$result=FALSE;
110
	if ( $exptime ) { /* Entry already listed */
111
		$nlist = '`nlist`';
112
		$exptime = sprintf('\'%s\'', $exptime);  /* Eh MySQL... an hour lost to notice this */
113
	}
114
	else {
115
		$exptime = 'CURRENT_TIMESTAMP';
116
		$nlist = '`nlist` + 1';
117
	}
118
119
        switch ($type) {
120 View Code Duplication
	  case 'ip':
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...
121
                $query= sprintf("UPDATE `$table` SET
122
			`active` = '1',
123
			`user` = '%s',
124
			`exp` = TIMESTAMPADD(%s,%d,%s),
125
			`nlist` = %s,
126
			`reason` = '%s'
127
			WHERE `$table`.`$type` = INET_ATON('%s') LIMIT 1" ,$user,$expUnit,$expQ,$exptime,$nlist,$myreason,$value);
128
		break;
129
          case 'network':
130
		list($sub['net'],$sub['mask'])=explode('/',$value);
131
                $query= sprintf("UPDATE `$table` SET
132
                        `active` = '1',
133
                        `user` = '%s',
134
                        `exp` = TIMESTAMPADD(%s,%d,%s),
135
                        `nlist` = %s,
136
                        `reason` = '%s'
137
                        WHERE (`$table`.`$type` = INET_ATON('%s') AND `$table`.`netmask` = INET_ATON('%s')) LIMIT 1" ,$user,$expUnit,$expQ,$exptime,$nlist,$myreason,$sub['net'],$sub['mask']);
0 ignored issues
show
Bug introduced by
The variable $sub does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
138
		break;
139 View Code Duplication
	  default:
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...
140
                $query= sprintf("UPDATE `$table` SET
141
                        `active` = '1',
142
                        `user` = '%s',
143
                        `exp` = TIMESTAMPADD(%s,%d,%s),
144
                        `nlist` = %s,
145
                        `reason` = '%s'
146
			WHERE `$table`.`$type` = '%s' LIMIT 1" ,$user,$expUnit,$expQ,$exptime,$nlist,$myreason,$value);
147
	}
148
149
        if ($myconn->query($query) === TRUE) {
150
            syslog(LOG_INFO, "$user: relist $type <$value> on <$table> for $expQ $expUnit from $exptime.");
151
		$result=TRUE;
152
        }
153
        else syslog (LOG_ERR, "$user: Error: ". $myconn->error);
154
	return $result;
155
}
156
157
function remove ($myconn,$user,$value,$type,$table) {
158
159
        switch ($type) {
160
          case 'ip':
161
		$query = sprintf("DELETE FROM `$table` WHERE
162
                        `$table`.`$type` = INET_ATON('%s') LIMIT 1", $value);
163
		break;
164 View Code Duplication
	  case 'network':
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...
165
		list($sub['net'],$sub['mask'])=explode('/',$value);
166
		$query = sprintf("DELETE FROM `$table` WHERE
167
			`$table`.`$type` = INET_ATON('%s') AND `$table`.`netmask` = INET_ATON('%s') LIMIT 1",
168
			$sub['net'],$sub['mask']);
0 ignored issues
show
Bug introduced by
The variable $sub does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
169
		break;
170
	  default:
171
		$query = sprintf("DELETE FROM `$table` WHERE
172
                        `$table`.`$type` = %s LIMIT 1", $value);
173
	}
174
175
176
        if ($return=$myconn->query($query) === TRUE) 
177
            syslog(LOG_INFO, "$user: permanently DELETED $type <$value> from <$table>.");
178
        else syslog(LOG_ERR, "$user: Error: ". $myconn->error);
179
180
        return $return;
181
}
182
183
184
function changestatus ($myconn,$user,$value,$status,$type,$table) {
185
186
	switch ($type) {
187
          case 'ip':
188
		$query= sprintf("UPDATE `$table` SET `active` = '$status', `user` = '%s' WHERE `$table`.`$type` = INET_ATON('%s') LIMIT 1" ,$user, $value);
189
		break;
190
	  case 'network':
191
		list($sub['net'],$sub['mask'])=explode('/',$value);
192
		$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']);
0 ignored issues
show
Bug introduced by
The variable $sub does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
193
		break;
194
	  default:
195
		$query= sprintf("UPDATE `$table` SET `active` = '$status', `user` = '%s' WHERE `$table`.`$type` = '%s' LIMIT 1" ,$user, $value);
196
	}
197
198
        if ($return=$myconn->query($query) === TRUE) {
199
            syslog(LOG_INFO, "$user: change status of $type <$value>. The status is now <$status>");
200
        }
201
        else syslog(LOG_ERR, "$user: Error: ". $myconn->error);
202
	return $return;	
203
}
204
205
206
function expire ($myconn,$user,$tables,$expireTime) {
207
        $return=TRUE;
208
	$log=array();
209
	$desc = array_keys($tables);
210
	foreach ($desc as $tdesc) { 
211
		/* QUERY */
212
		$query  = 'DELETE FROM `'.$tables["$tdesc"]['name']."` WHERE `exp` < DATE_SUB( NOW(), INTERVAL $expireTime YEAR);";
213
		$query .= 'DELETE FROM `'.$tables["$tdesc"]['name']."` WHERE `datemod` < DATE_SUB( NOW(), INTERVAL $expireTime YEAR) AND `active` = 0";
214
		/* END OF QUERY */
215
		$log[0] = 'expired for';
216
		$log[1] = 'disabled for';
217
        	if ($myconn->multi_query($query)) {
218
			$j = 0;
219
			do {
220
		    		$numdel = $myconn->affected_rows;
221
	            		syslog(LOG_INFO, "Expire job - <$user> Permanently DELETED $numdel records ".$log[$j]." $expireTime YEARS from <".$tables["$tdesc"]['name'].'>.');
222
				$j++;
223
224
			} while ($myconn->next_result());
225
		}
226
		else {
227
			syslog(LOG_ERR, "Expire job - Error: ". $myconn->error);
228
			$return = FALSE;
229
		}
230
	}
231
	if ( !($return) ) syslog(LOG_EMERG, 'End of Expire job with error. See above logs. SQL Connection terminated');
232
	else  syslog(LOG_INFO, 'Successfully End of Expire job. SQL Connection successfully terminated.');
233
        return $return;
234
}
235
236
237
function isListed($row) {
238
239
	$exp=new DateTime($row['exp']);
240
	$now=new DateTime('NOW');
241
	if (($exp > $now) and ($row['active'])) return true;
242
	else return false;
243
244
}
245
246
247
function askMilter($myconn,$id,$obj,$typedesc,$miltId,$value,$user,$adm)  {
248
	$milts = readMiltName($myconn,$user);
249
	$size = count($milts);
250
	if (in_array($user,array_keys($adm))) {
251
		$button = <<<END
252
		<form style="margin:0; display:inline;" name="Milter$id" enctype="text/plain" method="post" target="_self" action="changeMilter.php" onSubmit="xmlhttpPost('changeMilter.php', 'Milter$id', 'id$id', '<img src=\'/include/pleasewait.gif\'>'); return false;" />
253
		<input name="object" type="hidden" value="$obj" /><input name="oldvalues" type="hidden" value="$value" />
254
		<input name="type" type="hidden" value="$typedesc" />
255
		<input name="user" type="hidden" value="$user" />
256
		<input name="miltId" type="hidden" value="$miltId" />
257
		<div class="noscroll">
258
		<select class="input_text" name="newvalues[]" multiple size="$size">
259
END;
260
		$activeMilts = explode(',',$value);
261
		foreach ( $milts as $milter ) {
0 ignored issues
show
Bug introduced by
The expression $milts of type false|array is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
262
			if ( in_array($milter, $activeMilts) )
263
				$selected= 'selected';
264
			else
265
				$selected= NULL;
266
			$button .= sprintf('<option value="%s" %s>%s</option>', $milter, $selected, $milter);
267
		}	
268
		$button .= '</select></div><input class="button" name="Change" type="submit" value="Change" /></form>';
269
		return $button;
270
	}
271
	return $value;	
272
273
274
}
275
276
277
function ask($myconn,$id,$what,$alltables,$typedesc,$value,$lock,$user,$adm) {
278
279
	$whynot=NULL;
280
	switch ($what) {
281
		case 'Ok':
282
			if ($lock) return NULL;
283
			if (in_array($user,array_keys($adm)))
284
				if ( consistentListing($myconn,$alltables,$typedesc,$value,$whynot) ) return require('relistButton.php');
285
			return htmlspecialchars($whynot);
286
		case 'Listed':
287
		case 'WhiteListed':
288
			return require('delistButton.php');
289
	}
290
}
291
292
293
function consistentListing($myconn,$alltables,$typed,$value,&$warn) {
294
/* Check if there are no pending mislisting */
295
	$warn = NULL;
296
	if (! isset($alltables["$typed"]['depend']) ) return TRUE;
297
	foreach ($alltables["$typed"]['depend'] as $listdep) {
298
		if ($alltables["$typed"]['field'] != $alltables["$listdep"]['field'] ) {
299
			$warn = "Config ERROR: <$typed> and <$listdep> are of different types! I can't check consistency!";
300
			return FALSE;
301
		}
302
		$entry = searchentry($myconn,$value,$alltables["$listdep"]);
303
		if ( $entry->num_rows ) {
304
			if ( $entry->num_rows == 1 ) {
305
				$riga = $entry->fetch_array(MYSQLI_ASSOC);
306
                        	if (isListed($riga)) {
307
					$warn = "<$value> is already present in <$listdep> list!";
308
					$entry->free();
309
					return FALSE;
310
				}
311
			}
312
			if ( $entry->num_rows > 1 ) {$warn = "<$value> seems to be present more than once in <$listdep>. Contact a sysadmin NOW!";}
313
		}
314
		$entry->free();
315
	}
316
317
	return TRUE;
318
}
319
320
function searchentry ($myconn,$value,$tablelist) {
321
/* Make a MYSQL query and return result */
322
323
        $type = $tablelist['field'];
324
	
325
	if ( $tablelist['milter'] ) {
326
		$table = milterTable($type);
327
		if ($value == 'ALL')
328
			$query = sprintf('SELECT *, GROUP_CONCAT(milt.name) as miltnames FROM `%s` LEFT JOIN milt ON (%s.idmilt=milt.id) GROUP by idmilt',
329
				$table,$table);
330
		else {
331
			switch ($type) {
332 View Code Duplication
				case 'network':
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...
333
					list($sub['net'],$sub['mask'])=explode('/',$value);
334
					$query = sprintf('SELECT * FROM (
335
							SELECT *, GROUP_CONCAT(milt.name) as miltnames FROM `%s` LEFT JOIN milt ON (%s.idmilt=milt.id)
336
				 				WHERE (
337
									inet_aton(\'%s\') >= network AND
338
									( inet_aton(\'%s\') | ( inet_aton(\'%s\') ^ (power(2,32)-1) ) )
339
										<= network | ( netmask ^ (power(2,32)-1) )
340
								)
341
				 				GROUP by idmilt
342
							) AS val WHERE val.network IS NOT null', $table, $table, $sub['net'], $sub['net'], $sub['mask']);
0 ignored issues
show
Bug introduced by
The variable $sub does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
343
					break;
344
				case 'ip':
345
					$query = sprintf('SELECT * FROM (
346
							SELECT *, GROUP_CONCAT(milt.name) as miltnames FROM `%s` LEFT JOIN milt ON (%s.idmilt=milt.id)' .
347
                                                		'WHERE `ip` =  INET_ATON(\'%s\')
348
							 ) AS val WHERE val.ip IS NOT null', $table, $table, $value);
349
					break;
350
				default:
351
					syslog(LOG_EMERG, 'ALERT: The type <'.$type.'> is not allowed for milter lists.' );
352
					return FALSE;
353
			}
354
		}
355
	}
356
357
	else {
358
	        $table = $tablelist['name'];
359
	        if ($value == 'ALL') $query = 'select * from '.$table;
360
	        else {
361
	                switch ($type) {
362
	                  case 'ip':
363
	                        $query= "select * from $table where $type =  INET_ATON('$value')";
364
	                        break;
365 View Code Duplication
	                  case 'network':
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...
366
	                        list($sub['net'],$sub['mask'])=explode('/',$value);
367
	                        $query= sprintf('select * from `%s`
368
						WHERE (
369
							inet_aton(\'%s\') >= network AND
370
							( inet_aton(\'%s\') | ( inet_aton(\'%s\') ^ (power(2,32)-1) ) )
371
								<= network | ( netmask ^ (power(2,32)-1) )
372
						)', $table, $sub['net'], $sub['net'], $sub['mask']);
373
;
374
	                        break;
375
	                  default:
376
	                        $query= "select * from $table where $type = '$value'";
377
	                }
378
	        }
379
	}
380
381
	$result = $myconn->query($query);
382
	if($result === false)
383
		syslog(LOG_EMERG, "ALERT: Query <$query> failed: ".$myconn->error);
384
        return $result;
385
}
386
387
function countListed ($myconn,$table) {
388
/* Return number of current listed items into a rbl table */
389
	$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";
390
	$row = $myconn->query($query);
391
	$number = $row->fetch_array(MYSQLI_ASSOC);
392
	$number = $number['count'];
393
	$row->free();
394
	return $number;
395
}
396
397
398
function isFull($myconn,$typedesc,$alltables) {
399
        if (isset($alltables["$typedesc"]['limit'])) {
400
		if ( $alltables["$typedesc"]['milter'] )
401
			$tab = 'net';
402
		else
403
			$tab = $alltables["$typedesc"]['name'];
404
                if ( countListed($myconn,$tab) >= $alltables["$typedesc"]['limit'] ) 
405
                        return TRUE;
406
        }
407
	return FALSE;
408
}
409
410
function rlookup ($myconn,$user,$adm,$value,$typedesc,$tables) {
411
412
	$type = $tables["$typedesc"]['field'];
413
	$whynot=NULL;
414
415
	$tabhtm = <<<END
416
	<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>
417
END;
418
	if ( $tables["$typedesc"]['milter'] )
419
		$tabhtm .= '<th title="Milter active for this object">Milters</th>';
420
	$tabhtm .= '<th>Authored by</th><th width="250">Reason</th><th>Action</th></tr></thead><tfoot><tr></tr></tfoot><tbody>'."\n";
421
422
	$result = searchentry ($myconn,$value,$tables["$typedesc"]);
423
	if ($result) {
424
		printf("<pre>Your request for $type &lt;$value&gt; returned %d items.\n</pre>", $result->num_rows);
425
426
        /* Check for limit in number of listed items */
427
	$full = isFull($myconn,$typedesc,$tables);
428
	if ($full) print '<p>'.htmlspecialchars("$typedesc has reached maximum value of ".$tables["$typedesc"]['limit'].' listed items.').'</p>';
429
430
		if ($result->num_rows) {
431
			print $tabhtm;
432
			$i=0;
433
        		while ($riga = $result->fetch_array(MYSQLI_ASSOC)) {
434
				if (isListed($riga)) {
435
					if ($tables["$typedesc"]['bl']) $listed='Listed';
436
					else $listed='WhiteListed';
437
				}	
438
				else
439
					$listed='Ok';
440
441
				switch ($type) {
442
				  case 'ip':
443
					$element = long2ip($riga['ip']);
444
					break;
445 View Code Duplication
				  case 'network':
446
					$element = long2ip($riga['network']).'/'.long2ip($riga['netmask']);
447
					break;
448
				  default:
449
					$element = $riga["$type"];
450
				}
451
452
				if ( $tables["$typedesc"]['milter'] AND checkMilterConf($tables["$typedesc"]) )
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as and 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...
453
					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 nowrap id='status$listed'>%s</td><td id='status$listed'>%s</td><td id='status$listed'>%s</td><td>%s</td></tr>\n",
454
					$element, $riga['date'], $riga['datemod'], $riga['exp'], $riga['active'], $riga['nlist'], askMilter($myconn,$i,$element,$typedesc,$riga['idmilt'],$riga['miltnames'],$user,$adm), $riga['user'],htmlspecialchars($riga['reason']),ask($myconn,$i,$listed,$tables,$typedesc,$element,$full,$user,$adm));
455
				else
456
					 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",
457
					$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));
458
				$i++;
459
        		}
460
			print '</tbody></table>';
461
		}
462
		else {
463
			print "<pre>$type &lt;$value&gt; is not listed!\n</pre>";
464
			if ( in_array($user,array_keys($adm)) AND ($value != 'ALL') )
465
				if ( (!$full) AND (consistentListing($myconn,$tables,$typedesc,$value,$whynot)) ) require_once('listForm.php');
466
									else print '<p>'.htmlspecialchars($whynot).'</p>';
467
				
468
		}
469
		$result->free();
470
	}
471
	else print '<pre>Query error or something wrong in DB schema'."\n</pre>";
472
}
473
474
475
476
        
477
function sendEmailWarn($tplf,$from,$to,$sbj,$emailListed,$intervalToExpire,$detail) {
478
	$now = time();
479
        setlocale (LC_TIME, 'it_IT');
480
        $date = date("r",$now);
481
	$messageID = md5(uniqid($now,1)) . '@' . gethostname();
482
	$mua = 'PHP/' . phpversion();
483
484
	/* Parsing headers */
485 View Code Duplication
	if (!file_exists($tplf['header'])) {
486
    		syslog(LOG_ERR, 'Sending email... template file <'.$tplf['header'].'> not found!');
487
    		exit;
488
	}
489
490
	$head_tmpl = file_get_contents($tplf['header']);
491
	$arr_tpl_vars = array('{from}','{to}','{date}','{messageID}','{mua}');
492
	$arr_tpl_data = array($from,$to,$date,$messageID,$mua);
493
	$headers = str_replace($arr_tpl_vars, $arr_tpl_data, $head_tmpl);
494
	$headers = preg_replace( '/\r|\n/', "\r\n", $headers );
495
496
        /* Parsing body */
497
498 View Code Duplication
        if (!file_exists($tplf['body'])) {
499
                syslog(LOG_ERR, 'Sending email... template file <'.$tplf['body'].'> not found!');
500
                exit;
501
        }
502
503
        $body_tmpl = file_get_contents($tplf['body']);
504
        $arr_tpl_vars = array('{emailListed}','{expInterval}','{reason}');
505
        $arr_tpl_data = array($emailListed,$intervalToExpire,$detail);
506
        $body = str_replace($arr_tpl_vars, $arr_tpl_data, $body_tmpl);
507
        $body = preg_replace( "/\r|\n/", "\r\n", $body );
508
	$body = wordwrap ( $body, 75 , "\r\n" );	
509
510
	/* Send the mail! */
511
        if ( strlen(ini_get("safe_mode"))< 1) {
512
                $old_mailfrom = ini_get("sendmail_from");
513
                ini_set("sendmail_from", $from);
514
                $params = sprintf("-oi -f %s", '<>');
515 View Code Duplication
                if (!(mail($to,$sbj, $body,$headers,$params))) $flag=FALSE;
516
                else $flag=TRUE;
517
                if (isset($old_mailfrom))
518
                        ini_set("sendmail_from", $old_mailfrom);
519
        }
520 View Code Duplication
        else {
521
                if (!(mail($to,$sbj, $body,$headers))) $flag=FALSE;
522
                else $flag=TRUE;
523
        }
524
        return $flag;
525
}
526
527
function emailToNotify($notify_file,$dom) {
528
	$ini_array = parse_ini_file($notify_file);
529
	if (in_array($dom,array_keys($ini_array)))
530
		return $ini_array["$dom"];
531
	else return FALSE;
532
}
533
534
535
function searchAndList ($myconn,$loguser,$tables,$typedesc,$value,$unit,&$quantity,&$reason) {
536
537
/* Search and list value */
538
        $type = $tables["$typedesc"]['field'];
539
        $table = $tables["$typedesc"]['name'];
540
        $result = searchentry ($myconn,$value,$tables["$typedesc"]);
541
542
        /* Manage abnormal conditions */
543
        /* Value already present in db more than once. This is absurd. Panic! */
544
        if ($result->num_rows > 1) {
545
                syslog(LOG_EMERG,"$loguser: PANIC! Select for $type '$value' returned ". $result->num_rows ." items instead of one. Abnormal. Contact a sysadmin or a developer.");
546
                $result->free();
547
                return FALSE;
548
        }
549
550
        /* Value already present in db or not present: to list anyway */
551
        if ($result->num_rows >= 0) {
552
                /* First, check for limit in number of listed items */
553
                if (isFull($myconn,$typedesc,$tables)) {
554
                        syslog(LOG_EMERG,"$loguser: $typedesc has reached maximum value of ".$tables["$typedesc"]['limit'].' listed items. Abnormal exit.');
555
                        $result->free();
556
                        return FALSE;
557
                }
558
                /* Second, check if the (re)list would be consistent now */
559
                if (! consistentListing($myconn,$tables,$typedesc,$value,$whynot) ) {
560
                        syslog(LOG_ERR, $loguser.': '.$whynot);
561
                        $result->free();
562
                        return FALSE;
563
                }
564
        }
565
        /* End of abnormal conditions */
566
567
568
        /* Finally, here I can list the value! */
569
	$thisentry = $result->fetch_array(MYSQLI_ASSOC);
570
        switch ($result->num_rows) {
571
                /* Relist value if already present */
572
                case 1:
573
                        if ( isListed($thisentry) ) {
574
				/* Entry already listed */
575
				$expdate = $thisentry['exp'];
576
				$reason = sprintf('%s. Already listed. Adding 1 DAY to previous expire date.',
577
					 $reason);
578
				$quantity = 1;
579
				$unit = 'DAY';
580
                        }
581
			else {
582
                        	/* Entry delisted */
583
				$quantity *= $thisentry['nlist'];
584
				$expdate = 0; /* This forces expiration from CURRENT_TIMESTAMP */
585
			}
586
			$result->free();
587
                        return relist ($myconn,$loguser,$value,$type,$table,$unit,$quantity,$reason, $expdate);
588
589
                /* First time list value */
590
                case 0:
591
                        $result->free();
592
                        return addtolist ($myconn,$loguser,$value,$tables["$typedesc"],$unit,$quantity,$reason,$_);
593
        }
594
}
595
596
597
/*************** Functions to check if two net overlap each other ********************/
598
599
function ipRange ($range) {
600
/* List IP in range */
601
	return array_map('long2ip', range( ip2long($range[0]), ip2long($range[1]) ) );
602
}
603
604
function isIn($netA, $netB) {
605
/* TRUE if an IP of $netA is contained in netB */
606
	list($addressA,$maskA) = explode('/', $netA);
607
	list($addressB,$maskB) = explode('/', $netB);
608
	require_once 'vendor/autoload.php';
609
	$net = new \dautkom\ipv4\IPv4();
610
	$range = $net->address($addressA)->mask($maskA)->getRange();
611
	$ips = ipRange($range);
612
	foreach ( $ips as $ip )
613
		if ( $net->address($addressB)->mask($maskB)->has($ip) )
614
			return TRUE;
615
	return FALSE;
616
}
617
618
function netOverlap($myconn, $tabletype, $net, &$thisNet, $loguser) {
619
/* return TRUE if $net overlap an existing network into DB */
620
	$thisNet = NULL;
621
	if ($tabletype['field'] != 'network') {
622
		syslog(LOG_ERR, $loguser.': '.$tabletype['name'].' is not a network list.');
623
		return FALSE;
624
	}
625
	$result = searchentry ($myconn,'ALL',$tabletype);
626
        if ($result->num_rows) {
627
		while ($row = $result->fetch_array(MYSQLI_ASSOC)) {
628
			$thisNet = long2ip($row['network']).'/'.long2ip($row['netmask']);
629
			if ( isIn($thisNet, $net) ) {
630
				$result->free();
631
				syslog(LOG_INFO, "$loguser: the net <$net> overlaps the existing network <$thisNet>.");
632
				return TRUE;
633
			}
634
		}
635
	}
636
	$result->free();
637
	return FALSE;
638
}
639
640
/*********************************************************************************************/
641
642
643
/* For miltermap */
644
function checkMilterConf($table) {
645
	if (isset($table['milter'])) {
646
        	if ($table['milter'] ===  TRUE) {
647
			switch ( $table['field'] ) {
648
				case 'network':
649
				case 'ip':
650
					return TRUE;
651
			}
652
		}
653
	}
654
	return FALSE;
655
}			
656
657
/*
658
function enterDBMilt($myconn,$tables,$loguser) {
659
        if (!($myconn->select_db($tables('name')))) {
660
                syslog(LOG_ERR, $loguser.': Can\'t enter into DB '.$tables('name'));
661
                return FALSE;
662
        }
663
	return TRUE;
664
}
665
*/
666
667
function milterTable($t) {
668
	/* Return the milter object table for type t  or FALSE on error */
669
        switch ($t) {
670
                case 'network':
671
                        return 'net';
672
                case 'ip':
673
                        return 'ips';
674
                default:
675
			syslog(LOG_EMERG, "ALERT: type <$t> not allowed in configuration. ");
676
                        return FALSE;
677
        }
678
}
679
680
681
function readMiltName($myconn,$loguser) {
682
	$milters=array();
683
	$query = 'SELECT `name` FROM `config`';
684
685
        $result = $myconn->query($query);
686
        if($result === false) {
687
                syslog(LOG_EMERG, "$loguser: ALERT: Query <$query> failed: ".$myconn->error);
688
		return FALSE;
689
	}
690
	if ($result->num_rows) {
691
		while ($milt = $result->fetch_array(MYSQLI_ASSOC))
692
			$milters[] = $milt['name'];
693
	}
694
	$result->free();
695
	return $milters;
696
}
697
698
function changeMilter ($myconn,$loguser,$miltVal,$table,$miltID) {
699
	$query = array();
700
	foreach ( $miltVal as $value => $action ) {
701
		switch ( $action ) {
702
			case 'keep':
703
				break;
704
			case 'add':
705
				$query[] = sprintf( "INSERT INTO `milt` (
706
                		        	`id` ,
707
                        			`name` 
708
                			)
709
                			VALUES (
710
                        			%d ,
711
						'%s'
712
					)",$miltID,$value);
713
				break;
714
			case 'del':
715
				$query[] = "DELETE FROM  `milt` WHERE (`id` = '$miltID' AND `name` = '$value')";
716
		}
717
	}
718
	if ( count($query) ) /* This "if" is redundant, because if I call this I already checked there is a change */
719
		/* I update datemod because the user couldn't change */
720
		$query[] = sprintf('UPDATE `%s` SET
721
						`user`=\'%s\',
722
						`datemod`= CURRENT_TIMESTAMP
723
					 WHERE `idmilt`=%d', $table, $loguser, $miltID);
724
725
726
	/* Start a safe transaction: it commits only if all queries happen */
727
	$myconn->autocommit(FALSE);
728
	$myconn->begin_transaction(MYSQLI_TRANS_START_READ_ONLY);
729
	$ok = TRUE;
730
	foreach ( $query as $q ) {
731
		if ($myconn->query($q) !== TRUE) {
732
			$ok = FALSE;
733
			syslog(LOG_ERR, "$loguser: Error: ".$myconn->error);
734
		}
735
	}
736
	if ( $ok ) {
737
		if ( $myconn->commit() )
738
			syslog(LOG_INFO, "$loguser: Milter setting changed successfully.");
739
		else {
740
			syslog(LOG_ERR, "$loguser: Milter setting NOT changed for an unpredictable COMMIT error.");
741
			if ( $myconn->rollback() )
742
				syslog(LOG_INFO, "$loguser: rollback succeeded.");
743
			else
744
				syslog(LOG_ERR, "$loguser: rollback failed. Your db could be compromized. Check it!");
745
			$ok = FALSE;
746
		}
747
	}
748
	else
749
		syslog(LOG_ERR, "$loguser: Error: Milter setting NOT changed. See at above errors.");
750
	return $ok;
751
		
752
}
753
	
754
755
function curl_get($url, array $get = NULL, array $options = array(), $loguser)
756
{
757
    $defaults = array(
758
        CURLOPT_URL => $url. (strpos($url, '?') === FALSE ? '?' : ''). http_build_query($get),
759
        CURLOPT_HEADER => 0,
760
        CURLOPT_RETURNTRANSFER => TRUE,
761
        CURLOPT_TIMEOUT => 4
762
    );
763
764
    $ch = curl_init();
765
    curl_setopt_array($ch, ($options + $defaults));
766
    if( ! $result = curl_exec($ch))
767
    {
768
        syslog(LOG_ERR, sprintf('%s: CURL Error: <%s>', $loguser, curl_error($ch)));
769
    }
770
    curl_close($ch);
771
    return $result;
772
}
773
774
/*
0 ignored issues
show
Unused Code Comprehensibility introduced by
56% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
775
function checkEmailAddress($email) {
776
	if(preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/", $email))
777
		return true;
778
	return false;
779
}
780
781
function checkIP($ip)
782
{
783
	$cIP = ip2long($ip);
784
	$fIP = long2ip($cIP);
785
	if ($fIP == '0.0.0.0') return FALSE;
786
	return TRUE;
787
}
788
*/
789
790
?>
791
792