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 ( 4d35db...7c40ab )
by Marco
03:05
created

function.php ➔ curl_get()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 18
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 12
nc 4
nop 4
dl 0
loc 18
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
13
function myConnect($host, $user, $pass, $db, $port, $tablelist, $typedesc, $loguser) {
14
        $db = ( $tablelist["$typedesc"]['milter'] ) ? $tablelist["$typedesc"]['name'] : $db;
15
	$mysqli = new mysqli($host, $user, $pass, $db, $port);
16
        if ($mysqli->connect_error) {
17
           	syslog (LOG_EMERG, $loguser.': Connect Error to DB <'.$db.'> (' . $mysqli->connect_errno . ') '
18
                    		. $mysqli->connect_error);
19
		return FALSE;
20
	}
21
	syslog(LOG_INFO, $loguser.': Successfully MySQL connected at DB <'.$db.'> to ' . $mysqli->host_info) ;
22
	return $mysqli;
23
}
24
25
function addtolist ($myconn,$user,$value,$tabledesc,$expUnit,$expQ,$myreason,&$err) {
26
// See MySQL manual for $expQ and $expUnit at
27
// https://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_timestampadd
28
29
	$result=FALSE;
30
	$sub=array();
31
	$type = $tabledesc['field'];
32
	$milt = $tabledesc['milter'];
33
	$table = ($milt) ? milterTable($type) : $tabledesc['name'];
34
35
	switch ($type) {
36
	  case 'ip':
37
		$query= sprintf("INSERT INTO `$table` (
38
			`$type` ,
39
			`date` ,
40
			`exp` ,
41
			`active` ,
42
			`user` ,
43
			`reason`
44
		)
45
		VALUES (
46
			INET_ATON( '%s' ) ,
47
			CURRENT_TIMESTAMP , TIMESTAMPADD(%s,%d,CURRENT_TIMESTAMP), '1', '%s', '%s'
48
		)" ,$value,$expUnit,$expQ,$user,$myreason);
49
		break;
50
51
	  case 'network':
52
		if (!$milt) {
53
			if ( netOverlap($myconn, $tabledesc, $value, $overlappedNet, $user) ) {
54
				$err = "<$value> overlaps the existing network <$overlappedNet>";
55
				return FALSE;
56
			}
57
		}
58
		list($sub['net'],$sub['mask'])=explode('/',$value);
59
                $query= sprintf("INSERT INTO `$table` (
60
                        `$type` ,
61
			`netmask`,
62
                        `date` ,
63
                        `exp` ,
64
                        `active` ,
65
                        `user` ,
66
                        `reason`
67
                )
68
                VALUES (
69
                        INET_ATON( '%s' ) , INET_ATON( '%s' ) ,
70
                        CURRENT_TIMESTAMP , TIMESTAMPADD(%s,%d,CURRENT_TIMESTAMP), '1', '%s', '%s'
71
                )" ,$sub['net'],$sub['mask'],$expUnit,$expQ,$user,$myreason);
72
                break;
73
74
	  default:
75
                $query= sprintf("INSERT INTO `$table` (
76
                        `$type` ,
77
                        `date` ,
78
                        `exp` ,
79
                        `active` ,
80
                        `user` ,
81
                        `reason`
82
                )
83
                VALUES (
84
                        '%s' ,
85
                        CURRENT_TIMESTAMP , TIMESTAMPADD(%s,%d,CURRENT_TIMESTAMP), '1', '%s', '%s'
86
                )" ,$value,$expUnit,$expQ,$user,$myreason);
87
	}
88
89
	if ($myconn->query($query) === TRUE) {
90
	    syslog(LOG_INFO, "$user: $type <$value> successfully listed on <$table> for $expQ $expUnit.");
91
	    $result=TRUE;
92
	}
93
	else syslog(LOG_ERR, "$user: Error: ".$myconn->error);
94
	return $result;
95
}
96
97
function relist ($myconn,$user,$value,$type,$table,$expUnit,$expQ,$myreason, $exptime = 0) {
98
99
	$result=FALSE;
100
	if ( $exptime ) { /* Entry already listed */
101
		$nlist = '`nlist`';
102
		$exptime = sprintf('\'%s\'', $exptime);  /* Eh MySQL... an hour lost to notice this */
103
	}
104
	else {
105
		$exptime = 'CURRENT_TIMESTAMP';
106
		$nlist = '`nlist` + 1';
107
	}
108
109
        switch ($type) {
110 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...
111
                $query= sprintf("UPDATE `$table` SET
112
			`active` = '1',
113
			`user` = '%s',
114
			`exp` = TIMESTAMPADD(%s,%d,%s),
115
			`nlist` = %s,
116
			`reason` = '%s'
117
			WHERE `$table`.`$type` = INET_ATON('%s') LIMIT 1" ,$user,$expUnit,$expQ,$exptime,$nlist,$myreason,$value);
118
		break;
119
          case 'network':
120
		list($sub['net'],$sub['mask'])=explode('/',$value);
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') 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...
128
		break;
129 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...
130
                $query= sprintf("UPDATE `$table` SET
131
                        `active` = '1',
132
                        `user` = '%s',
133
                        `exp` = TIMESTAMPADD(%s,%d,%s),
134
                        `nlist` = %s,
135
                        `reason` = '%s'
136
			WHERE `$table`.`$type` = '%s' LIMIT 1" ,$user,$expUnit,$expQ,$exptime,$nlist,$myreason,$value);
137
	}
138
139
        if ($myconn->query($query) === TRUE) {
140
            syslog(LOG_INFO, "$user: relist $type <$value> on <$table> for $expQ $expUnit from $exptime.");
141
		$result=TRUE;
142
        }
143
        else syslog (LOG_ERR, "$user: Error: ". $myconn->error);
144
	return $result;
145
}
146
147
function remove ($myconn,$user,$value,$type,$table) {
148
149
        switch ($type) {
150
          case 'ip':
151
		$query = sprintf("DELETE FROM `$table` WHERE
152
                        `$table`.`$type` = INET_ATON('%s') LIMIT 1", $value);
153
		break;
154 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...
155
		list($sub['net'],$sub['mask'])=explode('/',$value);
156
		$query = sprintf("DELETE FROM `$table` WHERE
157
			`$table`.`$type` = INET_ATON('%s') AND `$table`.`netmask` = INET_ATON('%s') LIMIT 1",
158
			$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...
159
		break;
160
	  default:
161
		$query = sprintf("DELETE FROM `$table` WHERE
162
                        `$table`.`$type` = %s LIMIT 1", $value);
163
	}
164
165
166
        if ($return=$myconn->query($query) === TRUE) 
167
            syslog(LOG_INFO, "$user: permanently DELETED $type <$value> from <$table>.");
168
        else syslog(LOG_ERR, "$user: Error: ". $myconn->error);
169
170
        return $return;
171
}
172
173
174
function changestatus ($myconn,$user,$value,$status,$type,$table) {
175
176
	switch ($type) {
177
          case 'ip':
178
		$query= sprintf("UPDATE `$table` SET `active` = '$status', `user` = '%s' WHERE `$table`.`$type` = INET_ATON('%s') LIMIT 1" ,$user, $value);
179
		break;
180
	  case 'network':
181
		list($sub['net'],$sub['mask'])=explode('/',$value);
182
		$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...
183
		break;
184
	  default:
185
		$query= sprintf("UPDATE `$table` SET `active` = '$status', `user` = '%s' WHERE `$table`.`$type` = '%s' LIMIT 1" ,$user, $value);
186
	}
187
188
        if ($return=$myconn->query($query) === TRUE) {
189
            syslog(LOG_INFO, "$user: change status of $type <$value>. The status is now <$status>");
190
        }
191
        else syslog(LOG_ERR, "$user: Error: ". $myconn->error);
192
	return $return;	
193
}
194
195
196
function expire ($myconn,$user,$tables,$expireTime) {
197
        $return=TRUE;
198
	$log=array();
199
	$desc = array_keys($tables);
200
	foreach ($desc as $tdesc) { 
201
		/* QUERY */
202
		$query  = 'DELETE FROM `'.$tables["$tdesc"]['name']."` WHERE `exp` < DATE_SUB( NOW(), INTERVAL $expireTime YEAR);";
203
		$query .= 'DELETE FROM `'.$tables["$tdesc"]['name']."` WHERE `datemod` < DATE_SUB( NOW(), INTERVAL $expireTime YEAR) AND `active` = 0";
204
		/* END OF QUERY */
205
		$log[0] = 'expired for';
206
		$log[1] = 'disabled for';
207
        	if ($myconn->multi_query($query)) {
208
			$j = 0;
209
			do {
210
		    		$numdel = $myconn->affected_rows;
211
	            		syslog(LOG_INFO, "Expire job - <$user> Permanently DELETED $numdel records ".$log[$j]." $expireTime YEARS from <".$tables["$tdesc"]['name'].'>.');
212
				$j++;
213
214
			} while ($myconn->next_result());
215
		}
216
		else {
217
			syslog(LOG_ERR, "Expire job - Error: ". $myconn->error);
218
			$return = FALSE;
219
		}
220
	}
221
	if ( !($return) ) syslog(LOG_EMERG, 'End of Expire job with error. See above logs. SQL Connection terminated');
222
	else  syslog(LOG_INFO, 'Successfully End of Expire job. SQL Connection successfully terminated.');
223
        return $return;
224
}
225
226
227
function isListed($row) {
228
229
	$exp=new DateTime($row['exp']);
230
	$now=new DateTime('NOW');
231
	if (($exp > $now) and ($row['active'])) return true;
232
	else return false;
233
234
}
235
236
237
function askMilter($myconn,$id,$obj,$typedesc,$miltId,$value,$user,$adm)  {
238
	$milts = readMiltName($myconn,$user);
239
	$size = count($milts);
240
	if (in_array($user,array_keys($adm))) {
241
		$button = <<<END
242
		<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;" />
243
		<input name="object" type="hidden" value="$obj" /><input name="oldvalues" type="hidden" value="$value" />
244
		<input name="type" type="hidden" value="$typedesc" />
245
		<input name="user" type="hidden" value="$user" />
246
		<input name="miltId" type="hidden" value="$miltId" />
247
		<div class="noscroll">
248
		<select class="input_text" name="newvalues[]" multiple size="$size">
249
END;
250
		$activeMilts = explode(',',$value);
251
		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...
252
			if ( in_array($milter, $activeMilts) )
253
				$selected= 'selected';
254
			else
255
				$selected= NULL;
256
			$button .= sprintf('<option value="%s" %s>%s</option>', $milter, $selected, $milter);
257
		}	
258
		$button .= '</select></div><input class="button" name="Change" type="submit" value="Change" /></form>';
259
		return $button;
260
	}
261
	return $value;	
262
263
264
}
265
266
267
function ask($myconn,$id,$what,$alltables,$typedesc,$value,$lock,$user,$adm) {
268
269
	$whynot=NULL;
270
	switch ($what) {
271
		case 'Ok':
272
			if ($lock) return NULL;
273
			if (in_array($user,array_keys($adm)))
274
				if ( consistentListing($myconn,$alltables,$typedesc,$value,$whynot) ) return require('relistButton.php');
275
			return htmlspecialchars($whynot);
276
		case 'Listed':
277
		case 'WhiteListed':
278
			return require('delistButton.php');
279
	}
280
}
281
282
283
function consistentListing($myconn,$alltables,$typed,$value,&$warn) {
284
/* Check if there are no pending mislisting */
285
	$warn = NULL;
286
	if (! isset($alltables["$typed"]['depend']) ) return TRUE;
287
	foreach ($alltables["$typed"]['depend'] as $listdep) {
288
		if ($alltables["$typed"]['field'] != $alltables["$listdep"]['field'] ) {
289
			$warn = "Config ERROR: <$typed> and <$listdep> are of different types! I can't check consistency!";
290
			return FALSE;
291
		}
292
		$entry = searchentry($myconn,$value,$alltables["$listdep"]);
293
		if ( $entry->num_rows ) {
294
			if ( $entry->num_rows == 1 ) {
295
				$riga = $entry->fetch_array(MYSQLI_ASSOC);
296
                        	if (isListed($riga)) {
297
					$warn = "<$value> is already present in <$listdep> list!";
298
					$entry->free();
299
					return FALSE;
300
				}
301
			}
302
			if ( $entry->num_rows > 1 ) {$warn = "<$value> seems to be present more than once in <$listdep>. Contact a sysadmin NOW!";}
303
		}
304
		$entry->free();
305
	}
306
307
	return TRUE;
308
}
309
310
function searchentry ($myconn,$value,$tablelist) {
311
/* Make a MYSQL query and return result */
312
313
        $type = $tablelist['field'];
314
	
315
	if ( $tablelist['milter'] ) {
316
		$table = milterTable($type);
317
		if ($value == 'ALL')
318
			$query = sprintf('SELECT *, GROUP_CONCAT(milt.name) as miltnames FROM `%s` LEFT JOIN milt ON (%s.idmilt=milt.id) GROUP by idmilt',
319
				$table,$table);
320
		else {
321
			switch ($type) {
322 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...
323
					list($sub['net'],$sub['mask'])=explode('/',$value);
324
					$query = sprintf('SELECT * FROM (
325
							SELECT *, GROUP_CONCAT(milt.name) as miltnames FROM `%s` LEFT JOIN milt ON (%s.idmilt=milt.id)
326
				 				WHERE (
327
									inet_aton(\'%s\') >= network AND
328
									( inet_aton(\'%s\') | ( inet_aton(\'%s\') ^ (power(2,32)-1) ) )
329
										<= network | ( netmask ^ (power(2,32)-1) )
330
								)
331
				 				GROUP by idmilt
332
							) 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...
333
					break;
334
				case 'ip':
335
					$query = sprintf('SELECT * FROM (
336
							SELECT *, GROUP_CONCAT(milt.name) as miltnames FROM `%s` LEFT JOIN milt ON (%s.idmilt=milt.id)' .
337
                                                		'WHERE `ip` =  INET_ATON(\'%s\')
338
							 ) AS val WHERE val.ip IS NOT null', $table, $table, $value);
339
					break;
340
				default:
341
					syslog(LOG_EMERG, 'ALERT: The type <'.$type.'> is not allowed for milter lists.' );
342
					return FALSE;
343
			}
344
		}
345
	}
346
347
	else {
348
	        $table = $tablelist['name'];
349
	        if ($value == 'ALL') $query = 'select * from '.$table;
350
	        else {
351
	                switch ($type) {
352
	                  case 'ip':
353
	                        $query= "select * from $table where $type =  INET_ATON('$value')";
354
	                        break;
355 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...
356
	                        list($sub['net'],$sub['mask'])=explode('/',$value);
357
	                        $query= sprintf('select * from `%s`
358
						WHERE (
359
							inet_aton(\'%s\') >= network AND
360
							( inet_aton(\'%s\') | ( inet_aton(\'%s\') ^ (power(2,32)-1) ) )
361
								<= network | ( netmask ^ (power(2,32)-1) )
362
						)', $table, $sub['net'], $sub['net'], $sub['mask']);
363
;
364
	                        break;
365
	                  default:
366
	                        $query= "select * from $table where $type = '$value'";
367
	                }
368
	        }
369
	}
370
371
	$result = $myconn->query($query);
372
	if($result === false)
373
		syslog(LOG_EMERG, "ALERT: Query <$query> failed: ".$myconn->error);
374
        return $result;
375
}
376
377
function countListed ($myconn,$table) {
378
/* Return number of current listed items into a rbl table */
379
	$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";
380
	$row = $myconn->query($query);
381
	$number = $row->fetch_array(MYSQLI_ASSOC);
382
	$number = $number['count'];
383
	$row->free();
384
	return $number;
385
}
386
387
388
function isFull($myconn,$typedesc,$alltables) {
389
        if (isset($alltables["$typedesc"]['limit'])) {
390
		if ( $alltables["$typedesc"]['milter'] )
391
			$tab = 'net';
392
		else
393
			$tab = $alltables["$typedesc"]['name'];
394
                if ( countListed($myconn,$tab) >= $alltables["$typedesc"]['limit'] ) 
395
                        return TRUE;
396
        }
397
	return FALSE;
398
}
399
400
function rlookup ($myconn,$user,$adm,$value,$typedesc,$tables) {
401
402
	$type = $tables["$typedesc"]['field'];
403
	$whynot=NULL;
404
405
	$tabhtm = <<<END
406
	<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>
407
END;
408
	if ( $tables["$typedesc"]['milter'] )
409
		$tabhtm .= '<th title="Milter active for this object">Milters</th>';
410
	$tabhtm .= '<th>Authored by</th><th width="250">Reason</th><th>Action</th></tr></thead><tfoot><tr></tr></tfoot><tbody>'."\n";
411
412
	$result = searchentry ($myconn,$value,$tables["$typedesc"]);
413
	if ($result) {
414
		printf("<pre>Your request for $type &lt;$value&gt; returned %d items.\n</pre>", $result->num_rows);
415
416
        /* Check for limit in number of listed items */
417
	$full = isFull($myconn,$typedesc,$tables);
418
	if ($full) print '<p>'.htmlspecialchars("$typedesc has reached maximum value of ".$tables["$typedesc"]['limit'].' listed items.').'</p>';
419
420
		if ($result->num_rows) {
421
			print $tabhtm;
422
			$i=0;
423
        		while ($riga = $result->fetch_array(MYSQLI_ASSOC)) {
424
				if (isListed($riga)) {
425
					if ($tables["$typedesc"]['bl']) $listed='Listed';
426
					else $listed='WhiteListed';
427
				}	
428
				else
429
					$listed='Ok';
430
431
				switch ($type) {
432
				  case 'ip':
433
					$element = long2ip($riga['ip']);
434
					break;
435 View Code Duplication
				  case 'network':
436
					$element = long2ip($riga['network']).'/'.long2ip($riga['netmask']);
437
					break;
438
				  default:
439
					$element = $riga["$type"];
440
				}
441
442
				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...
443
					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",
444
					$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));
445
				else
446
					 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",
447
					$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));
448
				$i++;
449
        		}
450
			print '</tbody></table>';
451
		}
452
		else {
453
			print "<pre>$type &lt;$value&gt; is not listed!\n</pre>";
454
			if ( in_array($user,array_keys($adm)) AND ($value != 'ALL') )
455
				if ( (!$full) AND (consistentListing($myconn,$tables,$typedesc,$value,$whynot)) ) require_once('listForm.php');
456
									else print '<p>'.htmlspecialchars($whynot).'</p>';
457
				
458
		}
459
		$result->free();
460
	}
461
	else print '<pre>Query error or something wrong in DB schema'."\n</pre>";
462
}
463
464
465
466
        
467
function sendEmailWarn($tplf,$from,$to,$sbj,$emailListed,$intervalToExpire,$detail) {
468
	$now = time();
469
        setlocale (LC_TIME, 'it_IT');
470
        $date = date("r",$now);
471
	$messageID = md5(uniqid($now,1)) . '@' . gethostname();
472
	$mua = 'PHP/' . phpversion();
473
474
	/* Parsing headers */
475 View Code Duplication
	if (!file_exists($tplf['header'])) {
476
    		syslog(LOG_ERR, 'Sending email... template file <'.$tplf['header'].'> not found!');
477
    		exit;
478
	}
479
480
	$head_tmpl = file_get_contents($tplf['header']);
481
	$arr_tpl_vars = array('{from}','{to}','{date}','{messageID}','{mua}');
482
	$arr_tpl_data = array($from,$to,$date,$messageID,$mua);
483
	$headers = str_replace($arr_tpl_vars, $arr_tpl_data, $head_tmpl);
484
	$headers = preg_replace( '/\r|\n/', "\r\n", $headers );
485
486
        /* Parsing body */
487
488 View Code Duplication
        if (!file_exists($tplf['body'])) {
489
                syslog(LOG_ERR, 'Sending email... template file <'.$tplf['body'].'> not found!');
490
                exit;
491
        }
492
493
        $body_tmpl = file_get_contents($tplf['body']);
494
        $arr_tpl_vars = array('{emailListed}','{expInterval}','{reason}');
495
        $arr_tpl_data = array($emailListed,$intervalToExpire,$detail);
496
        $body = str_replace($arr_tpl_vars, $arr_tpl_data, $body_tmpl);
497
        $body = preg_replace( "/\r|\n/", "\r\n", $body );
498
	$body = wordwrap ( $body, 75 , "\r\n" );	
499
500
	/* Send the mail! */
501
        if ( strlen(ini_get("safe_mode"))< 1) {
502
                $old_mailfrom = ini_get("sendmail_from");
503
                ini_set("sendmail_from", $from);
504
                $params = sprintf("-oi -f %s", '<>');
505 View Code Duplication
                if (!(mail($to,$sbj, $body,$headers,$params))) $flag=FALSE;
506
                else $flag=TRUE;
507
                if (isset($old_mailfrom))
508
                        ini_set("sendmail_from", $old_mailfrom);
509
        }
510 View Code Duplication
        else {
511
                if (!(mail($to,$sbj, $body,$headers))) $flag=FALSE;
512
                else $flag=TRUE;
513
        }
514
        return $flag;
515
}
516
517
function emailToNotify($notify_file,$dom) {
518
	$ini_array = parse_ini_file($notify_file);
519
	if (in_array($dom,array_keys($ini_array)))
520
		return $ini_array["$dom"];
521
	else return FALSE;
522
}
523
524
525
function searchAndList ($myconn,$loguser,$tables,$typedesc,$value,$unit,&$quantity,&$reason) {
526
527
/* Search and list value */
528
        $type = $tables["$typedesc"]['field'];
529
        $table = $tables["$typedesc"]['name'];
530
        $result = searchentry ($myconn,$value,$tables["$typedesc"]);
531
532
        /* Manage abnormal conditions */
533
        /* Value already present in db more than once. This is absurd. Panic! */
534
        if ($result->num_rows > 1) {
535
                syslog(LOG_EMERG,"$loguser: PANIC! Select for $type '$value' returned ". $result->num_rows ." items instead of one. Abnormal. Contact a sysadmin or a developer.");
536
                $result->free();
537
                return FALSE;
538
        }
539
540
        /* Value already present in db or not present: to list anyway */
541
        if ($result->num_rows >= 0) {
542
                /* First, check for limit in number of listed items */
543
                if (isFull($myconn,$typedesc,$tables)) {
544
                        syslog(LOG_EMERG,"$loguser: $typedesc has reached maximum value of ".$tables["$typedesc"]['limit'].' listed items. Abnormal exit.');
545
                        $result->free();
546
                        return FALSE;
547
                }
548
                /* Second, check if the (re)list would be consistent now */
549
                if (! consistentListing($myconn,$tables,$typedesc,$value,$whynot) ) {
550
                        syslog(LOG_ERR, $loguser.': '.$whynot);
551
                        $result->free();
552
                        return FALSE;
553
                }
554
        }
555
        /* End of abnormal conditions */
556
557
558
        /* Finally, here I can list the value! */
559
	$thisentry = $result->fetch_array(MYSQLI_ASSOC);
560
        switch ($result->num_rows) {
561
                /* Relist value if already present */
562
                case 1:
563
                        if ( isListed($thisentry) ) {
564
				/* Entry already listed */
565
				$expdate = $thisentry['exp'];
566
				$reason = sprintf('%s. Already listed. Adding 1 DAY to previous expire date.',
567
					 $reason);
568
				$quantity = 1;
569
				$unit = 'DAY';
570
                        }
571
			else {
572
                        	/* Entry delisted */
573
				$quantity *= $thisentry['nlist'];
574
				$expdate = 0; /* This forces expiration from CURRENT_TIMESTAMP */
575
			}
576
			$result->free();
577
                        return relist ($myconn,$loguser,$value,$type,$table,$unit,$quantity,$reason, $expdate);
578
579
                /* First time list value */
580
                case 0:
581
                        $result->free();
582
                        return addtolist ($myconn,$loguser,$value,$tables["$typedesc"],$unit,$quantity,$reason,$_);
583
        }
584
}
585
586
587
/*************** Functions to check if two net overlap each other ********************/
588
589
function ipRange ($range) {
590
/* List IP in range */
591
	return array_map('long2ip', range( ip2long($range[0]), ip2long($range[1]) ) );
592
}
593
594
function isIn($netA, $netB) {
595
/* TRUE if an IP of $netA is contained in netB */
596
	list($addressA,$maskA) = explode('/', $netA);
597
	list($addressB,$maskB) = explode('/', $netB);
598
	require_once 'vendor/autoload.php';
599
	$net = new \dautkom\ipv4\IPv4();
600
	$range = $net->address($addressA)->mask($maskA)->getRange();
601
	$ips = ipRange($range);
602
	foreach ( $ips as $ip )
603
		if ( $net->address($addressB)->mask($maskB)->has($ip) )
604
			return TRUE;
605
	return FALSE;
606
}
607
608
function netOverlap($myconn, $tabletype, $net, &$thisNet, $loguser) {
609
/* return TRUE if $net overlap an existing network into DB */
610
	$thisNet = NULL;
611
	if ($tabletype['field'] != 'network') {
612
		syslog(LOG_ERR, $loguser.': '.$tabletype['name'].' is not a network list.');
613
		return FALSE;
614
	}
615
	$result = searchentry ($myconn,'ALL',$tabletype);
616
        if ($result->num_rows) {
617
		while ($row = $result->fetch_array(MYSQLI_ASSOC)) {
618
			$thisNet = long2ip($row['network']).'/'.long2ip($row['netmask']);
619
			if ( isIn($thisNet, $net) ) {
620
				$result->free();
621
				syslog(LOG_INFO, "$loguser: the net <$net> overlaps the existing network <$thisNet>.");
622
				return TRUE;
623
			}
624
		}
625
	}
626
	$result->free();
627
	return FALSE;
628
}
629
630
/*********************************************************************************************/
631
632
633
/* For miltermap */
634
function checkMilterConf($table) {
635
	if (isset($table['milter'])) {
636
        	if ($table['milter'] ===  TRUE) {
637
			switch ( $table['field'] ) {
638
				case 'network':
639
				case 'ip':
640
					return TRUE;
641
			}
642
		}
643
	}
644
	return FALSE;
645
}			
646
647
/*
648
function enterDBMilt($myconn,$tables,$loguser) {
649
        if (!($myconn->select_db($tables('name')))) {
650
                syslog(LOG_ERR, $loguser.': Can\'t enter into DB '.$tables('name'));
651
                return FALSE;
652
        }
653
	return TRUE;
654
}
655
*/
656
657
function milterTable($t) {
658
	/* Return the milter object table for type t  or FALSE on error */
659
        switch ($t) {
660
                case 'network':
661
                        return 'net';
662
                case 'ip':
663
                        return 'ips';
664
                default:
665
			syslog(LOG_EMERG, "ALERT: type <$t> not allowed in configuration. ");
666
                        return FALSE;
667
        }
668
}
669
670
671
function readMiltName($myconn,$loguser) {
672
	$milters=array();
673
	$query = 'SELECT `name` FROM `config`';
674
675
        $result = $myconn->query($query);
676
        if($result === false) {
677
                syslog(LOG_EMERG, "$loguser: ALERT: Query <$query> failed: ".$myconn->error);
678
		return FALSE;
679
	}
680
	if ($result->num_rows) {
681
		while ($milt = $result->fetch_array(MYSQLI_ASSOC))
682
			$milters[] = $milt['name'];
683
	}
684
	$result->free();
685
	return $milters;
686
}
687
688
function changeMilter ($myconn,$loguser,$miltVal,$table,$miltID) {
689
	$query = array();
690
	foreach ( $miltVal as $value => $action ) {
691
		switch ( $action ) {
692
			case 'keep':
693
				break;
694
			case 'add':
695
				$query[] = sprintf( "INSERT INTO `milt` (
696
                		        	`id` ,
697
                        			`name` 
698
                			)
699
                			VALUES (
700
                        			%d ,
701
						'%s'
702
					)",$miltID,$value);
703
				break;
704
			case 'del':
705
				$query[] = "DELETE FROM  `milt` WHERE (`id` = '$miltID' AND `name` = '$value')";
706
		}
707
	}
708
	if ( count($query) ) /* This "if" is redundant, because if I call this I already checked there is a change */
709
		/* I update datemod because the user couldn't change */
710
		$query[] = sprintf('UPDATE `%s` SET
711
						`user`=\'%s\',
712
						`datemod`= CURRENT_TIMESTAMP
713
					 WHERE `idmilt`=%d', $table, $loguser, $miltID);
714
715
716
	/* Start a safe transaction: it commits only if all queries happen */
717
	$myconn->autocommit(FALSE);
718
	$myconn->begin_transaction(MYSQLI_TRANS_START_READ_ONLY);
719
	$ok = TRUE;
720
	foreach ( $query as $q ) {
721
		if ($myconn->query($q) !== TRUE) {
722
			$ok = FALSE;
723
			syslog(LOG_ERR, "$loguser: Error: ".$myconn->error);
724
		}
725
	}
726
	if ( $ok ) {
727
		if ( $myconn->commit() )
728
			syslog(LOG_INFO, "$loguser: Milter setting changed successfully.");
729
		else {
730
			syslog(LOG_ERR, "$loguser: Milter setting NOT changed for an unpredictable COMMIT error.");
731
			if ( $myconn->rollback() )
732
				syslog(LOG_INFO, "$loguser: rollback succeeded.");
733
			else
734
				syslog(LOG_ERR, "$loguser: rollback failed. Your db could be compromized. Check it!");
735
			$ok = FALSE;
736
		}
737
	}
738
	else
739
		syslog(LOG_ERR, "$loguser: Error: Milter setting NOT changed. See at above errors.");
740
	return $ok;
741
		
742
}
743
	
744
745
function curl_get($url, array $get = NULL, array $options = array(), $loguser)
746
{
747
    $defaults = array(
748
        CURLOPT_URL => $url. (strpos($url, '?') === FALSE ? '?' : ''). http_build_query($get),
749
        CURLOPT_HEADER => 0,
750
        CURLOPT_RETURNTRANSFER => TRUE,
751
        CURLOPT_TIMEOUT => 4
752
    );
753
754
    $ch = curl_init();
755
    curl_setopt_array($ch, ($options + $defaults));
756
    if( ! $result = curl_exec($ch))
757
    {
758
        syslog(LOG_ERR, sprintf('%s: CURL Error: <%s>', $loguser, curl_error($ch)));
759
    }
760
    curl_close($ch);
761
    return $result;
762
}
763
764
/*
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...
765
function checkEmailAddress($email) {
766
	if(preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/", $email))
767
		return true;
768
	return false;
769
}
770
771
function checkIP($ip)
772
{
773
	$cIP = ip2long($ip);
774
	$fIP = long2ip($cIP);
775
	if ($fIP == '0.0.0.0') return FALSE;
776
	return TRUE;
777
}
778
*/
779
780
?>
781
782