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
Branch master (eb5762)
by Marco
05:09 queued 02:37
created

function.php (21 issues)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

1
<?php
2
3
$version='1.9d';
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 addtolist ($myconn,$user,$value,$type,$table,$expUnit,$expQ,$myreason) {
14
// See MySQL manual for $expQ and $expUnit at
15
// https://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_timestampadd
16
17
	$result=FALSE;
18
19 View Code Duplication
	switch ($type) {
1 ignored issue
show
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...
20
	  case 'ip':
21
		$query= sprintf("INSERT INTO `$table` (
22
			`$type` ,
23
			`date` ,
24
			`exp` ,
25
			`active` ,
26
			`user` ,
27
			`reason`
28
		)
29
		VALUES (
30
			INET_ATON( '%s' ) ,
31
			CURRENT_TIMESTAMP , TIMESTAMPADD(%s,%d,CURRENT_TIMESTAMP), '1', '%s', '%s'
32
		)" ,$value,$expUnit,$expQ,$user,$myreason);
33
		break;
34
35
	  case 'network':
36
		list($sub['net'],$sub['mask'])=explode('/',$value);
37
                $query= sprintf("INSERT INTO `$table` (
38
                        `$type` ,
39
			`netmask`,
40
                        `date` ,
41
                        `exp` ,
42
                        `active` ,
43
                        `user` ,
44
                        `reason`
45
                )
46
                VALUES (
47
                        INET_ATON( '%s' ) , INET_ATON( '%s' ) ,
48
                        CURRENT_TIMESTAMP , TIMESTAMPADD(%s,%d,CURRENT_TIMESTAMP), '1', '%s', '%s'
49
                )" ,$sub['net'],$sub['mask'],$expUnit,$expQ,$user,$myreason);
0 ignored issues
show
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...
50
                break;
51
52
	  default:
53
                $query= sprintf("INSERT INTO `$table` (
54
                        `$type` ,
55
                        `date` ,
56
                        `exp` ,
57
                        `active` ,
58
                        `user` ,
59
                        `reason`
60
                )
61
                VALUES (
62
                        '%s' ,
63
                        CURRENT_TIMESTAMP , TIMESTAMPADD(%s,%d,CURRENT_TIMESTAMP), '1', '%s', '%s'
64
                )" ,$value,$expUnit,$expQ,$user,$myreason);
65
	}
66
67 View Code Duplication
	if ($myconn->query($query) === TRUE) {
1 ignored issue
show
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...
68
	    syslog(LOG_INFO, "$user: $type <$value> successfully listed on <$table> for $expQ $expUnit.");
69
	    $result=TRUE;
70
	}
71
	else syslog(LOG_ERR, "$user: Error: ".$myconn->error);
72
	return $result;
73
}
74
75
function relist ($myconn,$user,$value,$type,$table,$expUnit,$expQ,$myreason) {
76
77
	$result=FALSE;
78
79
        switch ($type) {
80
	  case 'ip':
81
                $query= sprintf("UPDATE `$table` SET
82
			`active` = '1',
83
			`user` = '%s',
84
			`exp` = TIMESTAMPADD(%s,%d,CURRENT_TIMESTAMP),
85
			`nlist` = `nlist` + 1,
86
			`reason` = '%s'
87
			WHERE `$table`.`$type` = INET_ATON('%s') LIMIT 1" ,$user,$expUnit,$expQ,$myreason,$value);
88
		break;
89
          case 'network':
90
		list($sub['net'],$sub['mask'])=explode('/',$value);
91
                $query= sprintf("UPDATE `$table` SET
92
                        `active` = '1',
93
                        `user` = '%s',
94
                        `exp` = TIMESTAMPADD(%s,%d,CURRENT_TIMESTAMP),
95
                        `nlist` = `nlist` + 1,
96
                        `reason` = '%s'
97
                        WHERE (`$table`.`$type` = INET_ATON('%s') AND `$table`.`netmask` = INET_ATON('%s')) LIMIT 1" ,$user,$expUnit,$expQ,$myreason,$sub['net'],$sub['mask']);
98
		break;
99
	  default:
100
                $query= sprintf("UPDATE `$table` SET
101
                        `active` = '1',
102
                        `user` = '%s',
103
                        `exp` = TIMESTAMPADD(%s,%d,CURRENT_TIMESTAMP),
104
                        `nlist` = `nlist` + 1,
105
                        `reason` = '%s'
106
			WHERE `$table`.`$type` = '%s' LIMIT 1" ,$user,$expUnit,$expQ,$myreason,$value);
107
	}
108
109 View Code Duplication
        if ($myconn->query($query) === TRUE) {
1 ignored issue
show
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...
110
            syslog(LOG_INFO, "$user: relist $type <$value> on <$table> for $expQ $expUnit.");
111
		$result=TRUE;
112
        }
113
        else syslog (LOG_ERR, "$user: Error: ". $myconn->error);
114
	return $result;
115
}
116
117
function remove ($myconn,$user,$value,$type,$table) {
118
        $result=FALSE;
0 ignored issues
show
$result is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
119
120
        switch ($type) {
121
          case 'ip':
122
		$query = sprintf("DELETE FROM `$table` WHERE
123
                        `$table`.`$type` = INET_ATON('%s') LIMIT 1", $value);
124
		break;
125
	  case 'network':
126
		list($sub['net'],$sub['mask'])=explode('/',$value);
127
		$query = sprintf("DELETE FROM `$table` WHERE
128
			`$table`.`$type` = INET_ATON('%s') AND `$table`.`netmask` = INET_ATON('%s') LIMIT 1",
129
			$sub['net'],$sub['mask']);
130
		break;
131
	  default:
132
		$query = sprintf("DELETE FROM `$table` WHERE
133
                        `$table`.`$type` = %s LIMIT 1", $value);
134
	}
135
136
137
        if ($return=$myconn->query($query) === TRUE) 
138
            syslog(LOG_INFO, "$user: permanently DELETED $type <$value> from <$table>.");
139
        else syslog(LOG_ERR, "$user: Error: ". $myconn->error);
140
141
        return $return;
142
}
143
144
145
function changestatus ($myconn,$user,$value,$status,$type,$table) {
146
147 View Code Duplication
	switch ($type) {
148
          case 'ip':
149
		$query= sprintf("UPDATE `$table` SET `active` = '$status', `user` = '%s' WHERE `$table`.`$type` = INET_ATON('%s') LIMIT 1" ,$user, $value);
150
		break;
151
	  case 'network':
152
		list($sub['net'],$sub['mask'])=explode('/',$value);
153
		$query= sprintf("UPDATE `$table` SET `active` = '$status', `user` = '%s' WHERE (`$table`.`$type` = INET_ATON('%s') AND `$table`.`netmask` = INET_ATON('%s')) LIMIT 1" ,$user, $sub['net'],$sub['mask']);
154
		break;
155
	  default:
156
		$query= sprintf("UPDATE `$table` SET `active` = '$status', `user` = '%s' WHERE `$table`.`$type` = '%s' LIMIT 1" ,$user, $value);
157
	}
158
159
        if ($return=$myconn->query($query) === TRUE) {
160
            syslog(LOG_INFO, "$user: change status of $type <$value>. The status is now <$status>");
161
        }
162
        else syslog(LOG_ERR, "$user: Error: ". $myconn->error);
163
	return $return;	
164
}
165
166
167
function expire ($myconn,$user,$tables,$expireTime) {
168
        $return=TRUE;
169
	$desc = array_keys($tables);
170
	foreach ($desc as $tdesc) { 
171
		/* QUERY */
172
		$query  = 'DELETE FROM `'.$tables["$tdesc"]['name']."` WHERE `exp` < DATE_SUB( NOW(), INTERVAL $expireTime YEAR);";
173
		$query .= 'DELETE FROM `'.$tables["$tdesc"]['name']."` WHERE `datemod` < DATE_SUB( NOW(), INTERVAL $expireTime YEAR) AND `active` = 0";
174
		/* END OF QUERY */
175
		$log[0] = 'expired for';
0 ignored issues
show
Coding Style Comprehensibility introduced by
$log was never initialized. Although not strictly required by PHP, it is generally a good practice to add $log = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
176
		$log[1] = 'disabled for';
0 ignored issues
show
The variable $log does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
177
        	if ($myconn->multi_query($query)) {
178
			$j = 0;
179
			do {
180
		    		$numdel = $myconn->affected_rows;
181
	            		syslog(LOG_INFO, "Expire job - <$user> Permanently DELETED $numdel records ".$log[$j]." $expireTime YEARS from <".$tables["$tdesc"]['name'].'>.');
182
				$j++;
183
184
			} while ($myconn->next_result());
185
		}
186
		else {
187
			syslog(LOG_ERR, "Expire job - Error: ". $myconn->error);
188
			$return = FALSE;
189
		}
190
	}
191
	if ( !($return) ) syslog(LOG_EMERG, 'End of Expire job with error. See above logs. SQL Connection terminated');
192
	else  syslog(LOG_INFO, 'Successfully End of Expire job. SQL Connection successfully terminated.');
193
        return $return;
194
}
195
196
197
function isListed($row) {
198
199
	$exp=new DateTime($row['exp']);
200
	$now=new DateTime('NOW');
201
	if (($exp > $now) and ($row['active'])) return true;
1 ignored issue
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...
202
	else return false;
203
204
}
205
206
207
function ask($myconn,$id,$what,$alltables,$typedesc,$value,$lock,$user,$adm) {
208
209
	switch ($what) {
210
		case 'Ok':
211
			if ($lock) return NULL;
212
			if (in_array($user,array_keys($adm)))
213
				if ( consistentListing($myconn,$alltables,$typedesc,$value,$whynot) ) return require('relistButton.php');
214
			return htmlspecialchars($whynot);
0 ignored issues
show
The variable $whynot does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
215
		case 'Listed':
216
		case 'WhiteListed':
217
			return require('delistButton.php');
218
	}
219
}
220
221
222
function consistentListing($myconn,$alltables,$typed,$value,&$warn) {
223
/* Check if there are no pending mislisting */
224
	$warn = NULL;
225
	foreach ($alltables["$typed"]['depend'] as $listdep) {
226
		if ($alltables["$typed"]['field'] != $alltables["$listdep"]['field'] ) {
227
			$warn = "Config ERROR: <$typed> and <$listdep> are of different types! I can't check consistency!";
228
			return FALSE;
229
		}
230
		$entry = searchentry($myconn,$value,$alltables["$listdep"]);
231
		if ( $entry->num_rows ) {
232
			if ( $entry->num_rows == 1 ) {
233
				$riga = $entry->fetch_array(MYSQLI_ASSOC);
234
                        	if (isListed($riga)) {
235
					$warn = "<$value> is already present in <$listdep> list!";
236
					$entry->free();
237
					return FALSE;
238
				}
239
			}
240
			if ( $entry->num_rows > 1 ) {$warn = "<$value> seems to be present more than once in <$listdep>. Contact a sysadmin NOW!";}
241
		}
242
		$entry->free();
243
	}
244
245
	return TRUE;
246
}
247
248
function searchentry ($myconn,$value,$tablelist) {
249
/* Make a MYSQL query and return result */
250
251
        $type = $tablelist['field'];
252
        $table = $tablelist['name'];
253
254
        if ($value == 'ALL') $query = 'select * from '.$table;
255
        else {
256
                switch ($type) {
257
                  case 'ip':
258
                        $query= "select * from $table where $type =  INET_ATON('$value')";
259
                        break;
260
                  case 'network':
261
                        list($sub['net'],$sub['mask'])=explode('/',$value);
262
                        $query= 'select * from '.$table.' where (((inet_aton(\''.$sub['net'].'\') | (~ inet_aton(\''.$sub['mask'].'\'))) & netmask) = network)';
263
                        break;
264
                  default:
265
                        $query= "select * from $table where $type = '$value'";
266
                }
267
        }
268
269
	$result = $myconn->query($query);
270
	if($result === false)
271
		syslog(LOG_EMERG, "ALERT: Query <$query> failed: ".$myconn->error);
272
        return $result;
273
}
274
275
function countListed ($myconn,$table) {
276
/* Return number of current listed items into a rbl table */
277
	$number = 0;
0 ignored issues
show
$number is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
278
	$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";
279
	$row = $myconn->query($query);
280
	$number = $row->fetch_array(MYSQLI_ASSOC);
281
	$number = $number['count'];
282
	$row->free();
283
	return $number;
284
}
285
286
287
function isFull($myconn,$typedesc,$alltables) {
288
        if (isset($alltables["$typedesc"]['limit'])) {
289
                if ( countListed($myconn,$alltables["$typedesc"]['name']) >= $alltables["$typedesc"]['limit'] ) 
290
                        return TRUE;
291
        }
292
	return FALSE;
293
}
294
295
function rlookup ($myconn,$user,$adm,$value,$typedesc,$tables) {
296
297
	$type = $tables["$typedesc"]['field'];
298
	$table = $tables["$typedesc"]['name'];
0 ignored issues
show
$table is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
299
300
	$result = searchentry ($myconn,$value,$tables["$typedesc"]);
301
	if ($result) {
302
		printf("<pre>Your request for $type &lt;$value&gt; returned %d items.\n</pre>", $result->num_rows);
303
304
        /* Check for limit in number of listed items */
305
	$full = isFull($myconn,$typedesc,$tables);
306
	if ($full) print '<p>'.htmlspecialchars("$typedesc has reached maximum value of ".$tables["$typedesc"]['limit'].' listed items.').'</p>';
307
308
		if ($result->num_rows) {
309
			print '<table><thead><tr><th>'.$type.'</th><th title="The date this object has been listed for the first time">DateAdd</th><th>DateMod</th><th>Exp</th><th>Status</th><th title="Number of times this object has been listed">#List</th><th>Authored by</th><th width="250">Reason</th><th>Action</th></tr></thead><tfoot><tr></tr></tfoot><tbody>'."\n";
310
			$i=0;
311
        		while ($riga = $result->fetch_array(MYSQLI_ASSOC)) {
312
				if (isListed($riga)) {
313
					if ($tables["$typedesc"]['bl']) $listed='Listed';
314
					else $listed='WhiteListed';
315
				}	
316
				else
317
					$listed='Ok';
318
319
				switch ($type) {
320
				  case 'ip':
321
					$element = long2ip($riga['ip']);
322
					break;
323 View Code Duplication
				  case 'network':
1 ignored issue
show
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...
324
					$element = long2ip($riga['network']).'/'.long2ip($riga['netmask']);
325
					break;
326
				  default:
327
					$element = $riga["$type"];
328
				}
329
330
                		printf ("<tr id=id$i><td id='status$listed'>%s</td><td id='status$listed'>%s</td><td id='status$listed'>%s</td><td id='status$listed'>%s</td><td id='status$listed'>%s</td><td id='status$listed'>%s</td><td id='status$listed'>%s</td><td id='status$listed'>%s</td><td>%s</td></tr>\n", $element, $riga['date'], $riga['datemod'], $riga['exp'], $riga['active'], $riga['nlist'], $riga['user'],htmlspecialchars($riga['reason']),ask($myconn,$i,$listed,$tables,$typedesc,$element,$full,$user,$adm));
331
				$i++;
332
        		}
333
			print '</tbody></table>';
334
		}
335
		else {
336
			print "<pre>$type &lt;$value&gt; is not listed!\n</pre>";
337
			if ( in_array($user,array_keys($adm)) AND ($value != 'ALL') )
1 ignored issue
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...
338
				if ( (!$full) AND (consistentListing($myconn,$tables,$typedesc,$value,$whynot)) ) require_once('listForm.php');
1 ignored issue
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...
339
									else print '<p>'.htmlspecialchars($whynot).'</p>';
0 ignored issues
show
The variable $whynot does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
340
				
341
		}
342
		$result->free();
343
	}
344
	else print '<pre>Query error or something wrong in DB schema'."\n</pre>";
345
}
346
347
348
function sendEmailWarn($tplf,$from,$to,$sbj,$emailListed,$intervalToExpire,$detail) {
1 ignored issue
show
sendEmailWarn 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...
349
	$now = time();
350
        setlocale (LC_TIME, 'it_IT');
351
        $date = date("r",$now);
352
	$messageID = md5(uniqid($now,1)) . '@' . $_SERVER["HOSTNAME"];
353
	$mua = 'PHP/' . phpversion();
354
355
	/* Parsing headers */
356 View Code Duplication
	if (!file_exists($tplf['header'])) {
1 ignored issue
show
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...
357
    		syslog(LOG_ERR, 'Sending email... template file <'.$tplf['header'].'> not found!');
358
    		exit;
1 ignored issue
show
Coding Style Compatibility introduced by
The function sendEmailWarn() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
359
	}
360
361
	$head_tmpl = file_get_contents($tplf['header']);
362
	$arr_tpl_vars = array('{from}','{to}','{date}','{messageID}','{mua}');
363
	$arr_tpl_data = array($from,$to,$date,$messageID,$mua);
364
	$headers = str_replace($arr_tpl_vars, $arr_tpl_data, $head_tmpl);
365
	$headers = preg_replace( '/\r|\n/', "\r\n", $headers );
366
367
        /* Parsing body */
368
369 View Code Duplication
        if (!file_exists($tplf['body'])) {
1 ignored issue
show
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...
370
                syslog(LOG_ERR, 'Sending email... template file <'.$tplf['body'].'> not found!');
371
                exit;
1 ignored issue
show
Coding Style Compatibility introduced by
The function sendEmailWarn() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
372
        }
373
374
        $body_tmpl = file_get_contents($tplf['body']);
375
        $arr_tpl_vars = array('{emailListed}','{expInterval}','{reason}');
376
        $arr_tpl_data = array($emailListed,$intervalToExpire,$detail);
377
        $body = str_replace($arr_tpl_vars, $arr_tpl_data, $body_tmpl);
378
        $body = preg_replace( "/\r|\n/", "\r\n", $body );
379
	$body = wordwrap ( $body, 75 , "\r\n" );	
380
381
	/* Send the mail! */
382
	$params = NULL;
0 ignored issues
show
$params is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
383
        if ( strlen(ini_get("safe_mode"))< 1) {
384
                $old_mailfrom = ini_get("sendmail_from");
385
                ini_set("sendmail_from", $from);
386
                $params = sprintf("-oi -f %s", '<>');
387 View Code Duplication
                if (!(mail($to,$sbj, $body,$headers,$params))) $flag=FALSE;
388
                else $flag=TRUE;
389
                if (isset($old_mailfrom))
390
                        ini_set("sendmail_from", $old_mailfrom);
391
        }
392 View Code Duplication
        else {
393
                if (!(mail($to,$sbj, $body,$headers))) $flag=FALSE;
394
                else $flag=TRUE;
395
        }
396
        return $flag;
397
}
398
399
function emailToNotify($notify_file,$dom) {
400
	$ini_array = parse_ini_file($notify_file);
401
	if (in_array($dom,array_keys($ini_array)))
402
		return $ini_array["$dom"];
403
	else return FALSE;
404
}
405
406
407
function searchAndList ($myconn,$loguser,$tables,$typedesc,$value,$unit,&$quantity,$reason) {
408
409
/* Search and list value */
410
        $type = $tables["$typedesc"]['field'];
411
        $table = $tables["$typedesc"]['name'];
412
        $result = searchentry ($myconn,$value,$tables["$typedesc"]);
413
414
        /* Manage abnormal conditions */
415
        /* Value already present in db more than once. This is absurd. Panic! */
416
        if ($result->num_rows > 1) {
417
                syslog(LOG_EMERG,"$loguser: PANIC! Select for $type '$value' returned ". $result->num_rows ." items instead of one. Abnormal. Contact a sysadmin or a developer.");
418
                $result->free();
419
                return FALSE;
420
        }
421
422
        /* Value already present in db or not present: to list anyway */
423
        if ($result->num_rows >= 0) {
424
                /* First, check for limit in number of listed items */
425
                if (isFull($myconn,$typedesc,$tables)) {
426
                        syslog(LOG_EMERG,"$loguser: $typedesc has reached maximum value of ".$tables["$typedesc"]['limit'].' listed items. Abnormal exit.');
427
                        $result->free();
428
                        return FALSE;
429
                }
430
                /* Second, check if the (re)list would be consistent now */
431
                if (! consistentListing($myconn,$tables,$typedesc,$value,$whynot) ) {
432
                        syslog(LOG_ERR, $loguser.': '.$whynot);
433
                        $result->free();
434
                        return FALSE;
435
                }
436
        }
437
        /* End of abnormal conditions */
438
439
440
        /* Finally, here I can list the value! */
441
	$thisentry = $result->fetch_array(MYSQLI_ASSOC);
442
        switch ($result->num_rows) {
443
                /* Relist value if already present */
444
                case 1:
445
                        /* Entry already listed */
446
                        if ( isListed($thisentry) ) {
447
                                syslog(LOG_INFO, $loguser.': '.$value.' already listed. Nothing to do.');
448
                                $result->free();
449
                                return FALSE;
450
                        }
451
452
                        /* Entry delisted */
453
                        $result->free();
454
			$quantity *= $thisentry['nlist'];
455
                        return relist ($myconn,$loguser,$value,$type,$table,$unit,$quantity,$reason);
456
457
458
                /* First time list value */
459
                case 0:
460
                        $result->free();
461
                        return addtolist ($myconn,$loguser,$value,$type,$table,$unit,$quantity,$reason);
462
        }
463
}
464
465
466
	
467
/*
468
function checkEmailAddress($email) {
469
	if(preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/", $email))
470
		return true;
471
	return false;
472
}
473
474
function checkIP($ip)
475
{
476
	$cIP = ip2long($ip);
477
	$fIP = long2ip($cIP);
478
	if ($fIP == '0.0.0.0') return FALSE;
479
	return TRUE;
480
}
481
*/
482
483
?>
484
485