Completed
Push — master ( 77f38a...30f74b )
by Gary
04:59
created
functions/scripts/reset-admin-password.php 2 patches
Indentation   +47 added lines, -47 removed lines patch added patch discarded remove patch
@@ -30,14 +30,14 @@  discard block
 block discarded – undo
30 30
 // check if argv[1] provided, if not check readline support and wait for user pass
31 31
 if (isset($argv[1]))	{ $password = $argv[1]; }
32 32
 else {
33
-	// get available extensions
34
-	$available_extensions = get_loaded_extensions();
35
-	// not in array
36
-	if (!in_array("readline", $available_extensions)) 		{ $Result->show_cli("readline php extension is required.\nOr provide password as first argument", true); }
37
-	else {
38
-		// read password
39
-		$password = trim( readline("Enter new admin password: ") );
40
-	}
33
+    // get available extensions
34
+    $available_extensions = get_loaded_extensions();
35
+    // not in array
36
+    if (!in_array("readline", $available_extensions)) 		{ $Result->show_cli("readline php extension is required.\nOr provide password as first argument", true); }
37
+    else {
38
+        // read password
39
+        $password = trim( readline("Enter new admin password: ") );
40
+    }
41 41
 }
42 42
 
43 43
 // validate password
@@ -50,8 +50,8 @@  discard block
 block discarded – undo
50 50
 
51 51
 // set update array
52 52
 $values = array("id"=>1,
53
-				"password"=>$password_crypted
54
-				);
53
+                "password"=>$password_crypted
54
+                );
55 55
 
56 56
 // update password
57 57
 if(!$Admin->object_modify("users", "edit", "id", $values))	{ $Result->show_cli("Failed to update Admin password", false); }
@@ -59,10 +59,10 @@  discard block
 block discarded – undo
59 59
 
60 60
 // debug ?
61 61
 if ($debugging) {
62
-	$Result->show_cli("---------");
63
-	$Result->show_cli("Crypt type: ".$crypt_type);
64
-	$Result->show_cli("Password: ".$password_crypted);
65
-	$Result->show_cli("---------");
62
+    $Result->show_cli("---------");
63
+    $Result->show_cli("Crypt type: ".$crypt_type);
64
+    $Result->show_cli("Password: ".$password_crypted);
65
+    $Result->show_cli("---------");
66 66
 }
67 67
 
68 68
 // fail
@@ -70,7 +70,7 @@  discard block
 block discarded – undo
70 70
 
71 71
 # check for recipients
72 72
 foreach($Admin->fetch_multiple_objects ("users", "role", "Administrator") as $admin) {
73
-	$recepients[] = array("name"=>$admin->real_name, "email"=>$admin->email);
73
+    $recepients[] = array("name"=>$admin->real_name, "email"=>$admin->email);
74 74
 }
75 75
 # none?
76 76
 if(!isset($recepients))	{ die(); }
@@ -80,38 +80,38 @@  discard block
 block discarded – undo
80 80
 
81 81
 # try to send
82 82
 try {
83
-	// fetch mailer settings
84
-	$mail_settings = $Admin->fetch_object("settingsMail", "id", 1);
85
-	# initialize mailer
86
-	$phpipam_mail = new phpipam_mail($settings, $mail_settings);
87
-
88
-	// set subject
89
-	$subject	= "phpIPAM Administrator password updated";
90
-	//html
91
-	$content[] = "<h3>phpIPAM Administrator password updated</h3>";
92
-	$content[] = "<hr>";
93
-	$content[] = "Administrator password was updated via cli script";
94
-	//plain
95
-	$content_plain[] = "phpIPAM Administrator password updated \r\n------------------------------";
96
-	$content_plain[] = "Administrator password was updated via cli script";
97
-
98
-
99
-	# set content
100
-	$content 		= $phpipam_mail->generate_message (implode("\r\n", $content));
101
-	$content_plain 	= implode("\r\n",$content_plain);
102
-
103
-	$phpipam_mail->Php_mailer->setFrom($mail_settings->mAdminMail, $mail_settings->mAdminName);
104
-	//add all admins to CC
105
-	foreach($recepients as $admin) {
106
-		$phpipam_mail->Php_mailer->addAddress(addslashes($admin['email']), addslashes($admin['name']));
107
-	}
108
-	$phpipam_mail->Php_mailer->Subject = $subject;
109
-	$phpipam_mail->Php_mailer->msgHTML($content);
110
-	$phpipam_mail->Php_mailer->AltBody = $content_plain;
111
-	//send
112
-	$phpipam_mail->Php_mailer->send();
83
+    // fetch mailer settings
84
+    $mail_settings = $Admin->fetch_object("settingsMail", "id", 1);
85
+    # initialize mailer
86
+    $phpipam_mail = new phpipam_mail($settings, $mail_settings);
87
+
88
+    // set subject
89
+    $subject	= "phpIPAM Administrator password updated";
90
+    //html
91
+    $content[] = "<h3>phpIPAM Administrator password updated</h3>";
92
+    $content[] = "<hr>";
93
+    $content[] = "Administrator password was updated via cli script";
94
+    //plain
95
+    $content_plain[] = "phpIPAM Administrator password updated \r\n------------------------------";
96
+    $content_plain[] = "Administrator password was updated via cli script";
97
+
98
+
99
+    # set content
100
+    $content 		= $phpipam_mail->generate_message (implode("\r\n", $content));
101
+    $content_plain 	= implode("\r\n",$content_plain);
102
+
103
+    $phpipam_mail->Php_mailer->setFrom($mail_settings->mAdminMail, $mail_settings->mAdminName);
104
+    //add all admins to CC
105
+    foreach($recepients as $admin) {
106
+        $phpipam_mail->Php_mailer->addAddress(addslashes($admin['email']), addslashes($admin['name']));
107
+    }
108
+    $phpipam_mail->Php_mailer->Subject = $subject;
109
+    $phpipam_mail->Php_mailer->msgHTML($content);
110
+    $phpipam_mail->Php_mailer->AltBody = $content_plain;
111
+    //send
112
+    $phpipam_mail->Php_mailer->send();
113 113
 } catch (phpmailerException $e) {
114
-	$Result->show_cli("Mailer Error: ".$e->errorMessage(), true);
114
+    $Result->show_cli("Mailer Error: ".$e->errorMessage(), true);
115 115
 } catch (Exception $e) {
116
-	$Result->show_cli("Mailer Error: ".$e->getMessage(), true);
116
+    $Result->show_cli("Mailer Error: ".$e->getMessage(), true);
117 117
 }
118 118
\ No newline at end of file
Please login to merge, or discard this patch.
Spacing   +20 added lines, -20 removed lines patch added patch discarded remove patch
@@ -8,7 +8,7 @@  discard block
 block discarded – undo
8 8
  */
9 9
 
10 10
 # include required scripts
11
-require_once( dirname(__FILE__) . '/../functions.php' );
11
+require_once(dirname(__FILE__).'/../functions.php');
12 12
 
13 13
 # Set php warnign levels
14 14
 error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE);
@@ -18,35 +18,35 @@  discard block
 block discarded – undo
18 18
 $disable_email_notification = false;
19 19
 
20 20
 # initialize objects
21
-$Database 	= new Database_PDO;
22
-$Admin		= new Admin ($Database, false);
23
-$User		= new User ($Database, true);
24
-$Result		= new Result();
21
+$Database = new Database_PDO;
22
+$Admin = new Admin($Database, false);
23
+$User = new User($Database, true);
24
+$Result = new Result();
25 25
 
26 26
 
27 27
 // script can only be run from cli
28
-if(php_sapi_name()!="cli") 									{ $Result->show_cli("This script can only be run from cli", true); }
28
+if (php_sapi_name() != "cli") { $Result->show_cli("This script can only be run from cli", true); }
29 29
 
30 30
 // check if argv[1] provided, if not check readline support and wait for user pass
31
-if (isset($argv[1]))	{ $password = $argv[1]; }
31
+if (isset($argv[1])) { $password = $argv[1]; }
32 32
 else {
33 33
 	// get available extensions
34 34
 	$available_extensions = get_loaded_extensions();
35 35
 	// not in array
36
-	if (!in_array("readline", $available_extensions)) 		{ $Result->show_cli("readline php extension is required.\nOr provide password as first argument", true); }
36
+	if (!in_array("readline", $available_extensions)) { $Result->show_cli("readline php extension is required.\nOr provide password as first argument", true); }
37 37
 	else {
38 38
 		// read password
39
-		$password = trim( readline("Enter new admin password: ") );
39
+		$password = trim(readline("Enter new admin password: "));
40 40
 	}
41 41
 }
42 42
 
43 43
 // validate password
44
-if(strlen($password)<8)										{ $Result->show_cli("Password must be at least 8 characters long", true); }
44
+if (strlen($password) < 8) { $Result->show_cli("Password must be at least 8 characters long", true); }
45 45
 
46 46
 // hash passowrd
47
-$password_crypted = $User->crypt_user_pass ($password);
47
+$password_crypted = $User->crypt_user_pass($password);
48 48
 // save type
49
-$crypt_type = $User->return_crypt_type ();
49
+$crypt_type = $User->return_crypt_type();
50 50
 
51 51
 // set update array
52 52
 $values = array("id"=>1,
@@ -54,8 +54,8 @@  discard block
 block discarded – undo
54 54
 				);
55 55
 
56 56
 // update password
57
-if(!$Admin->object_modify("users", "edit", "id", $values))	{ $Result->show_cli("Failed to update Admin password", false); }
58
-else														{ $Result->show_cli("Admin password updated", false); }
57
+if (!$Admin->object_modify("users", "edit", "id", $values)) { $Result->show_cli("Failed to update Admin password", false); }
58
+else { $Result->show_cli("Admin password updated", false); }
59 59
 
60 60
 // debug ?
61 61
 if ($debugging) {
@@ -69,11 +69,11 @@  discard block
 block discarded – undo
69 69
 if ($disable_email_notification) { die(); }
70 70
 
71 71
 # check for recipients
72
-foreach($Admin->fetch_multiple_objects ("users", "role", "Administrator") as $admin) {
72
+foreach ($Admin->fetch_multiple_objects("users", "role", "Administrator") as $admin) {
73 73
 	$recepients[] = array("name"=>$admin->real_name, "email"=>$admin->email);
74 74
 }
75 75
 # none?
76
-if(!isset($recepients))	{ die(); }
76
+if (!isset($recepients)) { die(); }
77 77
 
78 78
 // fetch settings
79 79
 $settings = $Admin->fetch_object("settings", "id", 1);
@@ -86,7 +86,7 @@  discard block
 block discarded – undo
86 86
 	$phpipam_mail = new phpipam_mail($settings, $mail_settings);
87 87
 
88 88
 	// set subject
89
-	$subject	= "phpIPAM Administrator password updated";
89
+	$subject = "phpIPAM Administrator password updated";
90 90
 	//html
91 91
 	$content[] = "<h3>phpIPAM Administrator password updated</h3>";
92 92
 	$content[] = "<hr>";
@@ -97,12 +97,12 @@  discard block
 block discarded – undo
97 97
 
98 98
 
99 99
 	# set content
100
-	$content 		= $phpipam_mail->generate_message (implode("\r\n", $content));
101
-	$content_plain 	= implode("\r\n",$content_plain);
100
+	$content = $phpipam_mail->generate_message(implode("\r\n", $content));
101
+	$content_plain = implode("\r\n", $content_plain);
102 102
 
103 103
 	$phpipam_mail->Php_mailer->setFrom($mail_settings->mAdminMail, $mail_settings->mAdminName);
104 104
 	//add all admins to CC
105
-	foreach($recepients as $admin) {
105
+	foreach ($recepients as $admin) {
106 106
 		$phpipam_mail->Php_mailer->addAddress(addslashes($admin['email']), addslashes($admin['name']));
107 107
 	}
108 108
 	$phpipam_mail->Php_mailer->Subject = $subject;
Please login to merge, or discard this patch.
functions/scripts/discoveryCheck.php 2 patches
Indentation   +187 added lines, -187 removed lines patch added patch discarded remove patch
@@ -46,7 +46,7 @@  discard block
 block discarded – undo
46 46
 $statuses = explode(";", $Scan->settings->pingStatus);
47 47
 // set mail override flag
48 48
 if(!isset($config['discovery_check_send_mail'])) {
49
-	$config['discovery_check_send_mail'] = true;
49
+    $config['discovery_check_send_mail'] = true;
50 50
 }
51 51
 
52 52
 // set now for whole script
@@ -80,22 +80,22 @@  discard block
 block discarded – undo
80 80
     $addresses_tmp = array();
81 81
     // loop
82 82
     foreach($scan_subnets as $i => $s) {
83
-    	// if subnet has slaves dont check it
84
-    	if ($Subnets->has_slaves ($s->id) === false) {
85
-    		$addresses_tmp[$s->id] = $Scan-> prepare_addresses_to_scan ("discovery", $s->id, false);
86
-			// save discovery time
87
-			$Scan->update_subnet_discoverytime ($s->id, $nowdate);
83
+        // if subnet has slaves dont check it
84
+        if ($Subnets->has_slaves ($s->id) === false) {
85
+            $addresses_tmp[$s->id] = $Scan-> prepare_addresses_to_scan ("discovery", $s->id, false);
86
+            // save discovery time
87
+            $Scan->update_subnet_discoverytime ($s->id, $nowdate);
88 88
         } else {
89 89
             unset( $scan_subnets[$i] );
90
-    	}
90
+        }
91 91
     }
92 92
 
93 93
     //reindex
94 94
     if(sizeof($addresses_tmp)>0) {
95 95
         foreach($addresses_tmp as $s_id=>$a) {
96
-        	foreach($a as $ip) {
97
-        		$addresses[] = array("subnetId"=>$s_id, "ip_addr"=>$ip);
98
-        	}
96
+            foreach($a as $ip) {
97
+                $addresses[] = array("subnetId"=>$s_id, "ip_addr"=>$ip);
98
+            }
99 99
         }
100 100
     }
101 101
 }
@@ -118,101 +118,101 @@  discard block
 block discarded – undo
118 118
 
119 119
 //different scan for fping
120 120
 if($Scan->icmp_type=="fping") {
121
-	//run per MAX_THREADS
122
-	for ($m=0; $m<=$size_subnets; $m += $Scan->settings->scanMaxThreads) {
123
-	    // create threads
124
-	    $threads = array();
125
-	    //fork processes
126
-	    for ($i = 0; $i <= $Scan->settings->scanMaxThreads && $i <= $size_subnets; $i++) {
127
-	    	//only if index exists!
128
-	    	if(isset($scan_subnets[$z])) {
129
-				//start new thread
130
-	            $threads[$z] = new PingThread( 'fping_subnet' );
131
-				$threads[$z]->start_fping( $Subnets->transform_to_dotted($scan_subnets[$z]->subnet)."/".$scan_subnets[$z]->mask );
132
-	            $z++;				//next index
133
-			}
134
-	    }
135
-	    // wait for all the threads to finish
136
-	    while( !empty( $threads ) ) {
137
-			foreach($threads as $index => $thread) {
138
-				$child_pipe = "/tmp/pipe_".$thread->getPid();
139
-
140
-				if (file_exists($child_pipe)) {
141
-					$file_descriptor = fopen( $child_pipe, "r");
142
-					$child_response = "";
143
-					while (!feof($file_descriptor)) {
144
-						$child_response .= fread($file_descriptor, 8192);
145
-					}
146
-					//we have the child data in the parent, but serialized:
147
-					$child_response = unserialize( $child_response );
148
-					//store
149
-					$scan_subnets[$index]->discovered = $child_response;
150
-					//now, child is dead, and parent close the pipe
151
-					unlink( $child_pipe );
152
-					unset($threads[$index]);
153
-				}
154
-			}
155
-	        usleep(200000);
156
-	    }
157
-	}
158
-
159
-	//fping finds all subnet addresses, we must remove existing ones !
160
-	foreach($scan_subnets as $sk=>$s) {
161
-    	if(isset($s->discovered)) {
162
-    		foreach($s->discovered as $rk=>$result) {
163
-    			if(!in_array($Subnets->transform_to_decimal($result), $addresses_tmp[$s->id])) {
164
-    				unset($scan_subnets[$sk]->discovered[$rk]);
165
-    			}
166
-    		}
121
+    //run per MAX_THREADS
122
+    for ($m=0; $m<=$size_subnets; $m += $Scan->settings->scanMaxThreads) {
123
+        // create threads
124
+        $threads = array();
125
+        //fork processes
126
+        for ($i = 0; $i <= $Scan->settings->scanMaxThreads && $i <= $size_subnets; $i++) {
127
+            //only if index exists!
128
+            if(isset($scan_subnets[$z])) {
129
+                //start new thread
130
+                $threads[$z] = new PingThread( 'fping_subnet' );
131
+                $threads[$z]->start_fping( $Subnets->transform_to_dotted($scan_subnets[$z]->subnet)."/".$scan_subnets[$z]->mask );
132
+                $z++;				//next index
133
+            }
134
+        }
135
+        // wait for all the threads to finish
136
+        while( !empty( $threads ) ) {
137
+            foreach($threads as $index => $thread) {
138
+                $child_pipe = "/tmp/pipe_".$thread->getPid();
139
+
140
+                if (file_exists($child_pipe)) {
141
+                    $file_descriptor = fopen( $child_pipe, "r");
142
+                    $child_response = "";
143
+                    while (!feof($file_descriptor)) {
144
+                        $child_response .= fread($file_descriptor, 8192);
145
+                    }
146
+                    //we have the child data in the parent, but serialized:
147
+                    $child_response = unserialize( $child_response );
148
+                    //store
149
+                    $scan_subnets[$index]->discovered = $child_response;
150
+                    //now, child is dead, and parent close the pipe
151
+                    unlink( $child_pipe );
152
+                    unset($threads[$index]);
153
+                }
154
+            }
155
+            usleep(200000);
156
+        }
157
+    }
158
+
159
+    //fping finds all subnet addresses, we must remove existing ones !
160
+    foreach($scan_subnets as $sk=>$s) {
161
+        if(isset($s->discovered)) {
162
+            foreach($s->discovered as $rk=>$result) {
163
+                if(!in_array($Subnets->transform_to_decimal($result), $addresses_tmp[$s->id])) {
164
+                    unset($scan_subnets[$sk]->discovered[$rk]);
165
+                }
166
+            }
167 167
             //rekey
168 168
             $scan_subnets[$sk]->discovered = array_values($scan_subnets[$sk]->discovered);
169
-		}
170
-	}
169
+        }
170
+    }
171 171
 }
172 172
 //ping, pear
173 173
 else {
174
-	//run per MAX_THREADS
174
+    //run per MAX_THREADS
175 175
     for ($m=0; $m<=$size_addresses; $m += $Scan->settings->scanMaxThreads) {
176 176
         // create threads
177 177
         $threads = array();
178 178
 
179 179
         //fork processes
180 180
         for ($i = 0; $i <= $Scan->settings->scanMaxThreads && $i <= $size_addresses; $i++) {
181
-        	//only if index exists!
182
-        	if(isset($addresses[$z])) {
183
-				//start new thread
184
-	            $threads[$z] = new PingThread( 'ping_address' );
185
-	            $threads[$z]->start( $Subnets->transform_to_dotted($addresses[$z]['ip_addr']) );
186
-				$z++;			//next index
187
-			}
181
+            //only if index exists!
182
+            if(isset($addresses[$z])) {
183
+                //start new thread
184
+                $threads[$z] = new PingThread( 'ping_address' );
185
+                $threads[$z]->start( $Subnets->transform_to_dotted($addresses[$z]['ip_addr']) );
186
+                $z++;			//next index
187
+            }
188 188
         }
189 189
 
190 190
         // wait for all the threads to finish
191 191
         while( !empty( $threads ) ) {
192 192
             foreach( $threads as $index => $thread ) {
193 193
                 if( ! $thread->isAlive() ) {
194
-					//unset dead hosts
195
-					if($thread->getExitCode() != 0) {
196
-						unset($addresses[$index]);
197
-					}
194
+                    //unset dead hosts
195
+                    if($thread->getExitCode() != 0) {
196
+                        unset($addresses[$index]);
197
+                    }
198 198
                     //remove thread
199 199
                     unset( $threads[$index]);
200 200
                 }
201 201
             }
202 202
             usleep(200000);
203 203
         }
204
-	}
205
-
206
-	//ok, we have all available addresses, rekey them
207
-	foreach($addresses as $a) {
208
-		$add_tmp[$a['subnetId']][] = $Subnets->transform_to_dotted($a['ip_addr']);
209
-	}
210
-	//add to scan_subnets as result
211
-	foreach($scan_subnets as $sk=>$s) {
212
-		if(isset($add_tmp[$s->id])) {
213
-			$scan_subnets[$sk]->discovered = $add_tmp[$s->id];
214
-		}
215
-	}
204
+    }
205
+
206
+    //ok, we have all available addresses, rekey them
207
+    foreach($addresses as $a) {
208
+        $add_tmp[$a['subnetId']][] = $Subnets->transform_to_dotted($a['ip_addr']);
209
+    }
210
+    //add to scan_subnets as result
211
+    foreach($scan_subnets as $sk=>$s) {
212
+        if(isset($add_tmp[$s->id])) {
213
+            $scan_subnets[$sk]->discovered = $add_tmp[$s->id];
214
+        }
215
+    }
216 216
 }
217 217
 
218 218
 
@@ -234,34 +234,34 @@  discard block
 block discarded – undo
234 234
 $discovered = 0;				//for mailing
235 235
 
236 236
 foreach($scan_subnets as $s) {
237
-	if(isset($s->discovered)) {
238
-		foreach($s->discovered as $ip) {
239
-			// fetch subnet
240
-			$subnet = $Subnets->fetch_subnet ("id", $s->id);
241
-			$nsid = $subnet===false ? false : $subnet->nameserverId;
242
-			// try to resolve hostname
243
-			$hostname = $DNS->resolve_address ($ip, false, true, $nsid);
244
-			// save to hostnames
245
-			$hostnames[$ip] = $hostname['name']==$ip ? "" : $hostname['name'];
246
-
247
-			//set update query
248
-			$values = array(
249
-							"subnetId"    =>$s->id,
250
-							"ip_addr"     =>$ip,
251
-							"hostname"    =>$hostname['name'],
252
-							"description" =>"-- autodiscovered --",
253
-							"note"        =>"This host was autodiscovered on ".$nowdate,
254
-							"lastSeen"    =>$nowdate,
255
-							"state"       =>"2",
256
-							"action"      =>"add"
257
-							);
258
-			//insert
259
-			$Addresses->modify_address($values);
260
-
261
-			//set discovered
262
-			$discovered++;
263
-		}
264
-	}
237
+    if(isset($s->discovered)) {
238
+        foreach($s->discovered as $ip) {
239
+            // fetch subnet
240
+            $subnet = $Subnets->fetch_subnet ("id", $s->id);
241
+            $nsid = $subnet===false ? false : $subnet->nameserverId;
242
+            // try to resolve hostname
243
+            $hostname = $DNS->resolve_address ($ip, false, true, $nsid);
244
+            // save to hostnames
245
+            $hostnames[$ip] = $hostname['name']==$ip ? "" : $hostname['name'];
246
+
247
+            //set update query
248
+            $values = array(
249
+                            "subnetId"    =>$s->id,
250
+                            "ip_addr"     =>$ip,
251
+                            "hostname"    =>$hostname['name'],
252
+                            "description" =>"-- autodiscovered --",
253
+                            "note"        =>"This host was autodiscovered on ".$nowdate,
254
+                            "lastSeen"    =>$nowdate,
255
+                            "state"       =>"2",
256
+                            "action"      =>"add"
257
+                            );
258
+            //insert
259
+            $Addresses->modify_address($values);
260
+
261
+            //set discovered
262
+            $discovered++;
263
+        }
264
+    }
265 265
 }
266 266
 
267 267
 # update scan time
@@ -272,81 +272,81 @@  discard block
 block discarded – undo
272 272
 # send mail
273 273
 if($discovered>0 && $config['discovery_check_send_mail']) {
274 274
 
275
-	# check for recipients
276
-	foreach($Admin->fetch_multiple_objects ("users", "role", "Administrator") as $admin) {
277
-		if($admin->mailNotify=="Yes") {
278
-			$recepients[] = array("name"=>$admin->real_name, "email"=>$admin->email);
279
-		}
280
-	}
281
-	# none?
282
-	if(!isset($recepients))	{ die(); }
283
-
284
-	# fake user object, needed for create_link
285
-	$User = new StdClass();
286
-	@$User->settings->prettyLinks = $Scan->settings->prettyLinks;
287
-
288
-	# try to send
289
-	try {
290
-		# fetch mailer settings
291
-		$mail_settings = $Admin->fetch_object("settingsMail", "id", 1);
292
-		# initialize mailer
293
-		$phpipam_mail = new phpipam_mail($Scan->settings, $mail_settings);
294
-
295
-		// set subject
296
-		$subject	= "phpIPAM new addresses detected ".date("Y-m-d H:i:s");
297
-
298
-		//html
299
-		$content[] = "<h3>phpIPAM found $discovered new hosts</h3>";
300
-		$content[] = "<table style='margin-left:10px;margin-top:5px;width:auto;padding:0px;border-collapse:collapse;border:1px solid gray;'>";
301
-		$content[] = "<tr>";
302
-		$content[] = "	<th style='padding:3px 8px;border:1px solid silver;border-bottom:2px solid gray;'>IP</th>";
303
-		$content[] = "	<th style='padding:3px 8px;border:1px solid silver;border-bottom:2px solid gray;'>Hostname</th>";
304
-		$content[] = "	<th style='padding:3px 8px;border:1px solid silver;border-bottom:2px solid gray;'>Subnet</th>";
305
-		$content[] = "	<th style='padding:3px 8px;border:1px solid silver;border-bottom:2px solid gray;'>Section</th>";
306
-		$content[] = "</tr>";
307
-		//plain
308
-		$content_plain[] = "phpIPAM found $discovered new hosts\r\n------------------------------";
309
-		//Changes
310
-		foreach($scan_subnets as $s) {
311
-			if(sizeof(@$s->discovered)>0) {
312
-				foreach($s->discovered as $ip) {
313
-					//set subnet
314
-					$subnet 	 = $Subnets->fetch_subnet(null, $s->id);
315
-					//set section
316
-					$section 	 = $Admin->fetch_object("sections", "id", $s->sectionId);
317
-
318
-					$content[] = "<tr>";
319
-					$content[] = "	<td style='padding:3px 8px;border:1px solid silver;'>$ip</td>";
320
-					$content[] = "	<td style='padding:3px 8px;border:1px solid silver;'>".$hostnames[$ip]."</td>";
321
-					$content[] = "	<td style='padding:3px 8px;border:1px solid silver;'><a href='".rtrim($Scan->settings->siteURL, "/")."".create_link("subnets",$section->id,$subnet->id)."'>".$Subnets->transform_to_dotted($subnet->subnet)."/".$subnet->mask." - ".$subnet->description."</a></td>";
322
-					$content[] = "	<td style='padding:3px 8px;border:1px solid silver;'><a href='".rtrim($Scan->settings->siteURL, "/")."".create_link("subnets",$section->id)."'>$section->name $section->description</a></td>";
323
-					$content[] = "</tr>";
324
-
325
-					//plain content
326
-					$content_plain[] = "\t * $ip (".$Subnets->transform_to_dotted($subnet->subnet)."/".$subnet->mask.")";
327
-				}
328
-			}
329
-		}
330
-		$content[] = "</table>";
331
-
332
-
333
-		# set content
334
-		$content 		= $phpipam_mail->generate_message (implode("\r\n", $content));
335
-		$content_plain 	= implode("\r\n",$content_plain);
336
-
337
-		$phpipam_mail->Php_mailer->setFrom($mail_settings->mAdminMail, $mail_settings->mAdminName);
338
-		//add all admins to CC
339
-		foreach($recepients as $admin) {
340
-			$phpipam_mail->Php_mailer->addAddress(addslashes($admin['email']), addslashes($admin['name']));
341
-		}
342
-		$phpipam_mail->Php_mailer->Subject = $subject;
343
-		$phpipam_mail->Php_mailer->msgHTML($content);
344
-		$phpipam_mail->Php_mailer->AltBody = $content_plain;
345
-		//send
346
-		$phpipam_mail->Php_mailer->send();
347
-	} catch (phpmailerException $e) {
348
-		$Result->show_cli("Mailer Error: ".$e->errorMessage(), true);
349
-	} catch (Exception $e) {
350
-		$Result->show_cli("Mailer Error: ".$e->getMessage(), true);
351
-	}
275
+    # check for recipients
276
+    foreach($Admin->fetch_multiple_objects ("users", "role", "Administrator") as $admin) {
277
+        if($admin->mailNotify=="Yes") {
278
+            $recepients[] = array("name"=>$admin->real_name, "email"=>$admin->email);
279
+        }
280
+    }
281
+    # none?
282
+    if(!isset($recepients))	{ die(); }
283
+
284
+    # fake user object, needed for create_link
285
+    $User = new StdClass();
286
+    @$User->settings->prettyLinks = $Scan->settings->prettyLinks;
287
+
288
+    # try to send
289
+    try {
290
+        # fetch mailer settings
291
+        $mail_settings = $Admin->fetch_object("settingsMail", "id", 1);
292
+        # initialize mailer
293
+        $phpipam_mail = new phpipam_mail($Scan->settings, $mail_settings);
294
+
295
+        // set subject
296
+        $subject	= "phpIPAM new addresses detected ".date("Y-m-d H:i:s");
297
+
298
+        //html
299
+        $content[] = "<h3>phpIPAM found $discovered new hosts</h3>";
300
+        $content[] = "<table style='margin-left:10px;margin-top:5px;width:auto;padding:0px;border-collapse:collapse;border:1px solid gray;'>";
301
+        $content[] = "<tr>";
302
+        $content[] = "	<th style='padding:3px 8px;border:1px solid silver;border-bottom:2px solid gray;'>IP</th>";
303
+        $content[] = "	<th style='padding:3px 8px;border:1px solid silver;border-bottom:2px solid gray;'>Hostname</th>";
304
+        $content[] = "	<th style='padding:3px 8px;border:1px solid silver;border-bottom:2px solid gray;'>Subnet</th>";
305
+        $content[] = "	<th style='padding:3px 8px;border:1px solid silver;border-bottom:2px solid gray;'>Section</th>";
306
+        $content[] = "</tr>";
307
+        //plain
308
+        $content_plain[] = "phpIPAM found $discovered new hosts\r\n------------------------------";
309
+        //Changes
310
+        foreach($scan_subnets as $s) {
311
+            if(sizeof(@$s->discovered)>0) {
312
+                foreach($s->discovered as $ip) {
313
+                    //set subnet
314
+                    $subnet 	 = $Subnets->fetch_subnet(null, $s->id);
315
+                    //set section
316
+                    $section 	 = $Admin->fetch_object("sections", "id", $s->sectionId);
317
+
318
+                    $content[] = "<tr>";
319
+                    $content[] = "	<td style='padding:3px 8px;border:1px solid silver;'>$ip</td>";
320
+                    $content[] = "	<td style='padding:3px 8px;border:1px solid silver;'>".$hostnames[$ip]."</td>";
321
+                    $content[] = "	<td style='padding:3px 8px;border:1px solid silver;'><a href='".rtrim($Scan->settings->siteURL, "/")."".create_link("subnets",$section->id,$subnet->id)."'>".$Subnets->transform_to_dotted($subnet->subnet)."/".$subnet->mask." - ".$subnet->description."</a></td>";
322
+                    $content[] = "	<td style='padding:3px 8px;border:1px solid silver;'><a href='".rtrim($Scan->settings->siteURL, "/")."".create_link("subnets",$section->id)."'>$section->name $section->description</a></td>";
323
+                    $content[] = "</tr>";
324
+
325
+                    //plain content
326
+                    $content_plain[] = "\t * $ip (".$Subnets->transform_to_dotted($subnet->subnet)."/".$subnet->mask.")";
327
+                }
328
+            }
329
+        }
330
+        $content[] = "</table>";
331
+
332
+
333
+        # set content
334
+        $content 		= $phpipam_mail->generate_message (implode("\r\n", $content));
335
+        $content_plain 	= implode("\r\n",$content_plain);
336
+
337
+        $phpipam_mail->Php_mailer->setFrom($mail_settings->mAdminMail, $mail_settings->mAdminName);
338
+        //add all admins to CC
339
+        foreach($recepients as $admin) {
340
+            $phpipam_mail->Php_mailer->addAddress(addslashes($admin['email']), addslashes($admin['name']));
341
+        }
342
+        $phpipam_mail->Php_mailer->Subject = $subject;
343
+        $phpipam_mail->Php_mailer->msgHTML($content);
344
+        $phpipam_mail->Php_mailer->AltBody = $content_plain;
345
+        //send
346
+        $phpipam_mail->Php_mailer->send();
347
+    } catch (phpmailerException $e) {
348
+        $Result->show_cli("Mailer Error: ".$e->errorMessage(), true);
349
+    } catch (Exception $e) {
350
+        $Result->show_cli("Mailer Error: ".$e->getMessage(), true);
351
+    }
352 352
 }
353 353
\ No newline at end of file
Please login to merge, or discard this patch.
Spacing   +91 added lines, -91 removed lines patch added patch discarded remove patch
@@ -23,77 +23,77 @@  discard block
 block discarded – undo
23 23
  */
24 24
 
25 25
 # include required scripts
26
-require_once( dirname(__FILE__) . '/../functions.php' );
27
-require( dirname(__FILE__) . '/../../functions/classes/class.Thread.php');
26
+require_once(dirname(__FILE__).'/../functions.php');
27
+require(dirname(__FILE__).'/../../functions/classes/class.Thread.php');
28 28
 
29 29
 # initialize objects
30 30
 $Database 	= new Database_PDO;
31
-$Subnets	= new Subnets ($Database);
32
-$Addresses	= new Addresses ($Database);
33
-$Tools		= new Tools ($Database);
34
-$Scan		= new Scan ($Database);
35
-$DNS		= new DNS ($Database);
36
-$Result		= new Result();
31
+$Subnets = new Subnets($Database);
32
+$Addresses	= new Addresses($Database);
33
+$Tools = new Tools($Database);
34
+$Scan = new Scan($Database);
35
+$DNS = new DNS($Database);
36
+$Result = new Result();
37 37
 
38 38
 // set exit flag to true
39 39
 $Scan->ping_set_exit(true);
40 40
 // set debugging
41 41
 $Scan->reset_debugging(false);
42 42
 // change scan type?
43
-if(@$config['discovery_check_method'])
44
-$Scan->reset_scan_method ($config['discovery_check_method']);
43
+if (@$config['discovery_check_method'])
44
+$Scan->reset_scan_method($config['discovery_check_method']);
45 45
 // set ping statuses
46 46
 $statuses = explode(";", $Scan->settings->pingStatus);
47 47
 // set mail override flag
48
-if(!isset($config['discovery_check_send_mail'])) {
48
+if (!isset($config['discovery_check_send_mail'])) {
49 49
 	$config['discovery_check_send_mail'] = true;
50 50
 }
51 51
 
52 52
 // set now for whole script
53 53
 $now     = time();
54
-$nowdate = date ("Y-m-d H:i:s");
54
+$nowdate = date("Y-m-d H:i:s");
55 55
 
56 56
 // response for mailing
57
-$address_change = array();			// Array with differences, can be used to email to admins
58
-$hostnames      = array();			// Array with detected hostnames
57
+$address_change = array(); // Array with differences, can be used to email to admins
58
+$hostnames      = array(); // Array with detected hostnames
59 59
 
60 60
 
61 61
 // script can only be run from cli
62
-if(php_sapi_name()!="cli") 						{ die("This script can only be run from cli!"); }
62
+if (php_sapi_name() != "cli") { die("This script can only be run from cli!"); }
63 63
 // test to see if threading is available
64
-if(!PingThread::available()) 						{ die("Threading is required for scanning subnets. Please recompile PHP with pcntl extension"); }
64
+if (!PingThread::available()) { die("Threading is required for scanning subnets. Please recompile PHP with pcntl extension"); }
65 65
 // verify ping path
66
-if ($Scan->icmp_type=="ping") {
67
-if(!file_exists($Scan->settings->scanPingPath)) { die("Invalid ping path!"); }
66
+if ($Scan->icmp_type == "ping") {
67
+if (!file_exists($Scan->settings->scanPingPath)) { die("Invalid ping path!"); }
68 68
 }
69 69
 // verify fping path
70
-if ($Scan->icmp_type=="fping") {
71
-if(!file_exists($Scan->settings->scanFPingPath)){ die("Invalid fping path!"); }
70
+if ($Scan->icmp_type == "fping") {
71
+if (!file_exists($Scan->settings->scanFPingPath)) { die("Invalid fping path!"); }
72 72
 }
73 73
 
74 74
 
75 75
 //first fetch all subnets to be scanned
76
-$scan_subnets = $Subnets->fetch_all_subnets_for_discoveryCheck (1);
76
+$scan_subnets = $Subnets->fetch_all_subnets_for_discoveryCheck(1);
77 77
 //set addresses
78
-if ($scan_subnets!==false) {
78
+if ($scan_subnets !== false) {
79 79
     // initial array
80 80
     $addresses_tmp = array();
81 81
     // loop
82
-    foreach($scan_subnets as $i => $s) {
82
+    foreach ($scan_subnets as $i => $s) {
83 83
     	// if subnet has slaves dont check it
84
-    	if ($Subnets->has_slaves ($s->id) === false) {
85
-    		$addresses_tmp[$s->id] = $Scan-> prepare_addresses_to_scan ("discovery", $s->id, false);
84
+    	if ($Subnets->has_slaves($s->id) === false) {
85
+    		$addresses_tmp[$s->id] = $Scan-> prepare_addresses_to_scan("discovery", $s->id, false);
86 86
 			// save discovery time
87
-			$Scan->update_subnet_discoverytime ($s->id, $nowdate);
87
+			$Scan->update_subnet_discoverytime($s->id, $nowdate);
88 88
         } else {
89
-            unset( $scan_subnets[$i] );
89
+            unset($scan_subnets[$i]);
90 90
     	}
91 91
     }
92 92
 
93 93
     //reindex
94
-    if(sizeof($addresses_tmp)>0) {
95
-        foreach($addresses_tmp as $s_id=>$a) {
96
-        	foreach($a as $ip) {
94
+    if (sizeof($addresses_tmp) > 0) {
95
+        foreach ($addresses_tmp as $s_id=>$a) {
96
+        	foreach ($a as $ip) {
97 97
         		$addresses[] = array("subnetId"=>$s_id, "ip_addr"=>$ip);
98 98
         	}
99 99
         }
@@ -101,15 +101,15 @@  discard block
 block discarded – undo
101 101
 }
102 102
 
103 103
 
104
-if($Scan->debugging)							{ print_r($scan_subnets); }
105
-if($scan_subnets===false || !count($scan_subnets)) { die("No subnets are marked for new hosts checking\n"); }
104
+if ($Scan->debugging) { print_r($scan_subnets); }
105
+if ($scan_subnets === false || !count($scan_subnets)) { die("No subnets are marked for new hosts checking\n"); }
106 106
 
107 107
 
108 108
 //scan
109
-if($Scan->debugging)							{ print "Using $Scan->icmp_type\n--------------------\n\n"; }
109
+if ($Scan->debugging) { print "Using $Scan->icmp_type\n--------------------\n\n"; }
110 110
 
111 111
 
112
-$z = 0;			//addresses array index
112
+$z = 0; //addresses array index
113 113
 
114 114
 // let's just reindex the subnets array to save future issues
115 115
 $scan_subnets   = array_values($scan_subnets);
@@ -117,38 +117,38 @@  discard block
 block discarded – undo
117 117
 $size_addresses = max(array_keys($addresses));
118 118
 
119 119
 //different scan for fping
120
-if($Scan->icmp_type=="fping") {
120
+if ($Scan->icmp_type == "fping") {
121 121
 	//run per MAX_THREADS
122
-	for ($m=0; $m<=$size_subnets; $m += $Scan->settings->scanMaxThreads) {
122
+	for ($m = 0; $m <= $size_subnets; $m += $Scan->settings->scanMaxThreads) {
123 123
 	    // create threads
124 124
 	    $threads = array();
125 125
 	    //fork processes
126 126
 	    for ($i = 0; $i <= $Scan->settings->scanMaxThreads && $i <= $size_subnets; $i++) {
127 127
 	    	//only if index exists!
128
-	    	if(isset($scan_subnets[$z])) {
128
+	    	if (isset($scan_subnets[$z])) {
129 129
 				//start new thread
130
-	            $threads[$z] = new PingThread( 'fping_subnet' );
131
-				$threads[$z]->start_fping( $Subnets->transform_to_dotted($scan_subnets[$z]->subnet)."/".$scan_subnets[$z]->mask );
132
-	            $z++;				//next index
130
+	            $threads[$z] = new PingThread('fping_subnet');
131
+				$threads[$z]->start_fping($Subnets->transform_to_dotted($scan_subnets[$z]->subnet)."/".$scan_subnets[$z]->mask);
132
+	            $z++; //next index
133 133
 			}
134 134
 	    }
135 135
 	    // wait for all the threads to finish
136
-	    while( !empty( $threads ) ) {
137
-			foreach($threads as $index => $thread) {
136
+	    while (!empty($threads)) {
137
+			foreach ($threads as $index => $thread) {
138 138
 				$child_pipe = "/tmp/pipe_".$thread->getPid();
139 139
 
140 140
 				if (file_exists($child_pipe)) {
141
-					$file_descriptor = fopen( $child_pipe, "r");
141
+					$file_descriptor = fopen($child_pipe, "r");
142 142
 					$child_response = "";
143 143
 					while (!feof($file_descriptor)) {
144 144
 						$child_response .= fread($file_descriptor, 8192);
145 145
 					}
146 146
 					//we have the child data in the parent, but serialized:
147
-					$child_response = unserialize( $child_response );
147
+					$child_response = unserialize($child_response);
148 148
 					//store
149 149
 					$scan_subnets[$index]->discovered = $child_response;
150 150
 					//now, child is dead, and parent close the pipe
151
-					unlink( $child_pipe );
151
+					unlink($child_pipe);
152 152
 					unset($threads[$index]);
153 153
 				}
154 154
 			}
@@ -157,10 +157,10 @@  discard block
 block discarded – undo
157 157
 	}
158 158
 
159 159
 	//fping finds all subnet addresses, we must remove existing ones !
160
-	foreach($scan_subnets as $sk=>$s) {
161
-    	if(isset($s->discovered)) {
162
-    		foreach($s->discovered as $rk=>$result) {
163
-    			if(!in_array($Subnets->transform_to_decimal($result), $addresses_tmp[$s->id])) {
160
+	foreach ($scan_subnets as $sk=>$s) {
161
+    	if (isset($s->discovered)) {
162
+    		foreach ($s->discovered as $rk=>$result) {
163
+    			if (!in_array($Subnets->transform_to_decimal($result), $addresses_tmp[$s->id])) {
164 164
     				unset($scan_subnets[$sk]->discovered[$rk]);
165 165
     			}
166 166
     		}
@@ -172,31 +172,31 @@  discard block
 block discarded – undo
172 172
 //ping, pear
173 173
 else {
174 174
 	//run per MAX_THREADS
175
-    for ($m=0; $m<=$size_addresses; $m += $Scan->settings->scanMaxThreads) {
175
+    for ($m = 0; $m <= $size_addresses; $m += $Scan->settings->scanMaxThreads) {
176 176
         // create threads
177 177
         $threads = array();
178 178
 
179 179
         //fork processes
180 180
         for ($i = 0; $i <= $Scan->settings->scanMaxThreads && $i <= $size_addresses; $i++) {
181 181
         	//only if index exists!
182
-        	if(isset($addresses[$z])) {
182
+        	if (isset($addresses[$z])) {
183 183
 				//start new thread
184
-	            $threads[$z] = new PingThread( 'ping_address' );
185
-	            $threads[$z]->start( $Subnets->transform_to_dotted($addresses[$z]['ip_addr']) );
186
-				$z++;			//next index
184
+	            $threads[$z] = new PingThread('ping_address');
185
+	            $threads[$z]->start($Subnets->transform_to_dotted($addresses[$z]['ip_addr']));
186
+				$z++; //next index
187 187
 			}
188 188
         }
189 189
 
190 190
         // wait for all the threads to finish
191
-        while( !empty( $threads ) ) {
192
-            foreach( $threads as $index => $thread ) {
193
-                if( ! $thread->isAlive() ) {
191
+        while (!empty($threads)) {
192
+            foreach ($threads as $index => $thread) {
193
+                if (!$thread->isAlive()) {
194 194
 					//unset dead hosts
195
-					if($thread->getExitCode() != 0) {
195
+					if ($thread->getExitCode() != 0) {
196 196
 						unset($addresses[$index]);
197 197
 					}
198 198
                     //remove thread
199
-                    unset( $threads[$index]);
199
+                    unset($threads[$index]);
200 200
                 }
201 201
             }
202 202
             usleep(200000);
@@ -204,12 +204,12 @@  discard block
 block discarded – undo
204 204
 	}
205 205
 
206 206
 	//ok, we have all available addresses, rekey them
207
-	foreach($addresses as $a) {
207
+	foreach ($addresses as $a) {
208 208
 		$add_tmp[$a['subnetId']][] = $Subnets->transform_to_dotted($a['ip_addr']);
209 209
 	}
210 210
 	//add to scan_subnets as result
211
-	foreach($scan_subnets as $sk=>$s) {
212
-		if(isset($add_tmp[$s->id])) {
211
+	foreach ($scan_subnets as $sk=>$s) {
212
+		if (isset($add_tmp[$s->id])) {
213 213
 			$scan_subnets[$sk]->discovered = $add_tmp[$s->id];
214 214
 		}
215 215
 	}
@@ -217,32 +217,32 @@  discard block
 block discarded – undo
217 217
 
218 218
 
219 219
 # print change
220
-if($Scan->debugging)							{ "\nDiscovered addresses:\n----------\n"; print_r($scan_subnets); }
220
+if ($Scan->debugging) { "\nDiscovered addresses:\n----------\n"; print_r($scan_subnets); }
221 221
 
222 222
 
223 223
 
224 224
 # reinitialize objects
225 225
 $Database 	= new Database_PDO;
226
-$Admin		= new Admin ($Database, false);
227
-$Addresses	= new Addresses ($Database);
228
-$Subnets	= new Subnets ($Database);
229
-$DNS		= new DNS ($Database);
230
-$Scan		= new Scan ($Database);
226
+$Admin = new Admin($Database, false);
227
+$Addresses	= new Addresses($Database);
228
+$Subnets	= new Subnets($Database);
229
+$DNS = new DNS($Database);
230
+$Scan = new Scan($Database);
231 231
 $Result		= new Result();
232 232
 
233 233
 # insert to database
234
-$discovered = 0;				//for mailing
234
+$discovered = 0; //for mailing
235 235
 
236
-foreach($scan_subnets as $s) {
237
-	if(isset($s->discovered)) {
238
-		foreach($s->discovered as $ip) {
236
+foreach ($scan_subnets as $s) {
237
+	if (isset($s->discovered)) {
238
+		foreach ($s->discovered as $ip) {
239 239
 			// fetch subnet
240
-			$subnet = $Subnets->fetch_subnet ("id", $s->id);
241
-			$nsid = $subnet===false ? false : $subnet->nameserverId;
240
+			$subnet = $Subnets->fetch_subnet("id", $s->id);
241
+			$nsid = $subnet === false ? false : $subnet->nameserverId;
242 242
 			// try to resolve hostname
243
-			$hostname = $DNS->resolve_address ($ip, false, true, $nsid);
243
+			$hostname = $DNS->resolve_address($ip, false, true, $nsid);
244 244
 			// save to hostnames
245
-			$hostnames[$ip] = $hostname['name']==$ip ? "" : $hostname['name'];
245
+			$hostnames[$ip] = $hostname['name'] == $ip ? "" : $hostname['name'];
246 246
 
247 247
 			//set update query
248 248
 			$values = array(
@@ -265,21 +265,21 @@  discard block
 block discarded – undo
265 265
 }
266 266
 
267 267
 # update scan time
268
-$Scan->ping_update_scanagent_checktime (1, $nowdate);
268
+$Scan->ping_update_scanagent_checktime(1, $nowdate);
269 269
 
270 270
 
271 271
 
272 272
 # send mail
273
-if($discovered>0 && $config['discovery_check_send_mail']) {
273
+if ($discovered > 0 && $config['discovery_check_send_mail']) {
274 274
 
275 275
 	# check for recipients
276
-	foreach($Admin->fetch_multiple_objects ("users", "role", "Administrator") as $admin) {
277
-		if($admin->mailNotify=="Yes") {
276
+	foreach ($Admin->fetch_multiple_objects("users", "role", "Administrator") as $admin) {
277
+		if ($admin->mailNotify == "Yes") {
278 278
 			$recepients[] = array("name"=>$admin->real_name, "email"=>$admin->email);
279 279
 		}
280 280
 	}
281 281
 	# none?
282
-	if(!isset($recepients))	{ die(); }
282
+	if (!isset($recepients)) { die(); }
283 283
 
284 284
 	# fake user object, needed for create_link
285 285
 	$User = new StdClass();
@@ -293,7 +293,7 @@  discard block
 block discarded – undo
293 293
 		$phpipam_mail = new phpipam_mail($Scan->settings, $mail_settings);
294 294
 
295 295
 		// set subject
296
-		$subject	= "phpIPAM new addresses detected ".date("Y-m-d H:i:s");
296
+		$subject = "phpIPAM new addresses detected ".date("Y-m-d H:i:s");
297 297
 
298 298
 		//html
299 299
 		$content[] = "<h3>phpIPAM found $discovered new hosts</h3>";
@@ -307,19 +307,19 @@  discard block
 block discarded – undo
307 307
 		//plain
308 308
 		$content_plain[] = "phpIPAM found $discovered new hosts\r\n------------------------------";
309 309
 		//Changes
310
-		foreach($scan_subnets as $s) {
311
-			if(sizeof(@$s->discovered)>0) {
312
-				foreach($s->discovered as $ip) {
310
+		foreach ($scan_subnets as $s) {
311
+			if (sizeof(@$s->discovered) > 0) {
312
+				foreach ($s->discovered as $ip) {
313 313
 					//set subnet
314
-					$subnet 	 = $Subnets->fetch_subnet(null, $s->id);
314
+					$subnet = $Subnets->fetch_subnet(null, $s->id);
315 315
 					//set section
316 316
 					$section 	 = $Admin->fetch_object("sections", "id", $s->sectionId);
317 317
 
318 318
 					$content[] = "<tr>";
319 319
 					$content[] = "	<td style='padding:3px 8px;border:1px solid silver;'>$ip</td>";
320 320
 					$content[] = "	<td style='padding:3px 8px;border:1px solid silver;'>".$hostnames[$ip]."</td>";
321
-					$content[] = "	<td style='padding:3px 8px;border:1px solid silver;'><a href='".rtrim($Scan->settings->siteURL, "/")."".create_link("subnets",$section->id,$subnet->id)."'>".$Subnets->transform_to_dotted($subnet->subnet)."/".$subnet->mask." - ".$subnet->description."</a></td>";
322
-					$content[] = "	<td style='padding:3px 8px;border:1px solid silver;'><a href='".rtrim($Scan->settings->siteURL, "/")."".create_link("subnets",$section->id)."'>$section->name $section->description</a></td>";
321
+					$content[] = "	<td style='padding:3px 8px;border:1px solid silver;'><a href='".rtrim($Scan->settings->siteURL, "/")."".create_link("subnets", $section->id, $subnet->id)."'>".$Subnets->transform_to_dotted($subnet->subnet)."/".$subnet->mask." - ".$subnet->description."</a></td>";
322
+					$content[] = "	<td style='padding:3px 8px;border:1px solid silver;'><a href='".rtrim($Scan->settings->siteURL, "/")."".create_link("subnets", $section->id)."'>$section->name $section->description</a></td>";
323 323
 					$content[] = "</tr>";
324 324
 
325 325
 					//plain content
@@ -331,12 +331,12 @@  discard block
 block discarded – undo
331 331
 
332 332
 
333 333
 		# set content
334
-		$content 		= $phpipam_mail->generate_message (implode("\r\n", $content));
335
-		$content_plain 	= implode("\r\n",$content_plain);
334
+		$content = $phpipam_mail->generate_message(implode("\r\n", $content));
335
+		$content_plain = implode("\r\n", $content_plain);
336 336
 
337 337
 		$phpipam_mail->Php_mailer->setFrom($mail_settings->mAdminMail, $mail_settings->mAdminName);
338 338
 		//add all admins to CC
339
-		foreach($recepients as $admin) {
339
+		foreach ($recepients as $admin) {
340 340
 			$phpipam_mail->Php_mailer->addAddress(addslashes($admin['email']), addslashes($admin['name']));
341 341
 		}
342 342
 		$phpipam_mail->Php_mailer->Subject = $subject;
Please login to merge, or discard this patch.
functions/scripts/pingCheck.php 3 patches
Indentation   +337 added lines, -337 removed lines patch added patch discarded remove patch
@@ -59,7 +59,7 @@  discard block
 block discarded – undo
59 59
 $statuses = explode(";", $Scan->settings->pingStatus);
60 60
 // set mail override flag
61 61
 if(!isset($config['ping_check_send_mail'])) {
62
-	$config['ping_check_send_mail'] = true;
62
+    $config['ping_check_send_mail'] = true;
63 63
 }
64 64
 
65 65
 // response for mailing
@@ -91,60 +91,60 @@  discard block
 block discarded – undo
91 91
 //fetch all addresses that need to be checked
92 92
 foreach($scan_subnets as $s) {
93 93
 
94
-	// if subnet has slaves dont check it
95
-	if ($Subnets->has_slaves ($s->id) === false) {
96
-
97
-		$subnet_addresses = $Addresses->fetch_subnet_addresses ($s->id);
98
-		//set array for fping
99
-		if($Scan->icmp_type=="fping")	{
100
-			$subnets[] = array(
101
-								"id"         =>$s->id,
102
-								"cidr"       =>$Subnets->transform_to_dotted($s->subnet)."/".$s->mask,
103
-								"nsid"       =>$s->nameserverId,
104
-								"resolveDNS" =>$s->resolveDNS
105
-			                   );
106
-		}
107
-		//save addresses
108
-		if(sizeof($subnet_addresses)>0) {
109
-			foreach($subnet_addresses as $a) {
110
-				//ignore excludePing
111
-				if($a->excludePing!=1) {
112
-					//create different array for fping
113
-					if($Scan->icmp_type=="fping")	{
114
-						$addresses2[$s->id][$a->id] = array(
115
-															"id"          =>$a->id,
116
-															"ip_addr"     =>$a->ip_addr,
117
-															"description" =>$a->description,
118
-															"hostname"    =>$a->hostname,
119
-															"subnetId"    =>$a->subnetId,
120
-															"lastSeenOld" =>$a->lastSeen,
121
-															"lastSeen"    =>$a->lastSeen,
122
-															"state"       =>$a->state,
123
-															"resolveDNS"  =>$s->resolveDNS,
124
-															"nsid"        =>$s->nsid
125
-															);
126
-						$addresses[$s->id][$a->id]  = $a->ip_addr;
127
-					}
128
-					else {
129
-						$addresses[] 		 		= array(
130
-															"id"          =>$a->id,
131
-															"ip_addr"     =>$a->ip_addr,
132
-															"description" =>$a->description,
133
-															"hostname"    =>$a->hostname,
134
-															"subnetId"    =>$a->subnetId,
135
-															"lastSeenOld" =>$a->lastSeen,
136
-															"lastSeen"    =>$a->lastSeen,
137
-															"state"       =>$a->state,
138
-															"resolveDNS"  =>$s->resolveDNS,
139
-															"nsid"        =>$s->nsid
140
-						                          			);
141
-					}
142
-				}
143
-			}
144
-		}
145
-		// save update time
146
-		$Scan->update_subnet_scantime ($s->id, $nowdate);
147
-	}
94
+    // if subnet has slaves dont check it
95
+    if ($Subnets->has_slaves ($s->id) === false) {
96
+
97
+        $subnet_addresses = $Addresses->fetch_subnet_addresses ($s->id);
98
+        //set array for fping
99
+        if($Scan->icmp_type=="fping")	{
100
+            $subnets[] = array(
101
+                                "id"         =>$s->id,
102
+                                "cidr"       =>$Subnets->transform_to_dotted($s->subnet)."/".$s->mask,
103
+                                "nsid"       =>$s->nameserverId,
104
+                                "resolveDNS" =>$s->resolveDNS
105
+                                );
106
+        }
107
+        //save addresses
108
+        if(sizeof($subnet_addresses)>0) {
109
+            foreach($subnet_addresses as $a) {
110
+                //ignore excludePing
111
+                if($a->excludePing!=1) {
112
+                    //create different array for fping
113
+                    if($Scan->icmp_type=="fping")	{
114
+                        $addresses2[$s->id][$a->id] = array(
115
+                                                            "id"          =>$a->id,
116
+                                                            "ip_addr"     =>$a->ip_addr,
117
+                                                            "description" =>$a->description,
118
+                                                            "hostname"    =>$a->hostname,
119
+                                                            "subnetId"    =>$a->subnetId,
120
+                                                            "lastSeenOld" =>$a->lastSeen,
121
+                                                            "lastSeen"    =>$a->lastSeen,
122
+                                                            "state"       =>$a->state,
123
+                                                            "resolveDNS"  =>$s->resolveDNS,
124
+                                                            "nsid"        =>$s->nsid
125
+                                                            );
126
+                        $addresses[$s->id][$a->id]  = $a->ip_addr;
127
+                    }
128
+                    else {
129
+                        $addresses[] 		 		= array(
130
+                                                            "id"          =>$a->id,
131
+                                                            "ip_addr"     =>$a->ip_addr,
132
+                                                            "description" =>$a->description,
133
+                                                            "hostname"    =>$a->hostname,
134
+                                                            "subnetId"    =>$a->subnetId,
135
+                                                            "lastSeenOld" =>$a->lastSeen,
136
+                                                            "lastSeen"    =>$a->lastSeen,
137
+                                                            "state"       =>$a->state,
138
+                                                            "resolveDNS"  =>$s->resolveDNS,
139
+                                                            "nsid"        =>$s->nsid
140
+                                                                );
141
+                    }
142
+                }
143
+            }
144
+        }
145
+        // save update time
146
+        $Scan->update_subnet_scantime ($s->id, $nowdate);
147
+    }
148 148
 }
149 149
 
150 150
 
@@ -159,152 +159,152 @@  discard block
 block discarded – undo
159 159
 
160 160
 //different scan for fping
161 161
 if($Scan->icmp_type=="fping") {
162
-	//run per MAX_THREADS
163
-	for ($m=0; $m<=sizeof($subnets); $m += $Scan->settings->scanMaxThreads) {
164
-	    // create threads
165
-	    $threads = array();
166
-	    //fork processes
167
-	    for ($i = 0; $i <= $Scan->settings->scanMaxThreads && $i <= sizeof($subnets); $i++) {
168
-	    	//only if index exists!
169
-	    	if(isset($subnets[$z])) {
170
-				//start new thread
171
-	            $threads[$z] = new PingThread( 'fping_subnet' );
172
-	            $threads[$z]->start_fping( $subnets[$z]['cidr'] );
173
-	            $z++;				//next index
174
-			}
175
-	    }
176
-	    // wait for all the threads to finish
177
-	    while( !empty( $threads ) ) {
178
-			foreach($threads as $index => $thread) {
179
-				$child_pipe = "/tmp/pipe_".$thread->getPid();
180
-
181
-				if (file_exists($child_pipe)) {
182
-					$file_descriptor = fopen( $child_pipe, "r");
183
-					$child_response = "";
184
-					while (!feof($file_descriptor)) {
185
-						$child_response .= fread($file_descriptor, 8192);
186
-					}
187
-					//we have the child data in the parent, but serialized:
188
-					$child_response = unserialize( $child_response );
189
-					//store
190
-					$subnets[$index]['result'] = $child_response;
191
-
192
-					//now, child is dead, and parent close the pipe
193
-					unlink( $child_pipe );
194
-					unset($threads[$index]);
195
-				}
196
-			}
197
-	        usleep(200000);
198
-	    }
199
-	}
200
-
201
-	//now we must remove all non-existing hosts
202
-	foreach($subnets as $sk=>$s) {
203
-		if(sizeof(@$s['result'])>0 && sizeof($addresses[$s['id']])>0) {
204
-			//loop addresses
205
-			foreach($addresses[$s['id']] as $ak=>$a) {
206
-				//offline host
207
-				if(array_search($Subnets->transform_to_dotted($a), $subnets[$sk]['result'])===false) {
208
-    				// new change = null
209
-    				$addresses2[$s['id']][$ak]['lastSeenNew'] = NULL;
210
-					//save to out array
162
+    //run per MAX_THREADS
163
+    for ($m=0; $m<=sizeof($subnets); $m += $Scan->settings->scanMaxThreads) {
164
+        // create threads
165
+        $threads = array();
166
+        //fork processes
167
+        for ($i = 0; $i <= $Scan->settings->scanMaxThreads && $i <= sizeof($subnets); $i++) {
168
+            //only if index exists!
169
+            if(isset($subnets[$z])) {
170
+                //start new thread
171
+                $threads[$z] = new PingThread( 'fping_subnet' );
172
+                $threads[$z]->start_fping( $subnets[$z]['cidr'] );
173
+                $z++;				//next index
174
+            }
175
+        }
176
+        // wait for all the threads to finish
177
+        while( !empty( $threads ) ) {
178
+            foreach($threads as $index => $thread) {
179
+                $child_pipe = "/tmp/pipe_".$thread->getPid();
180
+
181
+                if (file_exists($child_pipe)) {
182
+                    $file_descriptor = fopen( $child_pipe, "r");
183
+                    $child_response = "";
184
+                    while (!feof($file_descriptor)) {
185
+                        $child_response .= fread($file_descriptor, 8192);
186
+                    }
187
+                    //we have the child data in the parent, but serialized:
188
+                    $child_response = unserialize( $child_response );
189
+                    //store
190
+                    $subnets[$index]['result'] = $child_response;
191
+
192
+                    //now, child is dead, and parent close the pipe
193
+                    unlink( $child_pipe );
194
+                    unset($threads[$index]);
195
+                }
196
+            }
197
+            usleep(200000);
198
+        }
199
+    }
200
+
201
+    //now we must remove all non-existing hosts
202
+    foreach($subnets as $sk=>$s) {
203
+        if(sizeof(@$s['result'])>0 && sizeof($addresses[$s['id']])>0) {
204
+            //loop addresses
205
+            foreach($addresses[$s['id']] as $ak=>$a) {
206
+                //offline host
207
+                if(array_search($Subnets->transform_to_dotted($a), $subnets[$sk]['result'])===false) {
208
+                    // new change = null
209
+                    $addresses2[$s['id']][$ak]['lastSeenNew'] = NULL;
210
+                    //save to out array
211 211
                     $address_change[] = $addresses2[$s['id']][$ak];
212
-				}
213
-				//online host
214
-				else {
215
-    				// new change = now
216
-    				$addresses2[$s['id']][$ak]['lastSeenNew'] = $nowdate;
217
-					//save to out array
212
+                }
213
+                //online host
214
+                else {
215
+                    // new change = now
216
+                    $addresses2[$s['id']][$ak]['lastSeenNew'] = $nowdate;
217
+                    //save to out array
218 218
                     $address_change[] = $addresses2[$s['id']][$ak];
219 219
                     //update status
220 220
                     $Scan->ping_update_lastseen ($addresses2[$s['id']][$ak]['id'], $nowdate);
221
-				}
222
-
223
-		        //resolve hostnames
224
-				if($subnets[$sk]['resolveDNS']=="1") {
225
-					$old_hostname_save = $addresses2[$s['id']][$ak]['hostname'];	// save old hostname to detect change
226
-					$old_hostname = $config['resolve_emptyonly']===false ? false : $addresses2[$s['id']][$ak]['hostname'];
227
-			        $hostname = $DNS->resolve_address ($Subnets->transform_to_dotted($addresses2[$s['id']][$ak]['ip_addr']), $old_hostname, true, $subnets[$sk]['nsid']);
228
-					if($hostname['class']=="resolved") {
229
-						if ($hostname['name']!=$old_hostname_save) {
230
-							$Addresses->update_address_hostname ($Subnets->transform_to_dotted($addresses2[$s['id']][$ak]['ip_addr']), $addresses2[$s['id']][$ak]['id'], $hostname['name']);
231
-						}
232
-					}
233
-				}
234
-			}
235
-		}
236
-	}
221
+                }
222
+
223
+                //resolve hostnames
224
+                if($subnets[$sk]['resolveDNS']=="1") {
225
+                    $old_hostname_save = $addresses2[$s['id']][$ak]['hostname'];	// save old hostname to detect change
226
+                    $old_hostname = $config['resolve_emptyonly']===false ? false : $addresses2[$s['id']][$ak]['hostname'];
227
+                    $hostname = $DNS->resolve_address ($Subnets->transform_to_dotted($addresses2[$s['id']][$ak]['ip_addr']), $old_hostname, true, $subnets[$sk]['nsid']);
228
+                    if($hostname['class']=="resolved") {
229
+                        if ($hostname['name']!=$old_hostname_save) {
230
+                            $Addresses->update_address_hostname ($Subnets->transform_to_dotted($addresses2[$s['id']][$ak]['ip_addr']), $addresses2[$s['id']][$ak]['id'], $hostname['name']);
231
+                        }
232
+                    }
233
+                }
234
+            }
235
+        }
236
+    }
237 237
 }
238 238
 //ping, pear
239 239
 else {
240
-	//run per MAX_THREADS
241
-	for ($m=0; $m<=sizeof($addresses); $m += $Scan->settings->scanMaxThreads) {
242
-	    // create threads
243
-	    $threads = array();
244
-	    //fork processes
245
-	    for ($i = 0; $i <= $Scan->settings->scanMaxThreads && $i <= sizeof($addresses); $i++) {
246
-	    	//only if index exists!
247
-	    	if(isset($addresses[$z])) {
248
-				//start new thread
249
-	            $threads[$z] = new PingThread( 'ping_address' );
250
-	            $threads[$z]->start($Subnets->transform_to_dotted($addresses[$z]['ip_addr']));
251
-	            $z++;				//next index
252
-			}
253
-	    }
254
-	    // wait for all the threads to finish
255
-	    while( !empty( $threads ) ) {
256
-	        foreach( $threads as $index => $thread ) {
257
-	            if( ! $thread->isAlive() ) {
258
-	            	//online
259
-	            	if($thread->getExitCode() == 0) {
260
-    	            	// set new available time
261
-    	            	$addresses[$index]['lastSeenNew'] =  $nowdate;
240
+    //run per MAX_THREADS
241
+    for ($m=0; $m<=sizeof($addresses); $m += $Scan->settings->scanMaxThreads) {
242
+        // create threads
243
+        $threads = array();
244
+        //fork processes
245
+        for ($i = 0; $i <= $Scan->settings->scanMaxThreads && $i <= sizeof($addresses); $i++) {
246
+            //only if index exists!
247
+            if(isset($addresses[$z])) {
248
+                //start new thread
249
+                $threads[$z] = new PingThread( 'ping_address' );
250
+                $threads[$z]->start($Subnets->transform_to_dotted($addresses[$z]['ip_addr']));
251
+                $z++;				//next index
252
+            }
253
+        }
254
+        // wait for all the threads to finish
255
+        while( !empty( $threads ) ) {
256
+            foreach( $threads as $index => $thread ) {
257
+                if( ! $thread->isAlive() ) {
258
+                    //online
259
+                    if($thread->getExitCode() == 0) {
260
+                        // set new available time
261
+                        $addresses[$index]['lastSeenNew'] =  $nowdate;
262 262
                         $address_change[$index] = $addresses[$index];	 				//change to online
263
-	            	}
264
-	            	//offline
265
-	            	else {
266
-    	            	// set nw online
267
-    	            	$addresses[$index]['lastSeenNew'] =  NULL;
263
+                    }
264
+                    //offline
265
+                    else {
266
+                        // set nw online
267
+                        $addresses[$index]['lastSeenNew'] =  NULL;
268 268
                         $address_change[$index] = $addresses[$index];	 				//change to online
269
-					}
270
-	            	//save exit code for host
271
-	                $addresses[$index]['newStatus'] = $thread->getExitCode();
272
-	                //remove thread
273
-	                unset( $threads[$index] );
274
-	            }
275
-	        }
276
-	        usleep(200000);
277
-	    }
278
-	}
279
-
280
-	//update statuses for online
281
-
282
-	# re-initialize classes
283
-	$Database  = new Database_PDO;
284
-	$Scan      = new Scan ($Database, $Subnets->settings);
285
-	$Addresses = new Addresses ($Database);
286
-
287
-	// reset debugging
288
-	$Scan->reset_debugging(false);
289
-
290
-	# update all active statuses
291
-	foreach($addresses as $k=>$a) {
292
-		if($a['newStatus']==0) {
293
-			$Scan->ping_update_lastseen ($a['id'], $nowdate);
294
-		}
269
+                    }
270
+                    //save exit code for host
271
+                    $addresses[$index]['newStatus'] = $thread->getExitCode();
272
+                    //remove thread
273
+                    unset( $threads[$index] );
274
+                }
275
+            }
276
+            usleep(200000);
277
+        }
278
+    }
279
+
280
+    //update statuses for online
281
+
282
+    # re-initialize classes
283
+    $Database  = new Database_PDO;
284
+    $Scan      = new Scan ($Database, $Subnets->settings);
285
+    $Addresses = new Addresses ($Database);
286
+
287
+    // reset debugging
288
+    $Scan->reset_debugging(false);
289
+
290
+    # update all active statuses
291
+    foreach($addresses as $k=>$a) {
292
+        if($a['newStatus']==0) {
293
+            $Scan->ping_update_lastseen ($a['id'], $nowdate);
294
+        }
295 295
 
296 296
         //resolve hostnames
297
-		if($a['resolveDNS']=="1") {
298
-			$old_hostname_save = $a['hostname'];	// save old hostname to detect change
299
-			$old_hostname = $config['resolve_emptyonly']===false ? false : $a['hostname'];
300
-	        $hostname = $DNS->resolve_address ($Subnets->transform_to_dotted($a['ip_addr']), $old_hostname, true, $a['nsid']);
301
-			if($hostname['class']=="resolved") {
302
-				if ($hostname['name']!=$old_hostname_save) {
303
-					$Addresses->update_address_hostname ($Subnets->transform_to_dotted($a['ip_addr']), $a['id'], $hostname['name']);
304
-				}
305
-			}
306
-		}
307
-	}
297
+        if($a['resolveDNS']=="1") {
298
+            $old_hostname_save = $a['hostname'];	// save old hostname to detect change
299
+            $old_hostname = $config['resolve_emptyonly']===false ? false : $a['hostname'];
300
+            $hostname = $DNS->resolve_address ($Subnets->transform_to_dotted($a['ip_addr']), $old_hostname, true, $a['nsid']);
301
+            if($hostname['class']=="resolved") {
302
+                if ($hostname['name']!=$old_hostname_save) {
303
+                    $Addresses->update_address_hostname ($Subnets->transform_to_dotted($a['ip_addr']), $a['id'], $hostname['name']);
304
+                }
305
+            }
306
+        }
307
+    }
308 308
 }
309 309
 
310 310
 
@@ -329,8 +329,8 @@  discard block
 block discarded – undo
329 329
         // update tag if not already online
330 330
         // tags have different indexes than script exit code is - 1=offline, 2=online
331 331
         if($address_change[$k]['state']!=2 && $Scan->settings->updateTags==1 && $Tools->address_types[$address_change[$k]['state']]['updateTag']==1) {
332
-	        $Scan->update_address_tag ($address_change[$k]['id'], 2, $address_change[$k]['state'], $change['lastSeenOld']);
333
-    	}
332
+            $Scan->update_address_tag ($address_change[$k]['id'], 2, $address_change[$k]['state'], $change['lastSeenOld']);
333
+        }
334 334
     }
335 335
     // now offline, and diff > offline period, do checks
336 336
     elseif($change['lastSeenNew']==NULL && $deviceDiff >= (int) $statuses[1]) {
@@ -338,38 +338,38 @@  discard block
 block discarded – undo
338 338
         if ($deviceDiff <= ((int) $statuses[1] + $agentDiff))  {
339 339
             $address_change[$k]['oldStatus'] = 0;
340 340
             $address_change[$k]['newStatus'] = 2;
341
-	        // update tag if not already offline
342
-	        // tags have different indexes than script exit code is - 1=offline, 2=online
343
-	        if($address_change[$k]['state']!=1 && $Scan->settings->updateTags==1 && $Tools->address_types[$address_change[$k]['state']]['updateTag']==1) {
344
-		        $Scan->update_address_tag ($address_change[$k]['id'], 1, $address_change[$k]['state'], $change['lastSeenOld']);
345
-		    }
341
+            // update tag if not already offline
342
+            // tags have different indexes than script exit code is - 1=offline, 2=online
343
+            if($address_change[$k]['state']!=1 && $Scan->settings->updateTags==1 && $Tools->address_types[$address_change[$k]['state']]['updateTag']==1) {
344
+                $Scan->update_address_tag ($address_change[$k]['id'], 1, $address_change[$k]['state'], $change['lastSeenOld']);
345
+            }
346 346
         }
347 347
         else {
348
-        	// already reported, check tag
349
-	        if($address_change[$k]['state']!=1 && $Scan->settings->updateTags==1 && $Tools->address_types[$address_change[$k]['state']]['updateTag']==1) {
350
-		        $Scan->update_address_tag ($address_change[$k]['id'], 1, $address_change[$k]['state'], $change['lastSeenOld']);
351
-		    }
352
-        	// remove from change array
348
+            // already reported, check tag
349
+            if($address_change[$k]['state']!=1 && $Scan->settings->updateTags==1 && $Tools->address_types[$address_change[$k]['state']]['updateTag']==1) {
350
+                $Scan->update_address_tag ($address_change[$k]['id'], 1, $address_change[$k]['state'], $change['lastSeenOld']);
351
+            }
352
+            // remove from change array
353 353
             unset ($address_change[$k]);
354 354
         }
355 355
     }
356 356
     // remove
357 357
     else {
358
-    	// check tag
359
-    	if ($change['lastSeenNew']!=NULL) {
360
-	        // update tag if not already online
361
-	        // tags have different indexes than script exit code is - 1=offline, 2=online
362
-	        if($address_change[$k]['state']!=2 && $Scan->settings->updateTags==1 && $Tools->address_types[$address_change[$k]['state']]['updateTag']==1) {
363
-		        $Scan->update_address_tag ($address_change[$k]['id'], 2, $address_change[$k]['state'], $change['lastSeenOld']);
364
-	    	}
365
-    	}
366
-    	else {
367
-    		// update tag if not already offline
368
-	        // tags have different indexes than script exit code is - 1=offline, 2=online
369
-	        if($address_change[$k]['state']!=1 && $Scan->settings->updateTags==1 && $Tools->address_types[$address_change[$k]['state']]['updateTag']==1) {
370
-		        $Scan->update_address_tag ($address_change[$k]['id'], 1, $address_change[$k]['state'], $change['lastSeenOld']);
371
-		    }
372
-    	}
358
+        // check tag
359
+        if ($change['lastSeenNew']!=NULL) {
360
+            // update tag if not already online
361
+            // tags have different indexes than script exit code is - 1=offline, 2=online
362
+            if($address_change[$k]['state']!=2 && $Scan->settings->updateTags==1 && $Tools->address_types[$address_change[$k]['state']]['updateTag']==1) {
363
+                $Scan->update_address_tag ($address_change[$k]['id'], 2, $address_change[$k]['state'], $change['lastSeenOld']);
364
+            }
365
+        }
366
+        else {
367
+            // update tag if not already offline
368
+            // tags have different indexes than script exit code is - 1=offline, 2=online
369
+            if($address_change[$k]['state']!=1 && $Scan->settings->updateTags==1 && $Tools->address_types[$address_change[$k]['state']]['updateTag']==1) {
370
+                $Scan->update_address_tag ($address_change[$k]['id'], 1, $address_change[$k]['state'], $change['lastSeenOld']);
371
+            }
372
+        }
373 373
 
374 374
         unset ($address_change[$k]);
375 375
     }
@@ -385,124 +385,124 @@  discard block
 block discarded – undo
385 385
 # all done, mail diff?
386 386
 if(sizeof($address_change)>0 && $config['ping_check_send_mail']) {
387 387
 
388
-	# remove old classes
389
-	unset($Database, $Subnets, $Addresses, $Tools, $Scan, $Result);
390
-
391
-	$Database 	= new Database_PDO;
392
-	$Subnets	= new Subnets ($Database);
393
-	$Addresses	= new Addresses ($Database);
394
-	$Tools		= new Tools ($Database);
395
-	$Scan		= new Scan ($Database);
396
-	$Result		= new Result();
397
-
398
-	// set exit flag to true
399
-	$Scan->ping_set_exit(true);
400
-	// set debugging
401
-	$Scan->reset_debugging(false);
402
-
403
-
404
-	# check for recipients
405
-	foreach($Tools->fetch_multiple_objects ("users", "role", "Administrator") as $admin) {
406
-		if($admin->mailNotify=="Yes") {
407
-			$recepients[] = array("name"=>$admin->real_name, "email"=>$admin->email);
408
-		}
409
-	}
410
-	# none?
411
-	if(!isset($recepients))	{ die(); }
412
-
413
-	# fake user object, needed for create_link
414
-	$User = new StdClass();
415
-	@$User->settings->prettyLinks = $Scan->settings->prettyLinks;
416
-
417
-	# try to send
418
-	try {
419
-		# fetch mailer settings
420
-		$mail_settings = $Tools->fetch_object("settingsMail", "id", 1);
421
-		# initialize mailer
422
-		$phpipam_mail = new phpipam_mail($Scan->settings, $mail_settings);
423
-
424
-		// set subject
425
-		$subject	= "phpIPAM IP state change ".$nowdate;
426
-
427
-		//html
428
-		$content[] = "<p style='margin-left:10px;'>$Subnets->mail_font_style <font style='font-size:16px;size:16px;'>phpIPAM host changes</font></font></p><br>";
429
-
430
-		$content[] = "<table style='margin-left:10px;margin-top:5px;width:auto;padding:0px;border-collapse:collapse;border:1px solid #ccc;'>";
431
-		$content[] = "<tr>";
432
-		$content[] = "	<th style='padding:3px 8px;border:1px solid #ccc;border-bottom:2px solid gray;white-space:nowrap;'>$Subnets->mail_font_style IP</font></th>";
433
-		$content[] = "	<th style='padding:3px 8px;border:1px solid #ccc;border-bottom:2px solid gray;'>$Subnets->mail_font_style Description</font></th>";
434
-		$content[] = "	<th style='padding:3px 8px;border:1px solid #ccc;border-bottom:2px solid gray;'>$Subnets->mail_font_style Hostname</font></th>";
435
-		$content[] = "	<th style='padding:3px 8px;border:1px solid #ccc;border-bottom:2px solid gray;'>$Subnets->mail_font_style Subnet</font></th>";
436
-		$content[] = "	<th style='padding:3px 8px;border:1px solid #ccc;border-bottom:2px solid gray;'>$Subnets->mail_font_style Last seen</font></th>";
437
-		$content[] = "	<th style='padding:3px 8px;border:1px solid #ccc;border-bottom:2px solid gray;'>$Subnets->mail_font_style Status</font></th>";
438
-		$content[] = "</tr>";
439
-
440
-		//plain
441
-		$content_plain[] = "phpIPAM host changes \r\n------------------------------";
442
-
443
-		//Changes
444
-		foreach($address_change as $change) {
445
-			//reformat statuses
446
-			if($change['oldStatus'] == 0) {
447
-				$oldStatus = "<font style='color:#04B486'>Online</font>";
448
-				$newStatus = "<font style='color:#DF0101'>Offline</font>";
449
-			}
450
-			else {
451
-				$oldStatus = "<font style='color:#DF0101'>Offline</font>";
452
-				$newStatus = "<font style='color:#04B486'>Online</font>";
453
-			}
454
-
455
-			//set subnet
456
-			$subnet 	 = $Subnets->fetch_subnet(null, $change['subnetId']);
457
-			//ago
458
-			if(is_null($change['lastSeen']) || $change['lastSeen']=="1970-01-01 00:00:01" || $change['lastSeen']=="0000-00-00 00:00:00") {
459
-				$ago	  = "never";
460
-			} else {
461
-				$timeDiff = $now - strtotime($change['lastSeen']);
462
-
463
-	    		// reformat
464
-	    		$lastSeen = date("m/d H:i", strtotime($change['lastSeen']) );
465
-				$ago 	  = $lastSeen." (".$Result->sec2hms($timeDiff)." ago)";
466
-			}
467
-	        // desc
468
-			$change['description'] = strlen($change['description'])>0 ? "$Subnets->mail_font_style $change[description]</font>" : "$Subnets->mail_font_style / </font>";
469
-			// subnet desc
470
-			$subnet->description = strlen($subnet->description)>0 ? "$Subnets->mail_font_style $subnet->description</font>" : "$Subnets->mail_font_style / </font>";
471
-
472
-			//content
473
-			$content[] = "<tr>";
474
-			$content[] = "	<td style='padding:3px 8px;border:1px solid #ccc;'><a href='".rtrim(str_replace(BASE, "",$Scan->settings->siteURL), "/")."".create_link("subnets",$subnet->sectionId,$subnet->id)."'>$Subnets->mail_font_style_href ".$Subnets->transform_to_dotted($change['ip_addr'])."</font></a></td>";
475
-			$content[] = "	<td style='padding:3px 8px;border:1px solid #ccc;'>$Subnets->mail_font_style $change[description]</font></td>";
476
-			$content[] = "	<td style='padding:3px 8px;border:1px solid #ccc;'>$Subnets->mail_font_style_href $change[hostname]</font></td>";
477
-			$content[] = "	<td style='padding:3px 8px;border:1px solid #ccc;'><a href='".rtrim(str_replace(BASE, "",$Scan->settings->siteURL), "/")."".create_link("subnets",$subnet->sectionId,$subnet->id)."'>$Subnets->mail_font_style_href ".$Subnets->transform_to_dotted($subnet->subnet)."/".$subnet->mask."</font></a>".$subnet->description."</td>";
478
-			$content[] = "	<td style='padding:3px 8px;border:1px solid #ccc;'>$Subnets->mail_font_style $ago</td>";
479
-			$content[] = "	<td style='padding:3px 8px;border:1px solid #ccc;'>$Subnets->mail_font_style $oldStatus > $newStatus</td>";
480
-			$content[] = "</tr>";
481
-
482
-			//plain content
483
-			$content_plain[] = "\t * ".$Subnets->transform_to_dotted($change['ip_addr'])." (".$Subnets->transform_to_dotted($subnet->subnet)."/".$subnet->mask.")\r\n \t  ".strip_tags($oldStatus)." => ".strip_tags($newStatus);
484
-
485
-		}
486
-		$content[] = "</table>";
487
-
488
-
489
-		# set content
490
-		$content 		= $phpipam_mail->generate_message (implode("\r\n", $content));
491
-		$content_plain 	= implode("\r\n",$content_plain);
492
-
493
-		$phpipam_mail->Php_mailer->setFrom($mail_settings->mAdminMail, $mail_settings->mAdminName);
494
-		//add all admins to CC
495
-		foreach($recepients as $admin) {
496
-			$phpipam_mail->Php_mailer->addAddress(addslashes($admin['email']), addslashes($admin['name']));
497
-		}
498
-		$phpipam_mail->Php_mailer->Subject = $subject;
499
-		$phpipam_mail->Php_mailer->msgHTML($content);
500
-		$phpipam_mail->Php_mailer->AltBody = $content_plain;
501
-		//send
502
-		$phpipam_mail->Php_mailer->send();
503
-	} catch (phpmailerException $e) {
504
-		$Result->show_cli("Mailer Error: ".$e->errorMessage(), true);
505
-	} catch (Exception $e) {
506
-		$Result->show_cli("Mailer Error: ".$e->getMessage(), true);
507
-	}
388
+    # remove old classes
389
+    unset($Database, $Subnets, $Addresses, $Tools, $Scan, $Result);
390
+
391
+    $Database 	= new Database_PDO;
392
+    $Subnets	= new Subnets ($Database);
393
+    $Addresses	= new Addresses ($Database);
394
+    $Tools		= new Tools ($Database);
395
+    $Scan		= new Scan ($Database);
396
+    $Result		= new Result();
397
+
398
+    // set exit flag to true
399
+    $Scan->ping_set_exit(true);
400
+    // set debugging
401
+    $Scan->reset_debugging(false);
402
+
403
+
404
+    # check for recipients
405
+    foreach($Tools->fetch_multiple_objects ("users", "role", "Administrator") as $admin) {
406
+        if($admin->mailNotify=="Yes") {
407
+            $recepients[] = array("name"=>$admin->real_name, "email"=>$admin->email);
408
+        }
409
+    }
410
+    # none?
411
+    if(!isset($recepients))	{ die(); }
412
+
413
+    # fake user object, needed for create_link
414
+    $User = new StdClass();
415
+    @$User->settings->prettyLinks = $Scan->settings->prettyLinks;
416
+
417
+    # try to send
418
+    try {
419
+        # fetch mailer settings
420
+        $mail_settings = $Tools->fetch_object("settingsMail", "id", 1);
421
+        # initialize mailer
422
+        $phpipam_mail = new phpipam_mail($Scan->settings, $mail_settings);
423
+
424
+        // set subject
425
+        $subject	= "phpIPAM IP state change ".$nowdate;
426
+
427
+        //html
428
+        $content[] = "<p style='margin-left:10px;'>$Subnets->mail_font_style <font style='font-size:16px;size:16px;'>phpIPAM host changes</font></font></p><br>";
429
+
430
+        $content[] = "<table style='margin-left:10px;margin-top:5px;width:auto;padding:0px;border-collapse:collapse;border:1px solid #ccc;'>";
431
+        $content[] = "<tr>";
432
+        $content[] = "	<th style='padding:3px 8px;border:1px solid #ccc;border-bottom:2px solid gray;white-space:nowrap;'>$Subnets->mail_font_style IP</font></th>";
433
+        $content[] = "	<th style='padding:3px 8px;border:1px solid #ccc;border-bottom:2px solid gray;'>$Subnets->mail_font_style Description</font></th>";
434
+        $content[] = "	<th style='padding:3px 8px;border:1px solid #ccc;border-bottom:2px solid gray;'>$Subnets->mail_font_style Hostname</font></th>";
435
+        $content[] = "	<th style='padding:3px 8px;border:1px solid #ccc;border-bottom:2px solid gray;'>$Subnets->mail_font_style Subnet</font></th>";
436
+        $content[] = "	<th style='padding:3px 8px;border:1px solid #ccc;border-bottom:2px solid gray;'>$Subnets->mail_font_style Last seen</font></th>";
437
+        $content[] = "	<th style='padding:3px 8px;border:1px solid #ccc;border-bottom:2px solid gray;'>$Subnets->mail_font_style Status</font></th>";
438
+        $content[] = "</tr>";
439
+
440
+        //plain
441
+        $content_plain[] = "phpIPAM host changes \r\n------------------------------";
442
+
443
+        //Changes
444
+        foreach($address_change as $change) {
445
+            //reformat statuses
446
+            if($change['oldStatus'] == 0) {
447
+                $oldStatus = "<font style='color:#04B486'>Online</font>";
448
+                $newStatus = "<font style='color:#DF0101'>Offline</font>";
449
+            }
450
+            else {
451
+                $oldStatus = "<font style='color:#DF0101'>Offline</font>";
452
+                $newStatus = "<font style='color:#04B486'>Online</font>";
453
+            }
454
+
455
+            //set subnet
456
+            $subnet 	 = $Subnets->fetch_subnet(null, $change['subnetId']);
457
+            //ago
458
+            if(is_null($change['lastSeen']) || $change['lastSeen']=="1970-01-01 00:00:01" || $change['lastSeen']=="0000-00-00 00:00:00") {
459
+                $ago	  = "never";
460
+            } else {
461
+                $timeDiff = $now - strtotime($change['lastSeen']);
462
+
463
+                // reformat
464
+                $lastSeen = date("m/d H:i", strtotime($change['lastSeen']) );
465
+                $ago 	  = $lastSeen." (".$Result->sec2hms($timeDiff)." ago)";
466
+            }
467
+            // desc
468
+            $change['description'] = strlen($change['description'])>0 ? "$Subnets->mail_font_style $change[description]</font>" : "$Subnets->mail_font_style / </font>";
469
+            // subnet desc
470
+            $subnet->description = strlen($subnet->description)>0 ? "$Subnets->mail_font_style $subnet->description</font>" : "$Subnets->mail_font_style / </font>";
471
+
472
+            //content
473
+            $content[] = "<tr>";
474
+            $content[] = "	<td style='padding:3px 8px;border:1px solid #ccc;'><a href='".rtrim(str_replace(BASE, "",$Scan->settings->siteURL), "/")."".create_link("subnets",$subnet->sectionId,$subnet->id)."'>$Subnets->mail_font_style_href ".$Subnets->transform_to_dotted($change['ip_addr'])."</font></a></td>";
475
+            $content[] = "	<td style='padding:3px 8px;border:1px solid #ccc;'>$Subnets->mail_font_style $change[description]</font></td>";
476
+            $content[] = "	<td style='padding:3px 8px;border:1px solid #ccc;'>$Subnets->mail_font_style_href $change[hostname]</font></td>";
477
+            $content[] = "	<td style='padding:3px 8px;border:1px solid #ccc;'><a href='".rtrim(str_replace(BASE, "",$Scan->settings->siteURL), "/")."".create_link("subnets",$subnet->sectionId,$subnet->id)."'>$Subnets->mail_font_style_href ".$Subnets->transform_to_dotted($subnet->subnet)."/".$subnet->mask."</font></a>".$subnet->description."</td>";
478
+            $content[] = "	<td style='padding:3px 8px;border:1px solid #ccc;'>$Subnets->mail_font_style $ago</td>";
479
+            $content[] = "	<td style='padding:3px 8px;border:1px solid #ccc;'>$Subnets->mail_font_style $oldStatus > $newStatus</td>";
480
+            $content[] = "</tr>";
481
+
482
+            //plain content
483
+            $content_plain[] = "\t * ".$Subnets->transform_to_dotted($change['ip_addr'])." (".$Subnets->transform_to_dotted($subnet->subnet)."/".$subnet->mask.")\r\n \t  ".strip_tags($oldStatus)." => ".strip_tags($newStatus);
484
+
485
+        }
486
+        $content[] = "</table>";
487
+
488
+
489
+        # set content
490
+        $content 		= $phpipam_mail->generate_message (implode("\r\n", $content));
491
+        $content_plain 	= implode("\r\n",$content_plain);
492
+
493
+        $phpipam_mail->Php_mailer->setFrom($mail_settings->mAdminMail, $mail_settings->mAdminName);
494
+        //add all admins to CC
495
+        foreach($recepients as $admin) {
496
+            $phpipam_mail->Php_mailer->addAddress(addslashes($admin['email']), addslashes($admin['name']));
497
+        }
498
+        $phpipam_mail->Php_mailer->Subject = $subject;
499
+        $phpipam_mail->Php_mailer->msgHTML($content);
500
+        $phpipam_mail->Php_mailer->AltBody = $content_plain;
501
+        //send
502
+        $phpipam_mail->Php_mailer->send();
503
+    } catch (phpmailerException $e) {
504
+        $Result->show_cli("Mailer Error: ".$e->errorMessage(), true);
505
+    } catch (Exception $e) {
506
+        $Result->show_cli("Mailer Error: ".$e->getMessage(), true);
507
+    }
508 508
 }
509 509
\ No newline at end of file
Please login to merge, or discard this patch.
Spacing   +129 added lines, -129 removed lines patch added patch discarded remove patch
@@ -30,18 +30,18 @@  discard block
 block discarded – undo
30 30
  */
31 31
 
32 32
 # include required scripts
33
-require_once( dirname(__FILE__) . '/../functions.php' );
34
-require( dirname(__FILE__) . '/../../functions/classes/class.Thread.php');
33
+require_once(dirname(__FILE__).'/../functions.php');
34
+require(dirname(__FILE__).'/../../functions/classes/class.Thread.php');
35 35
 
36 36
 # initialize objects
37 37
 $Database 	= new Database_PDO;
38
-$Subnets	= new Subnets ($Database);
39
-$Addresses	= new Addresses ($Database);
40
-$Tools		= new Tools ($Database);
41
-$Admin		= new Admin ($Database, false);
42
-$Scan		= new Scan ($Database);
43
-$DNS		= new DNS ($Database);
44
-$Result		= new Result();
38
+$Subnets = new Subnets($Database);
39
+$Addresses	= new Addresses($Database);
40
+$Tools		= new Tools($Database);
41
+$Admin		= new Admin($Database, false);
42
+$Scan = new Scan($Database);
43
+$DNS = new DNS($Database);
44
+$Result = new Result();
45 45
 
46 46
 // set exit flag to true
47 47
 $Scan->ping_set_exit(true);
@@ -50,53 +50,53 @@  discard block
 block discarded – undo
50 50
 // fetch agent
51 51
 $agent = $Tools->fetch_object("scanAgents", "id", 1);
52 52
 // set address types array
53
-$Tools->get_addresses_types ();
53
+$Tools->get_addresses_types();
54 54
 // change scan type?
55
-if(@$config['ping_check_method'])
56
-$Scan->reset_scan_method ($config['ping_check_method']);
55
+if (@$config['ping_check_method'])
56
+$Scan->reset_scan_method($config['ping_check_method']);
57 57
 
58 58
 // set ping statuses
59 59
 $statuses = explode(";", $Scan->settings->pingStatus);
60 60
 // set mail override flag
61
-if(!isset($config['ping_check_send_mail'])) {
61
+if (!isset($config['ping_check_send_mail'])) {
62 62
 	$config['ping_check_send_mail'] = true;
63 63
 }
64 64
 
65 65
 // response for mailing
66
-$address_change = array();			// Array with differences, can be used to email to admins
66
+$address_change = array(); // Array with differences, can be used to email to admins
67 67
 
68 68
 // set now for whole script
69 69
 $now     = time();
70
-$nowdate = date ("Y-m-d H:i:s");
70
+$nowdate = date("Y-m-d H:i:s");
71 71
 
72 72
 
73 73
 // script can only be run from cli
74
-if(php_sapi_name()!="cli") 						{ die("This script can only be run from cli!"); }
74
+if (php_sapi_name() != "cli") { die("This script can only be run from cli!"); }
75 75
 // test to see if threading is available
76
-if(!PingThread::available()) 					{ die("Threading is required for scanning subnets. Please recompile PHP with pcntl extension"); }
76
+if (!PingThread::available()) { die("Threading is required for scanning subnets. Please recompile PHP with pcntl extension"); }
77 77
 // verify ping path
78
-if ($Scan->icmp_type=="ping") {
79
-if(!file_exists($Scan->settings->scanPingPath)) { die("Invalid ping path!"); }
78
+if ($Scan->icmp_type == "ping") {
79
+if (!file_exists($Scan->settings->scanPingPath)) { die("Invalid ping path!"); }
80 80
 }
81 81
 // verify fping path
82
-if ($Scan->icmp_type=="fping") {
83
-if(!file_exists($Scan->settings->scanFPingPath)){ die("Invalid fping path!"); }
82
+if ($Scan->icmp_type == "fping") {
83
+if (!file_exists($Scan->settings->scanFPingPath)) { die("Invalid fping path!"); }
84 84
 }
85 85
 
86 86
 
87 87
 //first fetch all subnets to be scanned
88
-$scan_subnets = $Subnets->fetch_all_subnets_for_pingCheck (1);
89
-if($Scan->debugging)							{ print_r($scan_subnets); }
90
-if($scan_subnets===false) 						{ die("No subnets are marked for checking status updates\n"); }
88
+$scan_subnets = $Subnets->fetch_all_subnets_for_pingCheck(1);
89
+if ($Scan->debugging) { print_r($scan_subnets); }
90
+if ($scan_subnets === false) { die("No subnets are marked for checking status updates\n"); }
91 91
 //fetch all addresses that need to be checked
92
-foreach($scan_subnets as $s) {
92
+foreach ($scan_subnets as $s) {
93 93
 
94 94
 	// if subnet has slaves dont check it
95
-	if ($Subnets->has_slaves ($s->id) === false) {
95
+	if ($Subnets->has_slaves($s->id) === false) {
96 96
 
97
-		$subnet_addresses = $Addresses->fetch_subnet_addresses ($s->id);
97
+		$subnet_addresses = $Addresses->fetch_subnet_addresses($s->id);
98 98
 		//set array for fping
99
-		if($Scan->icmp_type=="fping")	{
99
+		if ($Scan->icmp_type == "fping") {
100 100
 			$subnets[] = array(
101 101
 								"id"         =>$s->id,
102 102
 								"cidr"       =>$Subnets->transform_to_dotted($s->subnet)."/".$s->mask,
@@ -105,12 +105,12 @@  discard block
 block discarded – undo
105 105
 			                   );
106 106
 		}
107 107
 		//save addresses
108
-		if(sizeof($subnet_addresses)>0) {
109
-			foreach($subnet_addresses as $a) {
108
+		if (sizeof($subnet_addresses) > 0) {
109
+			foreach ($subnet_addresses as $a) {
110 110
 				//ignore excludePing
111
-				if($a->excludePing!=1) {
111
+				if ($a->excludePing != 1) {
112 112
 					//create different array for fping
113
-					if($Scan->icmp_type=="fping")	{
113
+					if ($Scan->icmp_type == "fping") {
114 114
 						$addresses2[$s->id][$a->id] = array(
115 115
 															"id"          =>$a->id,
116 116
 															"ip_addr"     =>$a->ip_addr,
@@ -123,10 +123,10 @@  discard block
 block discarded – undo
123 123
 															"resolveDNS"  =>$s->resolveDNS,
124 124
 															"nsid"        =>$s->nsid
125 125
 															);
126
-						$addresses[$s->id][$a->id]  = $a->ip_addr;
126
+						$addresses[$s->id][$a->id] = $a->ip_addr;
127 127
 					}
128 128
 					else {
129
-						$addresses[] 		 		= array(
129
+						$addresses[] = array(
130 130
 															"id"          =>$a->id,
131 131
 															"ip_addr"     =>$a->ip_addr,
132 132
 															"description" =>$a->description,
@@ -143,54 +143,54 @@  discard block
 block discarded – undo
143 143
 			}
144 144
 		}
145 145
 		// save update time
146
-		$Scan->update_subnet_scantime ($s->id, $nowdate);
146
+		$Scan->update_subnet_scantime($s->id, $nowdate);
147 147
 	}
148 148
 }
149 149
 
150 150
 
151
-if($Scan->debugging)							{ print "Using $Scan->icmp_type\n--------------------\n\n";print_r($addresses); }
151
+if ($Scan->debugging) { print "Using $Scan->icmp_type\n--------------------\n\n"; print_r($addresses); }
152 152
 //if none die
153
-if(!isset($addresses))							{ die("No addresses to check"); }
153
+if (!isset($addresses)) { die("No addresses to check"); }
154 154
 
155 155
 
156 156
 /* scan */
157 157
 
158
-$z = 0;			//addresses array index
158
+$z = 0; //addresses array index
159 159
 
160 160
 //different scan for fping
161
-if($Scan->icmp_type=="fping") {
161
+if ($Scan->icmp_type == "fping") {
162 162
 	//run per MAX_THREADS
163
-	for ($m=0; $m<=sizeof($subnets); $m += $Scan->settings->scanMaxThreads) {
163
+	for ($m = 0; $m <= sizeof($subnets); $m += $Scan->settings->scanMaxThreads) {
164 164
 	    // create threads
165 165
 	    $threads = array();
166 166
 	    //fork processes
167 167
 	    for ($i = 0; $i <= $Scan->settings->scanMaxThreads && $i <= sizeof($subnets); $i++) {
168 168
 	    	//only if index exists!
169
-	    	if(isset($subnets[$z])) {
169
+	    	if (isset($subnets[$z])) {
170 170
 				//start new thread
171
-	            $threads[$z] = new PingThread( 'fping_subnet' );
172
-	            $threads[$z]->start_fping( $subnets[$z]['cidr'] );
173
-	            $z++;				//next index
171
+	            $threads[$z] = new PingThread('fping_subnet');
172
+	            $threads[$z]->start_fping($subnets[$z]['cidr']);
173
+	            $z++; //next index
174 174
 			}
175 175
 	    }
176 176
 	    // wait for all the threads to finish
177
-	    while( !empty( $threads ) ) {
178
-			foreach($threads as $index => $thread) {
177
+	    while (!empty($threads)) {
178
+			foreach ($threads as $index => $thread) {
179 179
 				$child_pipe = "/tmp/pipe_".$thread->getPid();
180 180
 
181 181
 				if (file_exists($child_pipe)) {
182
-					$file_descriptor = fopen( $child_pipe, "r");
182
+					$file_descriptor = fopen($child_pipe, "r");
183 183
 					$child_response = "";
184 184
 					while (!feof($file_descriptor)) {
185 185
 						$child_response .= fread($file_descriptor, 8192);
186 186
 					}
187 187
 					//we have the child data in the parent, but serialized:
188
-					$child_response = unserialize( $child_response );
188
+					$child_response = unserialize($child_response);
189 189
 					//store
190 190
 					$subnets[$index]['result'] = $child_response;
191 191
 
192 192
 					//now, child is dead, and parent close the pipe
193
-					unlink( $child_pipe );
193
+					unlink($child_pipe);
194 194
 					unset($threads[$index]);
195 195
 				}
196 196
 			}
@@ -199,12 +199,12 @@  discard block
 block discarded – undo
199 199
 	}
200 200
 
201 201
 	//now we must remove all non-existing hosts
202
-	foreach($subnets as $sk=>$s) {
203
-		if(sizeof(@$s['result'])>0 && sizeof($addresses[$s['id']])>0) {
202
+	foreach ($subnets as $sk=>$s) {
203
+		if (sizeof(@$s['result']) > 0 && sizeof($addresses[$s['id']]) > 0) {
204 204
 			//loop addresses
205
-			foreach($addresses[$s['id']] as $ak=>$a) {
205
+			foreach ($addresses[$s['id']] as $ak=>$a) {
206 206
 				//offline host
207
-				if(array_search($Subnets->transform_to_dotted($a), $subnets[$sk]['result'])===false) {
207
+				if (array_search($Subnets->transform_to_dotted($a), $subnets[$sk]['result']) === false) {
208 208
     				// new change = null
209 209
     				$addresses2[$s['id']][$ak]['lastSeenNew'] = NULL;
210 210
 					//save to out array
@@ -217,17 +217,17 @@  discard block
 block discarded – undo
217 217
 					//save to out array
218 218
                     $address_change[] = $addresses2[$s['id']][$ak];
219 219
                     //update status
220
-                    $Scan->ping_update_lastseen ($addresses2[$s['id']][$ak]['id'], $nowdate);
220
+                    $Scan->ping_update_lastseen($addresses2[$s['id']][$ak]['id'], $nowdate);
221 221
 				}
222 222
 
223 223
 		        //resolve hostnames
224
-				if($subnets[$sk]['resolveDNS']=="1") {
225
-					$old_hostname_save = $addresses2[$s['id']][$ak]['hostname'];	// save old hostname to detect change
226
-					$old_hostname = $config['resolve_emptyonly']===false ? false : $addresses2[$s['id']][$ak]['hostname'];
227
-			        $hostname = $DNS->resolve_address ($Subnets->transform_to_dotted($addresses2[$s['id']][$ak]['ip_addr']), $old_hostname, true, $subnets[$sk]['nsid']);
228
-					if($hostname['class']=="resolved") {
229
-						if ($hostname['name']!=$old_hostname_save) {
230
-							$Addresses->update_address_hostname ($Subnets->transform_to_dotted($addresses2[$s['id']][$ak]['ip_addr']), $addresses2[$s['id']][$ak]['id'], $hostname['name']);
224
+				if ($subnets[$sk]['resolveDNS'] == "1") {
225
+					$old_hostname_save = $addresses2[$s['id']][$ak]['hostname']; // save old hostname to detect change
226
+					$old_hostname = $config['resolve_emptyonly'] === false ? false : $addresses2[$s['id']][$ak]['hostname'];
227
+			        $hostname = $DNS->resolve_address($Subnets->transform_to_dotted($addresses2[$s['id']][$ak]['ip_addr']), $old_hostname, true, $subnets[$sk]['nsid']);
228
+					if ($hostname['class'] == "resolved") {
229
+						if ($hostname['name'] != $old_hostname_save) {
230
+							$Addresses->update_address_hostname($Subnets->transform_to_dotted($addresses2[$s['id']][$ak]['ip_addr']), $addresses2[$s['id']][$ak]['id'], $hostname['name']);
231 231
 						}
232 232
 					}
233 233
 				}
@@ -238,39 +238,39 @@  discard block
 block discarded – undo
238 238
 //ping, pear
239 239
 else {
240 240
 	//run per MAX_THREADS
241
-	for ($m=0; $m<=sizeof($addresses); $m += $Scan->settings->scanMaxThreads) {
241
+	for ($m = 0; $m <= sizeof($addresses); $m += $Scan->settings->scanMaxThreads) {
242 242
 	    // create threads
243 243
 	    $threads = array();
244 244
 	    //fork processes
245 245
 	    for ($i = 0; $i <= $Scan->settings->scanMaxThreads && $i <= sizeof($addresses); $i++) {
246 246
 	    	//only if index exists!
247
-	    	if(isset($addresses[$z])) {
247
+	    	if (isset($addresses[$z])) {
248 248
 				//start new thread
249
-	            $threads[$z] = new PingThread( 'ping_address' );
249
+	            $threads[$z] = new PingThread('ping_address');
250 250
 	            $threads[$z]->start($Subnets->transform_to_dotted($addresses[$z]['ip_addr']));
251
-	            $z++;				//next index
251
+	            $z++; //next index
252 252
 			}
253 253
 	    }
254 254
 	    // wait for all the threads to finish
255
-	    while( !empty( $threads ) ) {
256
-	        foreach( $threads as $index => $thread ) {
257
-	            if( ! $thread->isAlive() ) {
255
+	    while (!empty($threads)) {
256
+	        foreach ($threads as $index => $thread) {
257
+	            if (!$thread->isAlive()) {
258 258
 	            	//online
259
-	            	if($thread->getExitCode() == 0) {
259
+	            	if ($thread->getExitCode() == 0) {
260 260
     	            	// set new available time
261
-    	            	$addresses[$index]['lastSeenNew'] =  $nowdate;
262
-                        $address_change[$index] = $addresses[$index];	 				//change to online
261
+    	            	$addresses[$index]['lastSeenNew'] = $nowdate;
262
+                        $address_change[$index] = $addresses[$index]; //change to online
263 263
 	            	}
264 264
 	            	//offline
265 265
 	            	else {
266 266
     	            	// set nw online
267
-    	            	$addresses[$index]['lastSeenNew'] =  NULL;
268
-                        $address_change[$index] = $addresses[$index];	 				//change to online
267
+    	            	$addresses[$index]['lastSeenNew'] = NULL;
268
+                        $address_change[$index] = $addresses[$index]; //change to online
269 269
 					}
270 270
 	            	//save exit code for host
271 271
 	                $addresses[$index]['newStatus'] = $thread->getExitCode();
272 272
 	                //remove thread
273
-	                unset( $threads[$index] );
273
+	                unset($threads[$index]);
274 274
 	            }
275 275
 	        }
276 276
 	        usleep(200000);
@@ -281,26 +281,26 @@  discard block
 block discarded – undo
281 281
 
282 282
 	# re-initialize classes
283 283
 	$Database  = new Database_PDO;
284
-	$Scan      = new Scan ($Database, $Subnets->settings);
285
-	$Addresses = new Addresses ($Database);
284
+	$Scan      = new Scan($Database, $Subnets->settings);
285
+	$Addresses = new Addresses($Database);
286 286
 
287 287
 	// reset debugging
288 288
 	$Scan->reset_debugging(false);
289 289
 
290 290
 	# update all active statuses
291
-	foreach($addresses as $k=>$a) {
292
-		if($a['newStatus']==0) {
293
-			$Scan->ping_update_lastseen ($a['id'], $nowdate);
291
+	foreach ($addresses as $k=>$a) {
292
+		if ($a['newStatus'] == 0) {
293
+			$Scan->ping_update_lastseen($a['id'], $nowdate);
294 294
 		}
295 295
 
296 296
         //resolve hostnames
297
-		if($a['resolveDNS']=="1") {
298
-			$old_hostname_save = $a['hostname'];	// save old hostname to detect change
299
-			$old_hostname = $config['resolve_emptyonly']===false ? false : $a['hostname'];
300
-	        $hostname = $DNS->resolve_address ($Subnets->transform_to_dotted($a['ip_addr']), $old_hostname, true, $a['nsid']);
301
-			if($hostname['class']=="resolved") {
302
-				if ($hostname['name']!=$old_hostname_save) {
303
-					$Addresses->update_address_hostname ($Subnets->transform_to_dotted($a['ip_addr']), $a['id'], $hostname['name']);
297
+		if ($a['resolveDNS'] == "1") {
298
+			$old_hostname_save = $a['hostname']; // save old hostname to detect change
299
+			$old_hostname = $config['resolve_emptyonly'] === false ? false : $a['hostname'];
300
+	        $hostname = $DNS->resolve_address($Subnets->transform_to_dotted($a['ip_addr']), $old_hostname, true, $a['nsid']);
301
+			if ($hostname['class'] == "resolved") {
302
+				if ($hostname['name'] != $old_hostname_save) {
303
+					$Addresses->update_address_hostname($Subnets->transform_to_dotted($a['ip_addr']), $a['id'], $hostname['name']);
304 304
 				}
305 305
 			}
306 306
 		}
@@ -316,38 +316,38 @@  discard block
 block discarded – undo
316 316
 // loop
317 317
 foreach ($address_change as $k=>$change) {
318 318
     // null old - set to epoch time
319
-    if (strtotime($change['lastSeenOld'])===false)  { $change['lastSeenOld'] = date("Y-m-d H:i:s", 0); }
319
+    if (strtotime($change['lastSeenOld']) === false) { $change['lastSeenOld'] = date("Y-m-d H:i:s", 0); }
320 320
 
321 321
     // set general diffs
322
-    $deviceDiff = $now - strtotime($change['lastSeenOld']);	        // now - device last seen
323
-    $agentDiff  = $now - strtotime($agent->last_access);	        // now - last agent check
322
+    $deviceDiff = $now - strtotime($change['lastSeenOld']); // now - device last seen
323
+    $agentDiff  = $now - strtotime($agent->last_access); // now - last agent check
324 324
 
325 325
     // if now online and old offline send mail
326
-    if ($change['lastSeenNew']!=NULL && $deviceDiff >= (int) $statuses[1]) {
326
+    if ($change['lastSeenNew'] != NULL && $deviceDiff >= (int) $statuses[1]) {
327 327
         $address_change[$k]['oldStatus'] = 2;
328 328
         $address_change[$k]['newStatus'] = 0;
329 329
         // update tag if not already online
330 330
         // tags have different indexes than script exit code is - 1=offline, 2=online
331
-        if($address_change[$k]['state']!=2 && $Scan->settings->updateTags==1 && $Tools->address_types[$address_change[$k]['state']]['updateTag']==1) {
332
-	        $Scan->update_address_tag ($address_change[$k]['id'], 2, $address_change[$k]['state'], $change['lastSeenOld']);
331
+        if ($address_change[$k]['state'] != 2 && $Scan->settings->updateTags == 1 && $Tools->address_types[$address_change[$k]['state']]['updateTag'] == 1) {
332
+	        $Scan->update_address_tag($address_change[$k]['id'], 2, $address_change[$k]['state'], $change['lastSeenOld']);
333 333
     	}
334 334
     }
335 335
     // now offline, and diff > offline period, do checks
336
-    elseif($change['lastSeenNew']==NULL && $deviceDiff >= (int) $statuses[1]) {
336
+    elseif ($change['lastSeenNew'] == NULL && $deviceDiff >= (int) $statuses[1]) {
337 337
         // if not already reported
338
-        if ($deviceDiff <= ((int) $statuses[1] + $agentDiff))  {
338
+        if ($deviceDiff <= ((int) $statuses[1] + $agentDiff)) {
339 339
             $address_change[$k]['oldStatus'] = 0;
340 340
             $address_change[$k]['newStatus'] = 2;
341 341
 	        // update tag if not already offline
342 342
 	        // tags have different indexes than script exit code is - 1=offline, 2=online
343
-	        if($address_change[$k]['state']!=1 && $Scan->settings->updateTags==1 && $Tools->address_types[$address_change[$k]['state']]['updateTag']==1) {
344
-		        $Scan->update_address_tag ($address_change[$k]['id'], 1, $address_change[$k]['state'], $change['lastSeenOld']);
343
+	        if ($address_change[$k]['state'] != 1 && $Scan->settings->updateTags == 1 && $Tools->address_types[$address_change[$k]['state']]['updateTag'] == 1) {
344
+		        $Scan->update_address_tag($address_change[$k]['id'], 1, $address_change[$k]['state'], $change['lastSeenOld']);
345 345
 		    }
346 346
         }
347 347
         else {
348 348
         	// already reported, check tag
349
-	        if($address_change[$k]['state']!=1 && $Scan->settings->updateTags==1 && $Tools->address_types[$address_change[$k]['state']]['updateTag']==1) {
350
-		        $Scan->update_address_tag ($address_change[$k]['id'], 1, $address_change[$k]['state'], $change['lastSeenOld']);
349
+	        if ($address_change[$k]['state'] != 1 && $Scan->settings->updateTags == 1 && $Tools->address_types[$address_change[$k]['state']]['updateTag'] == 1) {
350
+		        $Scan->update_address_tag($address_change[$k]['id'], 1, $address_change[$k]['state'], $change['lastSeenOld']);
351 351
 		    }
352 352
         	// remove from change array
353 353
             unset ($address_change[$k]);
@@ -356,18 +356,18 @@  discard block
 block discarded – undo
356 356
     // remove
357 357
     else {
358 358
     	// check tag
359
-    	if ($change['lastSeenNew']!=NULL) {
359
+    	if ($change['lastSeenNew'] != NULL) {
360 360
 	        // update tag if not already online
361 361
 	        // tags have different indexes than script exit code is - 1=offline, 2=online
362
-	        if($address_change[$k]['state']!=2 && $Scan->settings->updateTags==1 && $Tools->address_types[$address_change[$k]['state']]['updateTag']==1) {
363
-		        $Scan->update_address_tag ($address_change[$k]['id'], 2, $address_change[$k]['state'], $change['lastSeenOld']);
362
+	        if ($address_change[$k]['state'] != 2 && $Scan->settings->updateTags == 1 && $Tools->address_types[$address_change[$k]['state']]['updateTag'] == 1) {
363
+		        $Scan->update_address_tag($address_change[$k]['id'], 2, $address_change[$k]['state'], $change['lastSeenOld']);
364 364
 	    	}
365 365
     	}
366 366
     	else {
367 367
     		// update tag if not already offline
368 368
 	        // tags have different indexes than script exit code is - 1=offline, 2=online
369
-	        if($address_change[$k]['state']!=1 && $Scan->settings->updateTags==1 && $Tools->address_types[$address_change[$k]['state']]['updateTag']==1) {
370
-		        $Scan->update_address_tag ($address_change[$k]['id'], 1, $address_change[$k]['state'], $change['lastSeenOld']);
369
+	        if ($address_change[$k]['state'] != 1 && $Scan->settings->updateTags == 1 && $Tools->address_types[$address_change[$k]['state']]['updateTag'] == 1) {
370
+		        $Scan->update_address_tag($address_change[$k]['id'], 1, $address_change[$k]['state'], $change['lastSeenOld']);
371 371
 		    }
372 372
     	}
373 373
 
@@ -376,24 +376,24 @@  discard block
 block discarded – undo
376 376
 }
377 377
 
378 378
 # update scan time
379
-$Scan->ping_update_scanagent_checktime (1, $nowdate);
379
+$Scan->ping_update_scanagent_checktime(1, $nowdate);
380 380
 
381 381
 
382 382
 # print change
383
-if($Scan->debugging)							{ print "\nAddress changes:\n----------\n"; print_r($address_change); }
383
+if ($Scan->debugging) { print "\nAddress changes:\n----------\n"; print_r($address_change); }
384 384
 
385 385
 # all done, mail diff?
386
-if(sizeof($address_change)>0 && $config['ping_check_send_mail']) {
386
+if (sizeof($address_change) > 0 && $config['ping_check_send_mail']) {
387 387
 
388 388
 	# remove old classes
389 389
 	unset($Database, $Subnets, $Addresses, $Tools, $Scan, $Result);
390 390
 
391 391
 	$Database 	= new Database_PDO;
392
-	$Subnets	= new Subnets ($Database);
393
-	$Addresses	= new Addresses ($Database);
394
-	$Tools		= new Tools ($Database);
395
-	$Scan		= new Scan ($Database);
396
-	$Result		= new Result();
392
+	$Subnets = new Subnets($Database);
393
+	$Addresses	= new Addresses($Database);
394
+	$Tools = new Tools($Database);
395
+	$Scan = new Scan($Database);
396
+	$Result = new Result();
397 397
 
398 398
 	// set exit flag to true
399 399
 	$Scan->ping_set_exit(true);
@@ -402,13 +402,13 @@  discard block
 block discarded – undo
402 402
 
403 403
 
404 404
 	# check for recipients
405
-	foreach($Tools->fetch_multiple_objects ("users", "role", "Administrator") as $admin) {
406
-		if($admin->mailNotify=="Yes") {
405
+	foreach ($Tools->fetch_multiple_objects("users", "role", "Administrator") as $admin) {
406
+		if ($admin->mailNotify == "Yes") {
407 407
 			$recepients[] = array("name"=>$admin->real_name, "email"=>$admin->email);
408 408
 		}
409 409
 	}
410 410
 	# none?
411
-	if(!isset($recepients))	{ die(); }
411
+	if (!isset($recepients)) { die(); }
412 412
 
413 413
 	# fake user object, needed for create_link
414 414
 	$User = new StdClass();
@@ -422,7 +422,7 @@  discard block
 block discarded – undo
422 422
 		$phpipam_mail = new phpipam_mail($Scan->settings, $mail_settings);
423 423
 
424 424
 		// set subject
425
-		$subject	= "phpIPAM IP state change ".$nowdate;
425
+		$subject = "phpIPAM IP state change ".$nowdate;
426 426
 
427 427
 		//html
428 428
 		$content[] = "<p style='margin-left:10px;'>$Subnets->mail_font_style <font style='font-size:16px;size:16px;'>phpIPAM host changes</font></font></p><br>";
@@ -441,9 +441,9 @@  discard block
 block discarded – undo
441 441
 		$content_plain[] = "phpIPAM host changes \r\n------------------------------";
442 442
 
443 443
 		//Changes
444
-		foreach($address_change as $change) {
444
+		foreach ($address_change as $change) {
445 445
 			//reformat statuses
446
-			if($change['oldStatus'] == 0) {
446
+			if ($change['oldStatus'] == 0) {
447 447
 				$oldStatus = "<font style='color:#04B486'>Online</font>";
448 448
 				$newStatus = "<font style='color:#DF0101'>Offline</font>";
449 449
 			}
@@ -453,28 +453,28 @@  discard block
 block discarded – undo
453 453
 			}
454 454
 
455 455
 			//set subnet
456
-			$subnet 	 = $Subnets->fetch_subnet(null, $change['subnetId']);
456
+			$subnet = $Subnets->fetch_subnet(null, $change['subnetId']);
457 457
 			//ago
458
-			if(is_null($change['lastSeen']) || $change['lastSeen']=="1970-01-01 00:00:01" || $change['lastSeen']=="0000-00-00 00:00:00") {
459
-				$ago	  = "never";
458
+			if (is_null($change['lastSeen']) || $change['lastSeen'] == "1970-01-01 00:00:01" || $change['lastSeen'] == "0000-00-00 00:00:00") {
459
+				$ago = "never";
460 460
 			} else {
461 461
 				$timeDiff = $now - strtotime($change['lastSeen']);
462 462
 
463 463
 	    		// reformat
464
-	    		$lastSeen = date("m/d H:i", strtotime($change['lastSeen']) );
465
-				$ago 	  = $lastSeen." (".$Result->sec2hms($timeDiff)." ago)";
464
+	    		$lastSeen = date("m/d H:i", strtotime($change['lastSeen']));
465
+				$ago = $lastSeen." (".$Result->sec2hms($timeDiff)." ago)";
466 466
 			}
467 467
 	        // desc
468
-			$change['description'] = strlen($change['description'])>0 ? "$Subnets->mail_font_style $change[description]</font>" : "$Subnets->mail_font_style / </font>";
468
+			$change['description'] = strlen($change['description']) > 0 ? "$Subnets->mail_font_style $change[description]</font>" : "$Subnets->mail_font_style / </font>";
469 469
 			// subnet desc
470
-			$subnet->description = strlen($subnet->description)>0 ? "$Subnets->mail_font_style $subnet->description</font>" : "$Subnets->mail_font_style / </font>";
470
+			$subnet->description = strlen($subnet->description) > 0 ? "$Subnets->mail_font_style $subnet->description</font>" : "$Subnets->mail_font_style / </font>";
471 471
 
472 472
 			//content
473 473
 			$content[] = "<tr>";
474
-			$content[] = "	<td style='padding:3px 8px;border:1px solid #ccc;'><a href='".rtrim(str_replace(BASE, "",$Scan->settings->siteURL), "/")."".create_link("subnets",$subnet->sectionId,$subnet->id)."'>$Subnets->mail_font_style_href ".$Subnets->transform_to_dotted($change['ip_addr'])."</font></a></td>";
474
+			$content[] = "	<td style='padding:3px 8px;border:1px solid #ccc;'><a href='".rtrim(str_replace(BASE, "", $Scan->settings->siteURL), "/")."".create_link("subnets", $subnet->sectionId, $subnet->id)."'>$Subnets->mail_font_style_href ".$Subnets->transform_to_dotted($change['ip_addr'])."</font></a></td>";
475 475
 			$content[] = "	<td style='padding:3px 8px;border:1px solid #ccc;'>$Subnets->mail_font_style $change[description]</font></td>";
476 476
 			$content[] = "	<td style='padding:3px 8px;border:1px solid #ccc;'>$Subnets->mail_font_style_href $change[hostname]</font></td>";
477
-			$content[] = "	<td style='padding:3px 8px;border:1px solid #ccc;'><a href='".rtrim(str_replace(BASE, "",$Scan->settings->siteURL), "/")."".create_link("subnets",$subnet->sectionId,$subnet->id)."'>$Subnets->mail_font_style_href ".$Subnets->transform_to_dotted($subnet->subnet)."/".$subnet->mask."</font></a>".$subnet->description."</td>";
477
+			$content[] = "	<td style='padding:3px 8px;border:1px solid #ccc;'><a href='".rtrim(str_replace(BASE, "", $Scan->settings->siteURL), "/")."".create_link("subnets", $subnet->sectionId, $subnet->id)."'>$Subnets->mail_font_style_href ".$Subnets->transform_to_dotted($subnet->subnet)."/".$subnet->mask."</font></a>".$subnet->description."</td>";
478 478
 			$content[] = "	<td style='padding:3px 8px;border:1px solid #ccc;'>$Subnets->mail_font_style $ago</td>";
479 479
 			$content[] = "	<td style='padding:3px 8px;border:1px solid #ccc;'>$Subnets->mail_font_style $oldStatus > $newStatus</td>";
480 480
 			$content[] = "</tr>";
@@ -487,12 +487,12 @@  discard block
 block discarded – undo
487 487
 
488 488
 
489 489
 		# set content
490
-		$content 		= $phpipam_mail->generate_message (implode("\r\n", $content));
491
-		$content_plain 	= implode("\r\n",$content_plain);
490
+		$content = $phpipam_mail->generate_message(implode("\r\n", $content));
491
+		$content_plain = implode("\r\n", $content_plain);
492 492
 
493 493
 		$phpipam_mail->Php_mailer->setFrom($mail_settings->mAdminMail, $mail_settings->mAdminName);
494 494
 		//add all admins to CC
495
-		foreach($recepients as $admin) {
495
+		foreach ($recepients as $admin) {
496 496
 			$phpipam_mail->Php_mailer->addAddress(addslashes($admin['email']), addslashes($admin['name']));
497 497
 		}
498 498
 		$phpipam_mail->Php_mailer->Subject = $subject;
Please login to merge, or discard this patch.
Braces   +8 added lines, -6 removed lines patch added patch discarded remove patch
@@ -52,8 +52,9 @@  discard block
 block discarded – undo
52 52
 // set address types array
53 53
 $Tools->get_addresses_types ();
54 54
 // change scan type?
55
-if(@$config['ping_check_method'])
56
-$Scan->reset_scan_method ($config['ping_check_method']);
55
+if(@$config['ping_check_method']) {
56
+    $Scan->reset_scan_method ($config['ping_check_method']);
57
+}
57 58
 
58 59
 // set ping statuses
59 60
 $statuses = explode(";", $Scan->settings->pingStatus);
@@ -96,7 +97,7 @@  discard block
 block discarded – undo
96 97
 
97 98
 		$subnet_addresses = $Addresses->fetch_subnet_addresses ($s->id);
98 99
 		//set array for fping
99
-		if($Scan->icmp_type=="fping")	{
100
+		if($Scan->icmp_type=="fping") {
100 101
 			$subnets[] = array(
101 102
 								"id"         =>$s->id,
102 103
 								"cidr"       =>$Subnets->transform_to_dotted($s->subnet)."/".$s->mask,
@@ -110,7 +111,7 @@  discard block
 block discarded – undo
110 111
 				//ignore excludePing
111 112
 				if($a->excludePing!=1) {
112 113
 					//create different array for fping
113
-					if($Scan->icmp_type=="fping")	{
114
+					if($Scan->icmp_type=="fping") {
114 115
 						$addresses2[$s->id][$a->id] = array(
115 116
 															"id"          =>$a->id,
116 117
 															"ip_addr"     =>$a->ip_addr,
@@ -335,7 +336,7 @@  discard block
 block discarded – undo
335 336
     // now offline, and diff > offline period, do checks
336 337
     elseif($change['lastSeenNew']==NULL && $deviceDiff >= (int) $statuses[1]) {
337 338
         // if not already reported
338
-        if ($deviceDiff <= ((int) $statuses[1] + $agentDiff))  {
339
+        if ($deviceDiff <= ((int) $statuses[1] + $agentDiff)) {
339 340
             $address_change[$k]['oldStatus'] = 0;
340 341
             $address_change[$k]['newStatus'] = 2;
341 342
 	        // update tag if not already offline
@@ -457,7 +458,8 @@  discard block
 block discarded – undo
457 458
 			//ago
458 459
 			if(is_null($change['lastSeen']) || $change['lastSeen']=="1970-01-01 00:00:01" || $change['lastSeen']=="0000-00-00 00:00:00") {
459 460
 				$ago	  = "never";
460
-			} else {
461
+			}
462
+			else {
461 463
 				$timeDiff = $now - strtotime($change['lastSeen']);
462 464
 
463 465
 	    		// reformat
Please login to merge, or discard this patch.
functions/scripts/remove_offline_addresses.php 2 patches
Indentation   +92 added lines, -92 removed lines patch added patch discarded remove patch
@@ -49,110 +49,110 @@
 block discarded – undo
49 49
 # fetch
50 50
 try { $offline_addresses = $Database->getObjectsQuery($query); }
51 51
 catch (Exception $e) {
52
-	$Result->show("danger", _("Error: ").$e->getMessage());
53
-	die();
52
+    $Result->show("danger", _("Error: ").$e->getMessage());
53
+    die();
54 54
 }
55 55
 
56 56
 # if none die, none to remove
57 57
 if (sizeof($offline_addresses)==0) {
58
-	die();
58
+    die();
59 59
 }
60 60
 # remove
61 61
 else {
62
-	foreach ($offline_addresses as $a) {
63
-		// save
64
-		$removed_addresses[] = $a;
65
-		// remove
66
-		$Addresses->modify_address ($a);
67
-	}
62
+    foreach ($offline_addresses as $a) {
63
+        // save
64
+        $removed_addresses[] = $a;
65
+        // remove
66
+        $Addresses->modify_address ($a);
67
+    }
68 68
 }
69 69
 
70 70
 
71 71
 # all done, mail diff?
72 72
 if(sizeof($removed_addresses)>0 && $config['removed_addresses_send_mail']) {
73
-	# settings
74
-	$Subnets->get_settings ();
75
-	# check for recipients
76
-	foreach($Subnets->fetch_multiple_objects ("users", "role", "Administrator") as $admin) {
77
-		if($admin->mailNotify=="Yes") {
78
-			$recepients[] = array("name"=>$admin->real_name, "email"=>$admin->email);
79
-		}
80
-	}
81
-	# none?
82
-	if(!isset($recepients))	{ die(); }
83
-
84
-	# fake user object, needed for create_link
85
-	$User = new StdClass();
86
-	# try to send
87
-	try {
88
-		# fetch mailer settings
89
-		$mail_settings = $Subnets->fetch_object("settingsMail", "id", 1);
90
-		# initialize mailer
91
-		$phpipam_mail = new phpipam_mail($Subnets->settings, $mail_settings);
92
-
93
-		// set subject
94
-		$subject	= "phpipam deleted offline addresses at ".$nowdate;
95
-
96
-		//html
97
-		$content[] = "<p style='margin-left:10px;'>$Subnets->mail_font_style <font style='font-size:16px;size:16px;'>phpipam removed inactive addresses at ".$nowdate."</font></font></p><br>";
98
-
99
-		$content[] = "<table style='margin-left:10px;margin-top:5px;width:auto;padding:0px;border-collapse:collapse;border:1px solid #ccc;'>";
100
-		$content[] = "<tr>";
101
-		$content[] = "	<th style='padding:3px 8px;border:1px solid #ccc;border-bottom:2px solid gray;white-space:nowrap;'>$Subnets->mail_font_style IP</font></th>";
102
-		$content[] = "	<th style='padding:3px 8px;border:1px solid #ccc;border-bottom:2px solid gray;'>$Subnets->mail_font_style Description</font></th>";
103
-		$content[] = "	<th style='padding:3px 8px;border:1px solid #ccc;border-bottom:2px solid gray;'>$Subnets->mail_font_style Hostname</font></th>";
104
-		$content[] = "	<th style='padding:3px 8px;border:1px solid #ccc;border-bottom:2px solid gray;'>$Subnets->mail_font_style Subnet</font></th>";
105
-		$content[] = "	<th style='padding:3px 8px;border:1px solid #ccc;border-bottom:2px solid gray;'>$Subnets->mail_font_style Last seen</font></th>";
106
-		$content[] = "</tr>";
107
-
108
-		//plain
109
-		$content_plain[] = "phpipam deleted offline addresses at ".$nowdate."\r\n------------------------------";
110
-
111
-		//Changes
112
-		foreach($removed_addresses as $change) {
113
-			// to array
114
-			$change = (array) $change;
115
-			//set subnet
116
-			$subnet = $Subnets->fetch_subnet(null, $change['subnetId']);
117
-
118
-	        // desc
119
-			$change['description'] = strlen($change['description'])>0 ? "$Subnets->mail_font_style $change[description]</font>" : "$Subnets->mail_font_style / </font>";
120
-			// subnet desc
121
-			$subnet->description = strlen($subnet->description)>0 ? "$Subnets->mail_font_style $subnet->description</font>" : "$Subnets->mail_font_style / </font>";
122
-
123
-			//content
124
-			$content[] = "<tr>";
125
-			$content[] = "	<td style='padding:3px 8px;border:1px solid #ccc;'>$Subnets->mail_font_style ".$Subnets->transform_to_dotted($change['ip_addr'])."</font></td>";
126
-			$content[] = "	<td style='padding:3px 8px;border:1px solid #ccc;'>$Subnets->mail_font_style $change[description]</font></td>";
127
-			$content[] = "	<td style='padding:3px 8px;border:1px solid #ccc;'>$Subnets->mail_font_style_href $change[hostname]</font></td>";
128
-			$content[] = "	<td style='padding:3px 8px;border:1px solid #ccc;'><a href='".rtrim(str_replace(BASE, "",$Subnets->settings->siteURL), "/")."".create_link("subnets",$subnet->sectionId,$subnet->id)."'>$Subnets->mail_font_style_href ".$Subnets->transform_to_dotted($subnet->subnet)."/".$subnet->mask."</font></a>".$subnet->description."</td>";
129
-			$content[] = "	<td style='padding:3px 8px;border:1px solid #ccc;'>$Subnets->mail_font_style $change[lastSeen]</td>";
130
-			$content[] = "</tr>";
131
-
132
-			//plain content
133
-			$content_plain[] = "\t * ".$Subnets->transform_to_dotted($change['ip_addr'])." (".$Subnets->transform_to_dotted($subnet->subnet)."/".$subnet->mask.")\r\n";
134
-		}
135
-		$content[] = "</table>";
136
-
137
-		# set content
138
-		$content 		= $phpipam_mail->generate_message (implode("\r\n", $content));
139
-		$content_plain 	= implode("\r\n",$content_plain);
140
-
141
-		$phpipam_mail->Php_mailer->setFrom($mail_settings->mAdminMail, $mail_settings->mAdminName);
142
-		//add all admins to CC
143
-		foreach($recepients as $admin) {
144
-			$phpipam_mail->Php_mailer->addAddress(addslashes($admin['email']), addslashes($admin['name']));
145
-		}
146
-		$phpipam_mail->Php_mailer->Subject = $subject;
147
-		$phpipam_mail->Php_mailer->msgHTML($content);
148
-		$phpipam_mail->Php_mailer->AltBody = $content_plain;
149
-		//send
150
-		$phpipam_mail->Php_mailer->send();
151
-	} catch (phpmailerException $e) {
152
-		$Result->show_cli("Mailer Error: ".$e->errorMessage(), true);
153
-	} catch (Exception $e) {
154
-		$Result->show_cli("Mailer Error: ".$e->getMessage(), true);
155
-	}
73
+    # settings
74
+    $Subnets->get_settings ();
75
+    # check for recipients
76
+    foreach($Subnets->fetch_multiple_objects ("users", "role", "Administrator") as $admin) {
77
+        if($admin->mailNotify=="Yes") {
78
+            $recepients[] = array("name"=>$admin->real_name, "email"=>$admin->email);
79
+        }
80
+    }
81
+    # none?
82
+    if(!isset($recepients))	{ die(); }
83
+
84
+    # fake user object, needed for create_link
85
+    $User = new StdClass();
86
+    # try to send
87
+    try {
88
+        # fetch mailer settings
89
+        $mail_settings = $Subnets->fetch_object("settingsMail", "id", 1);
90
+        # initialize mailer
91
+        $phpipam_mail = new phpipam_mail($Subnets->settings, $mail_settings);
92
+
93
+        // set subject
94
+        $subject	= "phpipam deleted offline addresses at ".$nowdate;
95
+
96
+        //html
97
+        $content[] = "<p style='margin-left:10px;'>$Subnets->mail_font_style <font style='font-size:16px;size:16px;'>phpipam removed inactive addresses at ".$nowdate."</font></font></p><br>";
98
+
99
+        $content[] = "<table style='margin-left:10px;margin-top:5px;width:auto;padding:0px;border-collapse:collapse;border:1px solid #ccc;'>";
100
+        $content[] = "<tr>";
101
+        $content[] = "	<th style='padding:3px 8px;border:1px solid #ccc;border-bottom:2px solid gray;white-space:nowrap;'>$Subnets->mail_font_style IP</font></th>";
102
+        $content[] = "	<th style='padding:3px 8px;border:1px solid #ccc;border-bottom:2px solid gray;'>$Subnets->mail_font_style Description</font></th>";
103
+        $content[] = "	<th style='padding:3px 8px;border:1px solid #ccc;border-bottom:2px solid gray;'>$Subnets->mail_font_style Hostname</font></th>";
104
+        $content[] = "	<th style='padding:3px 8px;border:1px solid #ccc;border-bottom:2px solid gray;'>$Subnets->mail_font_style Subnet</font></th>";
105
+        $content[] = "	<th style='padding:3px 8px;border:1px solid #ccc;border-bottom:2px solid gray;'>$Subnets->mail_font_style Last seen</font></th>";
106
+        $content[] = "</tr>";
107
+
108
+        //plain
109
+        $content_plain[] = "phpipam deleted offline addresses at ".$nowdate."\r\n------------------------------";
110
+
111
+        //Changes
112
+        foreach($removed_addresses as $change) {
113
+            // to array
114
+            $change = (array) $change;
115
+            //set subnet
116
+            $subnet = $Subnets->fetch_subnet(null, $change['subnetId']);
117
+
118
+            // desc
119
+            $change['description'] = strlen($change['description'])>0 ? "$Subnets->mail_font_style $change[description]</font>" : "$Subnets->mail_font_style / </font>";
120
+            // subnet desc
121
+            $subnet->description = strlen($subnet->description)>0 ? "$Subnets->mail_font_style $subnet->description</font>" : "$Subnets->mail_font_style / </font>";
122
+
123
+            //content
124
+            $content[] = "<tr>";
125
+            $content[] = "	<td style='padding:3px 8px;border:1px solid #ccc;'>$Subnets->mail_font_style ".$Subnets->transform_to_dotted($change['ip_addr'])."</font></td>";
126
+            $content[] = "	<td style='padding:3px 8px;border:1px solid #ccc;'>$Subnets->mail_font_style $change[description]</font></td>";
127
+            $content[] = "	<td style='padding:3px 8px;border:1px solid #ccc;'>$Subnets->mail_font_style_href $change[hostname]</font></td>";
128
+            $content[] = "	<td style='padding:3px 8px;border:1px solid #ccc;'><a href='".rtrim(str_replace(BASE, "",$Subnets->settings->siteURL), "/")."".create_link("subnets",$subnet->sectionId,$subnet->id)."'>$Subnets->mail_font_style_href ".$Subnets->transform_to_dotted($subnet->subnet)."/".$subnet->mask."</font></a>".$subnet->description."</td>";
129
+            $content[] = "	<td style='padding:3px 8px;border:1px solid #ccc;'>$Subnets->mail_font_style $change[lastSeen]</td>";
130
+            $content[] = "</tr>";
131
+
132
+            //plain content
133
+            $content_plain[] = "\t * ".$Subnets->transform_to_dotted($change['ip_addr'])." (".$Subnets->transform_to_dotted($subnet->subnet)."/".$subnet->mask.")\r\n";
134
+        }
135
+        $content[] = "</table>";
136
+
137
+        # set content
138
+        $content 		= $phpipam_mail->generate_message (implode("\r\n", $content));
139
+        $content_plain 	= implode("\r\n",$content_plain);
140
+
141
+        $phpipam_mail->Php_mailer->setFrom($mail_settings->mAdminMail, $mail_settings->mAdminName);
142
+        //add all admins to CC
143
+        foreach($recepients as $admin) {
144
+            $phpipam_mail->Php_mailer->addAddress(addslashes($admin['email']), addslashes($admin['name']));
145
+        }
146
+        $phpipam_mail->Php_mailer->Subject = $subject;
147
+        $phpipam_mail->Php_mailer->msgHTML($content);
148
+        $phpipam_mail->Php_mailer->AltBody = $content_plain;
149
+        //send
150
+        $phpipam_mail->Php_mailer->send();
151
+    } catch (phpmailerException $e) {
152
+        $Result->show_cli("Mailer Error: ".$e->errorMessage(), true);
153
+    } catch (Exception $e) {
154
+        $Result->show_cli("Mailer Error: ".$e->getMessage(), true);
155
+    }
156 156
 }
157 157
 
158 158
 ?>
Please login to merge, or discard this patch.
Spacing   +23 added lines, -23 removed lines patch added patch discarded remove patch
@@ -9,28 +9,28 @@  discard block
 block discarded – undo
9 9
  */
10 10
 
11 11
 # script can only be run from cli
12
-if(php_sapi_name()!="cli") 						{ die("This script can only be run from cli!"); }
12
+if (php_sapi_name() != "cli") { die("This script can only be run from cli!"); }
13 13
 
14 14
 # include required scripts
15
-require_once( dirname(__FILE__) . '/../functions.php' );
15
+require_once(dirname(__FILE__).'/../functions.php');
16 16
 
17 17
 # initialize objects
18 18
 $Database 	= new Database_PDO;
19
-$Addresses	= new Addresses ($Database);
20
-$Subnets	= new Subnets ($Database);
19
+$Addresses	= new Addresses($Database);
20
+$Subnets	= new Subnets($Database);
21 21
 $Result		= new Result();
22 22
 
23 23
 
24 24
 // response for mailing
25
-$removed_addresses = array();			// Array with differences, can be used to email to admins
25
+$removed_addresses = array(); // Array with differences, can be used to email to admins
26 26
 
27 27
 // if config is not set die
28
-if(!isset($config['removed_addresses_timelimit'])) { die("Please set timelimit for address removal!"); }
28
+if (!isset($config['removed_addresses_timelimit'])) { die("Please set timelimit for address removal!"); }
29 29
 
30 30
 // set now for whole script
31 31
 $now     = time();
32
-$nowdate = date ("Y-m-d H:i:s");
33
-$beforetime = date ("Y-m-d H:i:s", (time()-$config['removed_addresses_timelimit']));
32
+$nowdate = date("Y-m-d H:i:s");
33
+$beforetime = date("Y-m-d H:i:s", (time() - $config['removed_addresses_timelimit']));
34 34
 
35 35
 // set query to fetch addresses and belongign subnets
36 36
 $query = "select
@@ -54,7 +54,7 @@  discard block
 block discarded – undo
54 54
 }
55 55
 
56 56
 # if none die, none to remove
57
-if (sizeof($offline_addresses)==0) {
57
+if (sizeof($offline_addresses) == 0) {
58 58
 	die();
59 59
 }
60 60
 # remove
@@ -63,23 +63,23 @@  discard block
 block discarded – undo
63 63
 		// save
64 64
 		$removed_addresses[] = $a;
65 65
 		// remove
66
-		$Addresses->modify_address ($a);
66
+		$Addresses->modify_address($a);
67 67
 	}
68 68
 }
69 69
 
70 70
 
71 71
 # all done, mail diff?
72
-if(sizeof($removed_addresses)>0 && $config['removed_addresses_send_mail']) {
72
+if (sizeof($removed_addresses) > 0 && $config['removed_addresses_send_mail']) {
73 73
 	# settings
74
-	$Subnets->get_settings ();
74
+	$Subnets->get_settings();
75 75
 	# check for recipients
76
-	foreach($Subnets->fetch_multiple_objects ("users", "role", "Administrator") as $admin) {
77
-		if($admin->mailNotify=="Yes") {
76
+	foreach ($Subnets->fetch_multiple_objects("users", "role", "Administrator") as $admin) {
77
+		if ($admin->mailNotify == "Yes") {
78 78
 			$recepients[] = array("name"=>$admin->real_name, "email"=>$admin->email);
79 79
 		}
80 80
 	}
81 81
 	# none?
82
-	if(!isset($recepients))	{ die(); }
82
+	if (!isset($recepients)) { die(); }
83 83
 
84 84
 	# fake user object, needed for create_link
85 85
 	$User = new StdClass();
@@ -91,7 +91,7 @@  discard block
 block discarded – undo
91 91
 		$phpipam_mail = new phpipam_mail($Subnets->settings, $mail_settings);
92 92
 
93 93
 		// set subject
94
-		$subject	= "phpipam deleted offline addresses at ".$nowdate;
94
+		$subject = "phpipam deleted offline addresses at ".$nowdate;
95 95
 
96 96
 		//html
97 97
 		$content[] = "<p style='margin-left:10px;'>$Subnets->mail_font_style <font style='font-size:16px;size:16px;'>phpipam removed inactive addresses at ".$nowdate."</font></font></p><br>";
@@ -109,23 +109,23 @@  discard block
 block discarded – undo
109 109
 		$content_plain[] = "phpipam deleted offline addresses at ".$nowdate."\r\n------------------------------";
110 110
 
111 111
 		//Changes
112
-		foreach($removed_addresses as $change) {
112
+		foreach ($removed_addresses as $change) {
113 113
 			// to array
114 114
 			$change = (array) $change;
115 115
 			//set subnet
116 116
 			$subnet = $Subnets->fetch_subnet(null, $change['subnetId']);
117 117
 
118 118
 	        // desc
119
-			$change['description'] = strlen($change['description'])>0 ? "$Subnets->mail_font_style $change[description]</font>" : "$Subnets->mail_font_style / </font>";
119
+			$change['description'] = strlen($change['description']) > 0 ? "$Subnets->mail_font_style $change[description]</font>" : "$Subnets->mail_font_style / </font>";
120 120
 			// subnet desc
121
-			$subnet->description = strlen($subnet->description)>0 ? "$Subnets->mail_font_style $subnet->description</font>" : "$Subnets->mail_font_style / </font>";
121
+			$subnet->description = strlen($subnet->description) > 0 ? "$Subnets->mail_font_style $subnet->description</font>" : "$Subnets->mail_font_style / </font>";
122 122
 
123 123
 			//content
124 124
 			$content[] = "<tr>";
125 125
 			$content[] = "	<td style='padding:3px 8px;border:1px solid #ccc;'>$Subnets->mail_font_style ".$Subnets->transform_to_dotted($change['ip_addr'])."</font></td>";
126 126
 			$content[] = "	<td style='padding:3px 8px;border:1px solid #ccc;'>$Subnets->mail_font_style $change[description]</font></td>";
127 127
 			$content[] = "	<td style='padding:3px 8px;border:1px solid #ccc;'>$Subnets->mail_font_style_href $change[hostname]</font></td>";
128
-			$content[] = "	<td style='padding:3px 8px;border:1px solid #ccc;'><a href='".rtrim(str_replace(BASE, "",$Subnets->settings->siteURL), "/")."".create_link("subnets",$subnet->sectionId,$subnet->id)."'>$Subnets->mail_font_style_href ".$Subnets->transform_to_dotted($subnet->subnet)."/".$subnet->mask."</font></a>".$subnet->description."</td>";
128
+			$content[] = "	<td style='padding:3px 8px;border:1px solid #ccc;'><a href='".rtrim(str_replace(BASE, "", $Subnets->settings->siteURL), "/")."".create_link("subnets", $subnet->sectionId, $subnet->id)."'>$Subnets->mail_font_style_href ".$Subnets->transform_to_dotted($subnet->subnet)."/".$subnet->mask."</font></a>".$subnet->description."</td>";
129 129
 			$content[] = "	<td style='padding:3px 8px;border:1px solid #ccc;'>$Subnets->mail_font_style $change[lastSeen]</td>";
130 130
 			$content[] = "</tr>";
131 131
 
@@ -135,12 +135,12 @@  discard block
 block discarded – undo
135 135
 		$content[] = "</table>";
136 136
 
137 137
 		# set content
138
-		$content 		= $phpipam_mail->generate_message (implode("\r\n", $content));
139
-		$content_plain 	= implode("\r\n",$content_plain);
138
+		$content 		= $phpipam_mail->generate_message(implode("\r\n", $content));
139
+		$content_plain = implode("\r\n", $content_plain);
140 140
 
141 141
 		$phpipam_mail->Php_mailer->setFrom($mail_settings->mAdminMail, $mail_settings->mAdminName);
142 142
 		//add all admins to CC
143
-		foreach($recepients as $admin) {
143
+		foreach ($recepients as $admin) {
144 144
 			$phpipam_mail->Php_mailer->addAddress(addslashes($admin['email']), addslashes($admin['name']));
145 145
 		}
146 146
 		$phpipam_mail->Php_mailer->Subject = $subject;
Please login to merge, or discard this patch.
functions/classes/class.Log.php 2 patches
Indentation   +1823 added lines, -1823 removed lines patch added patch discarded remove patch
@@ -13,1525 +13,1525 @@  discard block
 block discarded – undo
13 13
 class Logging extends Common_functions {
14 14
 
15 15
 
16
-	/**
17
-	 * debugging flag
18
-	 *
19
-	 * (default value: false)
20
-	 *
21
-	 * @var bool
22
-	 * @access public
23
-	 */
24
-	public $debugging = false;
25
-
26
-	/**
27
-	 * log_type
28
-	 *
29
-	 * @var mixed
30
-	 * @access protected
31
-	 */
32
-	protected $log_type;
33
-
34
-	/**
35
-	 * log_command
36
-	 *
37
-	 * (default value: null)
38
-	 *
39
-	 * @var mixed
40
-	 * @access protected
41
-	 */
42
-	protected $log_command = null;
43
-
44
-	/**
45
-	 * log_details
46
-	 *
47
-	 * (default value: null)
48
-	 *
49
-	 * @var mixed
50
-	 * @access protected
51
-	 */
52
-	protected $log_details = null;
53
-
54
-	/**
55
-	 * Syslog facility
56
-	 *
57
-	 * @var mixed
58
-	 * @access protected
59
-	 */
60
-	protected $syslog_facility;
61
-
62
-	/**
63
-	 * syslog_priority
64
-	 *
65
-	 * @var mixed
66
-	 * @access protected
67
-	 */
68
-	protected $syslog_priority;
69
-
70
-	/**
71
-	 * log severity
72
-	 *
73
-	 *  0: informational
74
-	 *  1: warning
75
-	 *  2: error
76
-	 *
77
-	 * (default value: 0)
78
-	 *
79
-	 * @var int
80
-	 * @access protected
81
-	 */
82
-	protected $log_severity = 0;
83
-
84
-	/**
85
-	 * New object (changed)
86
-	 *
87
-	 * @var mixed
88
-	 * @access protected
89
-	 */
90
-	protected $object_new;
91
-
92
-	/**
93
-	 * Old object (before change)
94
-	 *
95
-	 * @var mixed
96
-	 * @access protected
97
-	 */
98
-	protected $object_old;
99
-
100
-	/**
101
-	 * Original Object (before logging modifications)
102
-	 *
103
-	 * @var mixed
104
-	 * @access protected
105
-	 */
106
-	protected $object_orig;
107
-
108
-	/**
109
-	 * object_type
110
-	 *
111
-	 * @var mixed
112
-	 * @access public
113
-	 */
114
-	public $object_type;
115
-
116
-	/**
117
-	 * Object action
118
-	 *
119
-	 *  add, edit, delete
120
-	 *
121
-	 * @var mixed
122
-	 * @access public
123
-	 */
124
-	public $object_action;
125
-
126
-	/**
127
-	 * Result - success, failure
128
-	 *
129
-	 * @var mixed
130
-	 * @access public
131
-	 */
132
-	public $object_result;
133
-
134
-	/**
135
-	 * mail_changelog
136
-	 *
137
-	 * @var mixed
138
-	 * @access public
139
-	 */
140
-	public $mail_changelog;
141
-
142
-	/**
143
-	 * log_username
144
-	 *
145
-	 * (default value: null)
146
-	 *
147
-	 * @var mixed
148
-	 * @access protected
149
-	 */
150
-	protected $log_username	= null;
151
-
152
-	/**
153
-	 * user details
154
-	 *
155
-	 * @var mixed
156
-	 * @access public
157
-	 */
158
-	public $user;
159
-
160
-	/**
161
-	 * id of user
162
-	 *
163
-	 * (default value: null)
164
-	 *
165
-	 * @var mixed
166
-	 * @access protected
167
-	 */
168
-	protected $user_id	= null;
169
-
170
-	/**
171
-	 * Changelog keys for nicer display fo changelog
172
-	 *
173
-	 * @var mixed
174
-	 * @access protected
175
-	 */
176
-	public $changelog_keys = array(
177
-    	"section" => array(
178
-						"id"             => "index",
179
-						"name"           => "Subnet name",
180
-						"description"    => "Description",
181
-						"masterSection"  => "Parent section index",
182
-						"strictMode"     => "Enforce strict checks",
183
-						"subnetOrdering" => "Order of subnets",
184
-						"order"          => "Order of display",
185
-						"showVLAN"       => "Show VLANs in side menu",
186
-						"showVRF"        => "Show VRF in side menu"
187
-    	),
188
-    	"subnet" => array(
189
-						"id"                    => "Subnet id",
190
-						"subnet"                => "Subnet",
191
-						"masterSubnetId"        => "Master subnet",
192
-						"mask"                  => "Netmask",
193
-						"sectionId"             => "Section",
194
-						"description"           => "Description",
195
-						"firewallAddressObject" => "Firewall object index",
196
-						"vrfId"                 => "VRF",
197
-						"vlanId"                => "VLAN",
198
-						"showName"              => "Show name instead of subnet",
199
-						"device"                => "Device",
200
-						"pingSubnet"            => "ICMP check for online hosts",
201
-						"discoverSubnet"        => "Discover new hosts for this subnet",
202
-						"allowRequests"         => "Allow IP requests for subnet",
203
-						"DNSrecursive"          => "Create recursive PowerDNS records",
204
-						"DNSrecords"            => "Show PowerDNS records",
205
-						"nameserverId"          => "Nameserver",
206
-						"scanAgent"             => "Scan agent index",
207
-						"isFolder"              => "Object is folder",
208
-						"isFull"                => "Subnet is marked as full",
209
-						"state"                 => "Subnet state index",
210
-						"NAT"                   => "NAT object index",
211
-						"threshold"             => "Usage alert threshold",
212
-						"linked_subnet"         => "Linked IPv6 subnet",
213
-						"location"              => "Subnet location",
214
-						"lastScan"              => "Last scan date"
215
-    	            ),
216
-    	"folder" => array(
217
-						"id"             => "Folder id",
218
-						"masterSubnetId" => "Master folder index",
219
-						"sectionId"      => "Section index",
220
-						"description"    => "Description",
221
-						"isFolder"       => "Object is folder"
222
-    	            ),
16
+    /**
17
+     * debugging flag
18
+     *
19
+     * (default value: false)
20
+     *
21
+     * @var bool
22
+     * @access public
23
+     */
24
+    public $debugging = false;
25
+
26
+    /**
27
+     * log_type
28
+     *
29
+     * @var mixed
30
+     * @access protected
31
+     */
32
+    protected $log_type;
33
+
34
+    /**
35
+     * log_command
36
+     *
37
+     * (default value: null)
38
+     *
39
+     * @var mixed
40
+     * @access protected
41
+     */
42
+    protected $log_command = null;
43
+
44
+    /**
45
+     * log_details
46
+     *
47
+     * (default value: null)
48
+     *
49
+     * @var mixed
50
+     * @access protected
51
+     */
52
+    protected $log_details = null;
53
+
54
+    /**
55
+     * Syslog facility
56
+     *
57
+     * @var mixed
58
+     * @access protected
59
+     */
60
+    protected $syslog_facility;
61
+
62
+    /**
63
+     * syslog_priority
64
+     *
65
+     * @var mixed
66
+     * @access protected
67
+     */
68
+    protected $syslog_priority;
69
+
70
+    /**
71
+     * log severity
72
+     *
73
+     *  0: informational
74
+     *  1: warning
75
+     *  2: error
76
+     *
77
+     * (default value: 0)
78
+     *
79
+     * @var int
80
+     * @access protected
81
+     */
82
+    protected $log_severity = 0;
83
+
84
+    /**
85
+     * New object (changed)
86
+     *
87
+     * @var mixed
88
+     * @access protected
89
+     */
90
+    protected $object_new;
91
+
92
+    /**
93
+     * Old object (before change)
94
+     *
95
+     * @var mixed
96
+     * @access protected
97
+     */
98
+    protected $object_old;
99
+
100
+    /**
101
+     * Original Object (before logging modifications)
102
+     *
103
+     * @var mixed
104
+     * @access protected
105
+     */
106
+    protected $object_orig;
107
+
108
+    /**
109
+     * object_type
110
+     *
111
+     * @var mixed
112
+     * @access public
113
+     */
114
+    public $object_type;
115
+
116
+    /**
117
+     * Object action
118
+     *
119
+     *  add, edit, delete
120
+     *
121
+     * @var mixed
122
+     * @access public
123
+     */
124
+    public $object_action;
125
+
126
+    /**
127
+     * Result - success, failure
128
+     *
129
+     * @var mixed
130
+     * @access public
131
+     */
132
+    public $object_result;
133
+
134
+    /**
135
+     * mail_changelog
136
+     *
137
+     * @var mixed
138
+     * @access public
139
+     */
140
+    public $mail_changelog;
141
+
142
+    /**
143
+     * log_username
144
+     *
145
+     * (default value: null)
146
+     *
147
+     * @var mixed
148
+     * @access protected
149
+     */
150
+    protected $log_username	= null;
151
+
152
+    /**
153
+     * user details
154
+     *
155
+     * @var mixed
156
+     * @access public
157
+     */
158
+    public $user;
159
+
160
+    /**
161
+     * id of user
162
+     *
163
+     * (default value: null)
164
+     *
165
+     * @var mixed
166
+     * @access protected
167
+     */
168
+    protected $user_id	= null;
169
+
170
+    /**
171
+     * Changelog keys for nicer display fo changelog
172
+     *
173
+     * @var mixed
174
+     * @access protected
175
+     */
176
+    public $changelog_keys = array(
177
+        "section" => array(
178
+                        "id"             => "index",
179
+                        "name"           => "Subnet name",
180
+                        "description"    => "Description",
181
+                        "masterSection"  => "Parent section index",
182
+                        "strictMode"     => "Enforce strict checks",
183
+                        "subnetOrdering" => "Order of subnets",
184
+                        "order"          => "Order of display",
185
+                        "showVLAN"       => "Show VLANs in side menu",
186
+                        "showVRF"        => "Show VRF in side menu"
187
+        ),
188
+        "subnet" => array(
189
+                        "id"                    => "Subnet id",
190
+                        "subnet"                => "Subnet",
191
+                        "masterSubnetId"        => "Master subnet",
192
+                        "mask"                  => "Netmask",
193
+                        "sectionId"             => "Section",
194
+                        "description"           => "Description",
195
+                        "firewallAddressObject" => "Firewall object index",
196
+                        "vrfId"                 => "VRF",
197
+                        "vlanId"                => "VLAN",
198
+                        "showName"              => "Show name instead of subnet",
199
+                        "device"                => "Device",
200
+                        "pingSubnet"            => "ICMP check for online hosts",
201
+                        "discoverSubnet"        => "Discover new hosts for this subnet",
202
+                        "allowRequests"         => "Allow IP requests for subnet",
203
+                        "DNSrecursive"          => "Create recursive PowerDNS records",
204
+                        "DNSrecords"            => "Show PowerDNS records",
205
+                        "nameserverId"          => "Nameserver",
206
+                        "scanAgent"             => "Scan agent index",
207
+                        "isFolder"              => "Object is folder",
208
+                        "isFull"                => "Subnet is marked as full",
209
+                        "state"                 => "Subnet state index",
210
+                        "NAT"                   => "NAT object index",
211
+                        "threshold"             => "Usage alert threshold",
212
+                        "linked_subnet"         => "Linked IPv6 subnet",
213
+                        "location"              => "Subnet location",
214
+                        "lastScan"              => "Last scan date"
215
+                    ),
216
+        "folder" => array(
217
+                        "id"             => "Folder id",
218
+                        "masterSubnetId" => "Master folder index",
219
+                        "sectionId"      => "Section index",
220
+                        "description"    => "Description",
221
+                        "isFolder"       => "Object is folder"
222
+                    ),
223 223
         "address" => array(
224
-						"id"                    => "Address id",
225
-						"subnetId"              => "Subnet",
226
-						"ip_addr"               => "IP address",
227
-						"is_gayeway"            => "Gateway",
228
-						"description"           => "Description",
229
-						"hostname"              => "Hostname",
230
-						"mac"                   => "MAC address",
231
-						"owner"                 => "Address owner",
232
-						"state"                 => "Address state index",
233
-						"switch"                => "Device",
234
-						"port"                  => "Port",
235
-						"note"                  => "Note",
236
-						"lastSeen"              => "Device last online",
237
-						"excludePing"           => "Exclude from ICMP check",
238
-						"PTRignore"             => "Dont create PTR records",
239
-						"PTR"                   => "PTR object index",
240
-						"NAT"                   => "NAT object index",
241
-						"firewallAddressObject" => "Firewall object index",
242
-						"is_gateway"            => "Address is subnet gateway",
243
-						"location"              => "Address location",
244
-						"location_item"			=> "Address location",
245
-						"section"				=> "Section"
224
+                        "id"                    => "Address id",
225
+                        "subnetId"              => "Subnet",
226
+                        "ip_addr"               => "IP address",
227
+                        "is_gayeway"            => "Gateway",
228
+                        "description"           => "Description",
229
+                        "hostname"              => "Hostname",
230
+                        "mac"                   => "MAC address",
231
+                        "owner"                 => "Address owner",
232
+                        "state"                 => "Address state index",
233
+                        "switch"                => "Device",
234
+                        "port"                  => "Port",
235
+                        "note"                  => "Note",
236
+                        "lastSeen"              => "Device last online",
237
+                        "excludePing"           => "Exclude from ICMP check",
238
+                        "PTRignore"             => "Dont create PTR records",
239
+                        "PTR"                   => "PTR object index",
240
+                        "NAT"                   => "NAT object index",
241
+                        "firewallAddressObject" => "Firewall object index",
242
+                        "is_gateway"            => "Address is subnet gateway",
243
+                        "location"              => "Address location",
244
+                        "location_item"			=> "Address location",
245
+                        "section"				=> "Section"
246 246
                     )
247
-	);
248
-
249
-	/**
250
-	 * Database object
251
-	 *
252
-	 * @var mixed
253
-	 * @access protected
254
-	 */
255
-	protected $Database;
256
-
257
-	/**
258
-	 * Result object
259
-	 *
260
-	 * @var mixed
261
-	 * @access public
262
-	 */
263
-	public $Result;
264
-
265
-	/**
266
-	 * Addresses object
267
-	 *
268
-	 * @var mixed
269
-	 * @access protected
270
-	 */
271
-	protected $Addresses;
272
-
273
-	/**
274
-	 * Sections object
275
-	 *
276
-	 * @var mixed
277
-	 * @access protected
278
-	 */
279
-	protected $Sections;
280
-
281
-	/**
282
-	 * Subnets object
283
-	 *
284
-	 * @var mixed
285
-	 * @access protected
286
-	 */
287
-	protected $Subnets;
288
-
289
-	/**
290
-	 * Tools object
291
-	 *
292
-	 * @var mixed
293
-	 * @access protected
294
-	 */
295
-	protected $Tools;
296
-
297
-	/**
298
-	 * settings
299
-	 *
300
-	 * @var mixed
301
-	 * @access public
302
-	 */
303
-	public $settings;
304
-
305
-
306
-
307
-
308
-
309
-	/**
310
-	 * __construct function.
311
-	 *
312
-	 * @access public
313
-	 * @param Database_PDO $database
314
-	 * @param mixed $settings (default: null)
315
-	 */
316
-	public function __construct (Database_PDO $database, $settings = null) {
317
-		# Save database object
318
-		$this->Database = $database;
319
-		# Result
320
-		$this->Result = new Result ();
321
-		# User
322
-		$this->log_username = @$_SESSION['ipamusername'];
323
-
324
-		# settings
325
-		if ($settings===null || $settings===false) {
326
-			$this->get_settings(); #assigns $this->settings internally
327
-		}
328
-		else {
329
-			$this->settings = (object) $settings;
330
-		}
331
-		# debugging
332
-		$this->set_debugging();
333
-		# set log type
334
-		$this->set_log_type ();
335
-	}
336
-
337
-
338
-
339
-
340
-
341
-
342
-	/**
343
-	 * Sets log type based on phpipam settings
344
-	 *
345
-	 *	available options:
346
-	 *		Database (default)
347
-	 *		syslog
348
-	 *
349
-	 * @access private
350
-	 * @return void
351
-	 */
352
-	private function set_log_type () {
353
-		# check settings
354
-		$this->log_type = $this->settings->log;
355
-	}
356
-
357
-	/**
358
-	 * Gets id of active user
359
-	 *
360
-	 * @access private
361
-	 * @return void
362
-	 */
363
-	private function get_active_user_id () {
364
-		# cache
365
-		if ($this->user_id===null) {
366
-			# null
367
-			$user_id = null;
368
-			if (!isset($_SESSION['ipamusername'])) {
369
-				// when API calls subnet_create we get:
370
-				// Error: SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'cuser' cannot be null
371
-				// so let's get a user_id
372
-				if (array_key_exists("HTTP_PHPIPAM_TOKEN", $_SERVER)) {
373
-					$admin = new Admin($this->Database, False);
374
-					$token = $admin->fetch_object ("users", "token", $_SERVER['HTTP_PHPIPAM_TOKEN']);
375
-					if ($token === False) {
376
-						$this->user_id = null;
377
-					}
378
-					else {
379
-						$user_id = $token;
380
-					}
381
-				}
382
-				else {
383
-					$this->user_id = null;
384
-				}
385
-			}
386
-			else {
387
-				try { $user_id = $this->Database->getObjectQuery("select * from `users` where `username` = ? limit 1", array($_SESSION['ipamusername'])); }
388
-				catch (Exception $e) { $this->Result->show("danger", _("Database error: ").$e->getMessage()); }
389
-			}
390
-			# save id
391
-			$this->user_id = $user_id->id;
392
-			# save user
393
-			$this->user = $user_id;
394
-		}
395
-	}
396
-
397
-
398
-
399
-
400
-
401
-
402
-	/**
403
-	 * write log function
404
-	 *
405
-	 * @access public
406
-	 * @param mixed $command
407
-	 * @param mixed $details (default: NULL)
408
-	 * @param int $severity (default: 0)
409
-	 * @param mixed $username (default: NULL)
410
-	 * @return void
411
-	 */
412
-	public function write ($command, $details = NULL, $severity = 0, $username = null) {
413
-		// save provided values
414
-		$this->log_command = $command;
415
-		$this->log_details = $details;
416
-		$this->log_severity = $severity;
417
-		$this->log_username	= $username===null ? $this->log_username : $username;
418
-
419
-		// validate
420
-		!is_null($this->log_command) ? : $this->Result->show("danger", _("Invalid log command"));
421
-
422
-		// execute
423
-		if ($this->log_type == "syslog")	{ $this->syslog_write (); }
424
-		elseif ($this->log_type == "both")	{ $this->database_write_log (); $this->syslog_write (); }
425
-		else								{ $this->database_write_log (); }
426
-	}
427
-
428
-
429
-
430
-
431
-
432
-
433
-	/**
434
-	 *	@syslog log methods
435
-	 *	--------------------------------
436
-	 */
437
-
438
-	/**
439
-	 * Generates new syslog message
440
-	 *
441
-	 *		# > syslogd example:
442
-	 *
443
-	 *		# phpipam syslog messages setup
444
-	 *		# user.alert;user.warning;user.debug            /var/log/messages
445
-	 *		auth.alert;auth.warning;auth.debug              /var/log/auth.log
446
-	 *
447
-	 *		# log all phpipam messages
448
-	 *		!phpipam
449
-	 *		*.*                                             /var/log/phpipam.log
450
-	 *		!*
451
-	 *
452
-	 *		# changelog
453
-	 *		!phpipam-changelog
454
-	 *		*.*                                             /var/log/phpipam-changelog.log
455
-	 *		!*
456
-	 *
457
-	 *		# > rysylog example
458
-	 *		auth.alert;auth.warning;auth.debug              /var/log/auth.log
459
-	 *		if $programname == 'phpipam' then /var/log/phpipam.log
460
-	 *		if $programname == 'phpipam-changelog' then /var/log/phpipam-changelog.log
461
-	 *
462
-	 * @access private
463
-	 * @return void
464
-	 */
465
-	private function syslog_write () {
466
-		# set facility
467
-		$this->syslog_set_facility ();
468
-		# set priority
469
-		$this->syslog_set_priority ();
470
-		# format details
471
-		$this->syslog_format_details ();
472
-
473
-		# add username if present
474
-		$username = $this->log_username!==null ? $this->log_username." | " : "";
475
-
476
-		# open syslog and write log
477
-		openlog('phpipam', LOG_NDELAY | LOG_PID, $this->syslog_facility);
478
-		syslog($this->syslog_priority, $_SERVER['REMOTE_ADDR']." | ".$username.$this->log_command." | ".$this->log_details);
479
-
480
-		# close
481
-		closelog();
482
-	}
483
-
484
-	/**
485
-	 * Sets facility for syslog
486
-	 *
487
-	 * @access private
488
-	 * @return void
489
-	 */
490
-	private function syslog_set_facility () {
491
-		# for windows we can only use LOG_USER
492
-		if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN')		{ $facility = "LOG_USER"; }
493
-		else {
494
-			//login, logout
495
-			if (strpos($this->log_command, "login")>0 ||
496
-				strpos($this->log_command, "logged out")>0) { $facility = "LOG_AUTH"; }
497
-			else 											{ $facility = "LOG_USER"; }
498
-		}
499
-		# save
500
-		$this->syslog_facility = constant($facility);
501
-	}
502
-
503
-	/**
504
-	 * Sets priority
505
-	 *
506
-	 * @access private
507
-	 * @return void
508
-	 */
509
-	private function syslog_set_priority () {
510
-    	// init
511
-    	$priorities = array();
512
-		# definitions
513
-		$priorities[] = "LOG_EMERG";
514
-		$priorities[] = "LOG_ALERT";
515
-		$priorities[] = "LOG_CRIT";
516
-		$priorities[] = "LOG_ERR";
517
-		$priorities[] = "LOG_WARNING";
518
-		$priorities[] = "LOG_NOTICE";
519
-		$priorities[] = "LOG_INFO";
520
-		$priorities[] = "LOG_DEBUG";
521
-		# set
522
-		if ($this->log_severity == "2")		{ $priority = "LOG_ALERT"; }
523
-		elseif ($this->log_severity == "1")	{ $priority = "LOG_WARNING"; }
524
-		else								{ $priority = "LOG_DEBUG"; }
525
-		# set
526
-		$this->syslog_priority = constant($priority);
527
-	}
528
-
529
-	/**
530
-	 * Reformat syslog details
531
-	 *
532
-	 * @access private
533
-	 * @return void
534
-	 */
535
-	private function syslog_format_details () {
536
-		// replace <br>
537
-		$this->log_details = str_replace("<br>", ",",$this->log_details);
538
-		$this->log_details = str_replace("<hr>", ",",$this->log_details);
539
-		// replace spaces
540
-		$this->log_details = trim($this->log_details, ",");
541
-	}
542
-
543
-	/**
544
-	 * Writes changelog to syslog
545
-	 *
546
-	 * @access private
547
-	 * @param mixed $changelog
548
-	 * @return void
549
-	 */
550
-	private function syslog_write_changelog ($changelog) {
551
-		# fetch user id
552
-		$this->get_active_user_id ();
553
-		# set update id based on action
554
-		if ($this->object_action=="add")	{ $obj_id = $this->object_new['id']; }
555
-		else								{ $obj_id = $this->object_old['id']; }
556
-
557
-		# format
558
-		$changelog = str_replace("<br>", ",",$changelog);
559
-		$changelog = str_replace("<hr>", ",",$changelog);
560
-
561
-		# formulate
562
-		$log = array();
247
+    );
248
+
249
+    /**
250
+     * Database object
251
+     *
252
+     * @var mixed
253
+     * @access protected
254
+     */
255
+    protected $Database;
256
+
257
+    /**
258
+     * Result object
259
+     *
260
+     * @var mixed
261
+     * @access public
262
+     */
263
+    public $Result;
264
+
265
+    /**
266
+     * Addresses object
267
+     *
268
+     * @var mixed
269
+     * @access protected
270
+     */
271
+    protected $Addresses;
272
+
273
+    /**
274
+     * Sections object
275
+     *
276
+     * @var mixed
277
+     * @access protected
278
+     */
279
+    protected $Sections;
280
+
281
+    /**
282
+     * Subnets object
283
+     *
284
+     * @var mixed
285
+     * @access protected
286
+     */
287
+    protected $Subnets;
288
+
289
+    /**
290
+     * Tools object
291
+     *
292
+     * @var mixed
293
+     * @access protected
294
+     */
295
+    protected $Tools;
296
+
297
+    /**
298
+     * settings
299
+     *
300
+     * @var mixed
301
+     * @access public
302
+     */
303
+    public $settings;
304
+
305
+
306
+
307
+
308
+
309
+    /**
310
+     * __construct function.
311
+     *
312
+     * @access public
313
+     * @param Database_PDO $database
314
+     * @param mixed $settings (default: null)
315
+     */
316
+    public function __construct (Database_PDO $database, $settings = null) {
317
+        # Save database object
318
+        $this->Database = $database;
319
+        # Result
320
+        $this->Result = new Result ();
321
+        # User
322
+        $this->log_username = @$_SESSION['ipamusername'];
323
+
324
+        # settings
325
+        if ($settings===null || $settings===false) {
326
+            $this->get_settings(); #assigns $this->settings internally
327
+        }
328
+        else {
329
+            $this->settings = (object) $settings;
330
+        }
331
+        # debugging
332
+        $this->set_debugging();
333
+        # set log type
334
+        $this->set_log_type ();
335
+    }
336
+
337
+
338
+
339
+
340
+
341
+
342
+    /**
343
+     * Sets log type based on phpipam settings
344
+     *
345
+     *	available options:
346
+     *		Database (default)
347
+     *		syslog
348
+     *
349
+     * @access private
350
+     * @return void
351
+     */
352
+    private function set_log_type () {
353
+        # check settings
354
+        $this->log_type = $this->settings->log;
355
+    }
356
+
357
+    /**
358
+     * Gets id of active user
359
+     *
360
+     * @access private
361
+     * @return void
362
+     */
363
+    private function get_active_user_id () {
364
+        # cache
365
+        if ($this->user_id===null) {
366
+            # null
367
+            $user_id = null;
368
+            if (!isset($_SESSION['ipamusername'])) {
369
+                // when API calls subnet_create we get:
370
+                // Error: SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'cuser' cannot be null
371
+                // so let's get a user_id
372
+                if (array_key_exists("HTTP_PHPIPAM_TOKEN", $_SERVER)) {
373
+                    $admin = new Admin($this->Database, False);
374
+                    $token = $admin->fetch_object ("users", "token", $_SERVER['HTTP_PHPIPAM_TOKEN']);
375
+                    if ($token === False) {
376
+                        $this->user_id = null;
377
+                    }
378
+                    else {
379
+                        $user_id = $token;
380
+                    }
381
+                }
382
+                else {
383
+                    $this->user_id = null;
384
+                }
385
+            }
386
+            else {
387
+                try { $user_id = $this->Database->getObjectQuery("select * from `users` where `username` = ? limit 1", array($_SESSION['ipamusername'])); }
388
+                catch (Exception $e) { $this->Result->show("danger", _("Database error: ").$e->getMessage()); }
389
+            }
390
+            # save id
391
+            $this->user_id = $user_id->id;
392
+            # save user
393
+            $this->user = $user_id;
394
+        }
395
+    }
396
+
397
+
398
+
399
+
400
+
401
+
402
+    /**
403
+     * write log function
404
+     *
405
+     * @access public
406
+     * @param mixed $command
407
+     * @param mixed $details (default: NULL)
408
+     * @param int $severity (default: 0)
409
+     * @param mixed $username (default: NULL)
410
+     * @return void
411
+     */
412
+    public function write ($command, $details = NULL, $severity = 0, $username = null) {
413
+        // save provided values
414
+        $this->log_command = $command;
415
+        $this->log_details = $details;
416
+        $this->log_severity = $severity;
417
+        $this->log_username	= $username===null ? $this->log_username : $username;
418
+
419
+        // validate
420
+        !is_null($this->log_command) ? : $this->Result->show("danger", _("Invalid log command"));
421
+
422
+        // execute
423
+        if ($this->log_type == "syslog")	{ $this->syslog_write (); }
424
+        elseif ($this->log_type == "both")	{ $this->database_write_log (); $this->syslog_write (); }
425
+        else								{ $this->database_write_log (); }
426
+    }
427
+
428
+
429
+
430
+
431
+
432
+
433
+    /**
434
+     *	@syslog log methods
435
+     *	--------------------------------
436
+     */
437
+
438
+    /**
439
+     * Generates new syslog message
440
+     *
441
+     *		# > syslogd example:
442
+     *
443
+     *		# phpipam syslog messages setup
444
+     *		# user.alert;user.warning;user.debug            /var/log/messages
445
+     *		auth.alert;auth.warning;auth.debug              /var/log/auth.log
446
+     *
447
+     *		# log all phpipam messages
448
+     *		!phpipam
449
+     *		*.*                                             /var/log/phpipam.log
450
+     *		!*
451
+     *
452
+     *		# changelog
453
+     *		!phpipam-changelog
454
+     *		*.*                                             /var/log/phpipam-changelog.log
455
+     *		!*
456
+     *
457
+     *		# > rysylog example
458
+     *		auth.alert;auth.warning;auth.debug              /var/log/auth.log
459
+     *		if $programname == 'phpipam' then /var/log/phpipam.log
460
+     *		if $programname == 'phpipam-changelog' then /var/log/phpipam-changelog.log
461
+     *
462
+     * @access private
463
+     * @return void
464
+     */
465
+    private function syslog_write () {
466
+        # set facility
467
+        $this->syslog_set_facility ();
468
+        # set priority
469
+        $this->syslog_set_priority ();
470
+        # format details
471
+        $this->syslog_format_details ();
472
+
473
+        # add username if present
474
+        $username = $this->log_username!==null ? $this->log_username." | " : "";
475
+
476
+        # open syslog and write log
477
+        openlog('phpipam', LOG_NDELAY | LOG_PID, $this->syslog_facility);
478
+        syslog($this->syslog_priority, $_SERVER['REMOTE_ADDR']." | ".$username.$this->log_command." | ".$this->log_details);
479
+
480
+        # close
481
+        closelog();
482
+    }
483
+
484
+    /**
485
+     * Sets facility for syslog
486
+     *
487
+     * @access private
488
+     * @return void
489
+     */
490
+    private function syslog_set_facility () {
491
+        # for windows we can only use LOG_USER
492
+        if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN')		{ $facility = "LOG_USER"; }
493
+        else {
494
+            //login, logout
495
+            if (strpos($this->log_command, "login")>0 ||
496
+                strpos($this->log_command, "logged out")>0) { $facility = "LOG_AUTH"; }
497
+            else 											{ $facility = "LOG_USER"; }
498
+        }
499
+        # save
500
+        $this->syslog_facility = constant($facility);
501
+    }
502
+
503
+    /**
504
+     * Sets priority
505
+     *
506
+     * @access private
507
+     * @return void
508
+     */
509
+    private function syslog_set_priority () {
510
+        // init
511
+        $priorities = array();
512
+        # definitions
513
+        $priorities[] = "LOG_EMERG";
514
+        $priorities[] = "LOG_ALERT";
515
+        $priorities[] = "LOG_CRIT";
516
+        $priorities[] = "LOG_ERR";
517
+        $priorities[] = "LOG_WARNING";
518
+        $priorities[] = "LOG_NOTICE";
519
+        $priorities[] = "LOG_INFO";
520
+        $priorities[] = "LOG_DEBUG";
521
+        # set
522
+        if ($this->log_severity == "2")		{ $priority = "LOG_ALERT"; }
523
+        elseif ($this->log_severity == "1")	{ $priority = "LOG_WARNING"; }
524
+        else								{ $priority = "LOG_DEBUG"; }
525
+        # set
526
+        $this->syslog_priority = constant($priority);
527
+    }
528
+
529
+    /**
530
+     * Reformat syslog details
531
+     *
532
+     * @access private
533
+     * @return void
534
+     */
535
+    private function syslog_format_details () {
536
+        // replace <br>
537
+        $this->log_details = str_replace("<br>", ",",$this->log_details);
538
+        $this->log_details = str_replace("<hr>", ",",$this->log_details);
539
+        // replace spaces
540
+        $this->log_details = trim($this->log_details, ",");
541
+    }
542
+
543
+    /**
544
+     * Writes changelog to syslog
545
+     *
546
+     * @access private
547
+     * @param mixed $changelog
548
+     * @return void
549
+     */
550
+    private function syslog_write_changelog ($changelog) {
551
+        # fetch user id
552
+        $this->get_active_user_id ();
553
+        # set update id based on action
554
+        if ($this->object_action=="add")	{ $obj_id = $this->object_new['id']; }
555
+        else								{ $obj_id = $this->object_old['id']; }
556
+
557
+        # format
558
+        $changelog = str_replace("<br>", ",",$changelog);
559
+        $changelog = str_replace("<hr>", ",",$changelog);
560
+
561
+        # formulate
562
+        $log = array();
563 563
         if(isset($changelog)) {
564 564
             if (is_array($changelog)) {
565
-        		foreach($changelog as $k=>$l) {
566
-    	    		$log[] = "$k: $l";
567
-    		    }
568
-		    }
569
-
570
-    		# open syslog and write log
571
-    		openlog('phpipam-changelog', LOG_NDELAY | LOG_PID, LOG_USER);
572
-    		syslog(LOG_DEBUG, "changelog | $this->log_username | $this->object_type | $obj_id | $this->object_action | ".date("Y-m-d H:i:s")." | ".implode(", ",$log));
573
-    		# close
574
-    		closelog();
575
-        }
576
-	}
577
-
578
-
579
-
580
-
581
-
582
-
583
-
584
-
585
-
586
-
587
-
588
-	/**
589
-	 *	@database log methods
590
-	 *	--------------------------------
591
-	 */
592
-
593
-	/**
594
-	 * Writes log to local database
595
-	 *
596
-	 * @access private
597
-	 * @return boolean
598
-	 */
599
-	private function database_write_log () {
600
-	    # set values
601
-	    $values = array(
602
-	    			"command"=>$this->log_command,
603
-	    			"severity"=>$this->log_severity,
604
-	    			"date"=>$this->Database->toDate(),
605
-	    			"username"=>$this->log_username,
606
-	    			"ipaddr"=> array_key_exists('HTTP_X_REAL_IP', $_SERVER) ? $_SERVER['HTTP_X_REAL_IP'] : @$_SERVER['REMOTE_ADDR'],
607
-	    			"details"=>$this->log_details
608
-					);
609
-		# null empty values
610
-		$values = $this->reformat_empty_array_fields($values, null);
611
-		$values = $this->strip_input_tags($values);
612
-
613
-		# execute
614
-		try { $this->Database->insertObject("logs", $values); }
615
-		catch (Exception $e) {
616
-			$this->Result->show("danger", _("Error: ").$e->getMessage(), false);
617
-			return false;
618
-		}
619
-		# ok
620
-		return true;
621
-	}
622
-
623
-	/**
624
-	 * fetches logs for specified parameters
625
-	 *
626
-	 * @access public
627
-	 * @param mixed $logCount
628
-	 * @param mixed $direction (default: NULL)
629
-	 * @param mixed $lastId (default: NULL)
630
-	 * @param mixed $highestId (default: NULL)
631
-	 * @param mixed $informational (default: Off)
632
-	 * @param mixed $notice (default: Off)
633
-	 * @param mixed $warning (default: Off)
634
-	 * @return void
635
-	 */
636
-	public function fetch_logs ($logCount, $direction = NULL, $lastId = NULL, $highestId = NULL, $informational = "off", $notice = "off", $warning = "off") {
637
-
638
-    	# check for lastId - must be numeric
639
-    	if(!is_numeric($logCount))      { $this->Result->show("danger", "Invalid logcount value", true);	return false; }
640
-    	if($direction!==NULL) {
565
+                foreach($changelog as $k=>$l) {
566
+                    $log[] = "$k: $l";
567
+                }
568
+            }
569
+
570
+            # open syslog and write log
571
+            openlog('phpipam-changelog', LOG_NDELAY | LOG_PID, LOG_USER);
572
+            syslog(LOG_DEBUG, "changelog | $this->log_username | $this->object_type | $obj_id | $this->object_action | ".date("Y-m-d H:i:s")." | ".implode(", ",$log));
573
+            # close
574
+            closelog();
575
+        }
576
+    }
577
+
578
+
579
+
580
+
581
+
582
+
583
+
584
+
585
+
586
+
587
+
588
+    /**
589
+     *	@database log methods
590
+     *	--------------------------------
591
+     */
592
+
593
+    /**
594
+     * Writes log to local database
595
+     *
596
+     * @access private
597
+     * @return boolean
598
+     */
599
+    private function database_write_log () {
600
+        # set values
601
+        $values = array(
602
+                    "command"=>$this->log_command,
603
+                    "severity"=>$this->log_severity,
604
+                    "date"=>$this->Database->toDate(),
605
+                    "username"=>$this->log_username,
606
+                    "ipaddr"=> array_key_exists('HTTP_X_REAL_IP', $_SERVER) ? $_SERVER['HTTP_X_REAL_IP'] : @$_SERVER['REMOTE_ADDR'],
607
+                    "details"=>$this->log_details
608
+                    );
609
+        # null empty values
610
+        $values = $this->reformat_empty_array_fields($values, null);
611
+        $values = $this->strip_input_tags($values);
612
+
613
+        # execute
614
+        try { $this->Database->insertObject("logs", $values); }
615
+        catch (Exception $e) {
616
+            $this->Result->show("danger", _("Error: ").$e->getMessage(), false);
617
+            return false;
618
+        }
619
+        # ok
620
+        return true;
621
+    }
622
+
623
+    /**
624
+     * fetches logs for specified parameters
625
+     *
626
+     * @access public
627
+     * @param mixed $logCount
628
+     * @param mixed $direction (default: NULL)
629
+     * @param mixed $lastId (default: NULL)
630
+     * @param mixed $highestId (default: NULL)
631
+     * @param mixed $informational (default: Off)
632
+     * @param mixed $notice (default: Off)
633
+     * @param mixed $warning (default: Off)
634
+     * @return void
635
+     */
636
+    public function fetch_logs ($logCount, $direction = NULL, $lastId = NULL, $highestId = NULL, $informational = "off", $notice = "off", $warning = "off") {
637
+
638
+        # check for lastId - must be numeric
639
+        if(!is_numeric($logCount))      { $this->Result->show("danger", "Invalid logcount value", true);	return false; }
640
+        if($direction!==NULL) {
641 641
             if($direction!="next" && $direction!="prev" && $direction!="") {
642 642
                                         { $this->Result->show("danger", "Invalid direction", true);	return false; }
643 643
             }
644
-    	}
644
+        }
645 645
 
646
-		# query
647
-		$query = array();               // query
648
-		$query_severities = array();    // severities
649
-		$params = array();              // sql bind parameters
646
+        # query
647
+        $query = array();               // query
648
+        $query_severities = array();    // severities
649
+        $params = array();              // sql bind parameters
650 650
 
651 651
         $query[] = "select * from (";
652
-		$query[] = "select * from logs ";
653
-		$query[] = "where (";
654
-		// severities
655
-		if($informational=="on")
656
-		$query_severities[] = "`severity` = 0";
657
-		if($notice=="on")
658
-		$query_severities[] = "`severity` = 1";
659
-		if($warning=="on")
660
-		$query_severities[] = "`severity` = 2";
652
+        $query[] = "select * from logs ";
653
+        $query[] = "where (";
654
+        // severities
655
+        if($informational=="on")
656
+        $query_severities[] = "`severity` = 0";
657
+        if($notice=="on")
658
+        $query_severities[] = "`severity` = 1";
659
+        if($warning=="on")
660
+        $query_severities[] = "`severity` = 2";
661 661
         // join severities
662 662
         $query[] = implode(" or ", $query_severities);
663 663
         $query[] = ")";
664 664
 
665
-		// direction
666
-		if( ($direction=="next") && ($lastId!=$highestId) ) {
667
-			$query[] = "and `id` < :lastId";
668
-			$query[] = "order by `id` desc limit $logCount";
669
-			$params['lastId'] = $lastId;
670
-		}
671
-		elseif( $direction=="prev" && $lastId!=$highestId) {
672
-			$query[] = "and `id` > :lastId";
673
-			$query[] = "order by `id` asc limit $logCount";
674
-			$params['lastId'] = $lastId;
675
-		}
676
-		else {
677
-			$query[] = "order by `id` desc limit $logCount";
678
-		}
665
+        // direction
666
+        if( ($direction=="next") && ($lastId!=$highestId) ) {
667
+            $query[] = "and `id` < :lastId";
668
+            $query[] = "order by `id` desc limit $logCount";
669
+            $params['lastId'] = $lastId;
670
+        }
671
+        elseif( $direction=="prev" && $lastId!=$highestId) {
672
+            $query[] = "and `id` > :lastId";
673
+            $query[] = "order by `id` asc limit $logCount";
674
+            $params['lastId'] = $lastId;
675
+        }
676
+        else {
677
+            $query[] = "order by `id` desc limit $logCount";
678
+        }
679 679
         $query[] = ") as test ";
680 680
         $query[] = "order by `id` desc limit $logCount ;";
681 681
 
682
-	    # fetch
683
-	    try { $logs = $this->Database->getObjectsQuery(implode("\n", $query), $params); }
684
-		catch (Exception $e) { $this->Result->show("danger", $e->getMessage(), false);	return false; }
685
-
686
-	    # return results
687
-	    return $logs;
688
-	}
689
-
690
-	/**
691
-	 * Returns highest (last) log id
692
-	 *
693
-	 * @access public
694
-	 * @return void
695
-	 */
696
-	public function log_fetch_highest_id () {
697
-		# fetch
698
-	    try { $id = $this->Database->getObjectQuery("select id from logs order by id desc limit 1;"); }
699
-		catch (Exception $e) { $this->Result->show("danger", $e->getMessage(), false);	return false; }
700
-		# return result
701
-		return $id->id;
702
-	}
703
-
704
-
705
-
706
-
707
-
708
-
709
-
710
-
711
-
712
-
713
-	/**
714
-	 *	@changelog methods
715
-	 *	--------------------------------
716
-	 */
717
-
718
-	/**
719
-	 * Write new changelog to db or send to syslog
720
-	 *
721
-	 * @access public
722
-	 * @param string $object_type
723
-	 * @param string $action
724
-	 * @param string $result
725
-	 * @param array $old (default: array())
726
-	 * @param array $new (default: array())
727
-	 * @param bool $mail_changelog (default: true)
728
-	 * @return boolean|null
729
-	 */
730
-	public function write_changelog ($object_type, $action, $result, $old = array(), $new = array(), $mail_changelog = true) {
731
-		//set values
732
-		$this->object_type 	  = $object_type;
733
-		$this->object_action  = $action;
734
-		$this->object_result  = $result;
735
-		$this->mail_changelog = $mail_changelog;
736
-		//cast diff objects as array
737
-		$this->object_old = (array) $old;		// new object
738
-		$this->object_new = (array) $new;		// old object
739
-		// Save original unmodified values to construct URLs.
740
-		$this->object_orig = ($action == "add") ? $this->object_new : $this->object_old;
741
-
742
-		// validate - if object should write changelog or not
743
-		if ($this->changelog_validate_object () === false) {
744
-			return true;
745
-		}
746
-
747
-		// folder
748
-		if($this->object_type == "subnet") {
749
-			if ($this->object_old['isFolder'] || $this->object_new['isFolder']) {
750
-				$this->object_type = "folder";
751
-			}
752
-		}
753
-
754
-		// make sure we have settings
755
-		$this->get_settings ();
756
-
757
-		# default log
758
-		$log = array();
759
-
760
-		// check if syslog globally enabled and write log
761
-	    if($this->settings->enableChangelog==1) {
762
-		    # get user details and initialize required objects
763
-		    if (!is_object($this->Addresses)) $this->Addresses = new Addresses ($this->Database);
764
-		    if (!is_object($this->Subnets))   $this->Subnets   = new Subnets ($this->Database);
765
-		    if (!is_object($this->Sections))  $this->Sections  = new Sections ($this->Database);
766
-		    if (!is_object($this->Tools))     $this->Tools     = new Tools ($this->Database);
767
-
768
-		    # unset unneeded values and format
769
-		    $this->changelog_unset_unneeded_values ();
770
-
771
-		    # calculate diff
772
-		    if($action == "edit") {
773
-				$log = $this->changelog_calculate_edit_diff ();
774
-			}
775
-			elseif($action == "add") {
776
-				// format
777
-				$this->changelog_reformat_add_diff ();
778
-				//booleans
779
-				foreach ($this->object_new as $k=>$v) {
780
-					$this->object_new[$k] = $this->changelog_make_booleans ($k, $v);
781
-				}
782
-				$log['details'] = "<br>".$this->array_to_log ($this->object_new, true);
783
-			}
784
-			elseif($action == "delete") {
785
-				// format
786
-				$this->changelog_reformat_delete_diff ();
787
-				//booleans
788
-				foreach ($this->object_old as $k=>$v) {
789
-					$this->changelog_make_booleans ($k, $v);
790
-				}
791
-				$log['details'] = "<br>".$this->array_to_log ($this->object_old, true);
792
-			}
793
-			elseif($action == "truncate") {
794
-				$log['truncate'] = "Subnet truncated";
795
-			}
796
-			elseif($action == "resize") {
797
-				$log['resize'] = "Subnet Resized";
798
-				$log['mask'] = $this->object_old['mask']."/".$this->object_new['mask'];
799
-			}
800
-			elseif($action == "perm_change") {
801
-				$log = $this->changelog_format_permission_change ();
802
-			}
803
-
804
-			# if change happened write it!
805
-			if(is_array($log) && sizeof($log)>0) {
806
-				// reformat null
807
-				foreach ($log as $k=>$v) {
808
-					$log[$k] = str_replace(": <br>", ": / <br>", $v);
809
-				}
810
-				// execute
811
-				if ($this->log_type == "syslog")	{ $this->syslog_write_changelog ($log); }
812
-				elseif ($this->log_type == "both")	{ $this->changelog_write_to_db ($log); $this->syslog_write_changelog ($log); }
813
-				else								{ $this->changelog_write_to_db ($log); }
814
-			}
815
-		}
816
-		# not enabled
817
-		else {
818
-			return true;
819
-		}
820
-	}
821
-
822
-	/**
823
-	 * Writes changelog to database
824
-	 *
825
-	 * @access private
826
-	 * @param mixed $changelog
827
-	 * @return void
828
-	 */
829
-	private function changelog_write_to_db ($changelog) {
830
-		# log to array
831
-		$changelog = str_replace("<br>", "\r\n", $this->array_to_log ($changelog, true));
832
-		# fetch user id
833
-		$this->get_active_user_id ();
834
-
835
-		# null and from cli, set admin user
836
-		if ($this->user===null && php_sapi_name()=="cli") { $this->user_id = 1; }
682
+        # fetch
683
+        try { $logs = $this->Database->getObjectsQuery(implode("\n", $query), $params); }
684
+        catch (Exception $e) { $this->Result->show("danger", $e->getMessage(), false);	return false; }
685
+
686
+        # return results
687
+        return $logs;
688
+    }
689
+
690
+    /**
691
+     * Returns highest (last) log id
692
+     *
693
+     * @access public
694
+     * @return void
695
+     */
696
+    public function log_fetch_highest_id () {
697
+        # fetch
698
+        try { $id = $this->Database->getObjectQuery("select id from logs order by id desc limit 1;"); }
699
+        catch (Exception $e) { $this->Result->show("danger", $e->getMessage(), false);	return false; }
700
+        # return result
701
+        return $id->id;
702
+    }
703
+
704
+
705
+
706
+
707
+
708
+
709
+
710
+
711
+
712
+
713
+    /**
714
+     *	@changelog methods
715
+     *	--------------------------------
716
+     */
717
+
718
+    /**
719
+     * Write new changelog to db or send to syslog
720
+     *
721
+     * @access public
722
+     * @param string $object_type
723
+     * @param string $action
724
+     * @param string $result
725
+     * @param array $old (default: array())
726
+     * @param array $new (default: array())
727
+     * @param bool $mail_changelog (default: true)
728
+     * @return boolean|null
729
+     */
730
+    public function write_changelog ($object_type, $action, $result, $old = array(), $new = array(), $mail_changelog = true) {
731
+        //set values
732
+        $this->object_type 	  = $object_type;
733
+        $this->object_action  = $action;
734
+        $this->object_result  = $result;
735
+        $this->mail_changelog = $mail_changelog;
736
+        //cast diff objects as array
737
+        $this->object_old = (array) $old;		// new object
738
+        $this->object_new = (array) $new;		// old object
739
+        // Save original unmodified values to construct URLs.
740
+        $this->object_orig = ($action == "add") ? $this->object_new : $this->object_old;
741
+
742
+        // validate - if object should write changelog or not
743
+        if ($this->changelog_validate_object () === false) {
744
+            return true;
745
+        }
746
+
747
+        // folder
748
+        if($this->object_type == "subnet") {
749
+            if ($this->object_old['isFolder'] || $this->object_new['isFolder']) {
750
+                $this->object_type = "folder";
751
+            }
752
+        }
753
+
754
+        // make sure we have settings
755
+        $this->get_settings ();
756
+
757
+        # default log
758
+        $log = array();
759
+
760
+        // check if syslog globally enabled and write log
761
+        if($this->settings->enableChangelog==1) {
762
+            # get user details and initialize required objects
763
+            if (!is_object($this->Addresses)) $this->Addresses = new Addresses ($this->Database);
764
+            if (!is_object($this->Subnets))   $this->Subnets   = new Subnets ($this->Database);
765
+            if (!is_object($this->Sections))  $this->Sections  = new Sections ($this->Database);
766
+            if (!is_object($this->Tools))     $this->Tools     = new Tools ($this->Database);
767
+
768
+            # unset unneeded values and format
769
+            $this->changelog_unset_unneeded_values ();
770
+
771
+            # calculate diff
772
+            if($action == "edit") {
773
+                $log = $this->changelog_calculate_edit_diff ();
774
+            }
775
+            elseif($action == "add") {
776
+                // format
777
+                $this->changelog_reformat_add_diff ();
778
+                //booleans
779
+                foreach ($this->object_new as $k=>$v) {
780
+                    $this->object_new[$k] = $this->changelog_make_booleans ($k, $v);
781
+                }
782
+                $log['details'] = "<br>".$this->array_to_log ($this->object_new, true);
783
+            }
784
+            elseif($action == "delete") {
785
+                // format
786
+                $this->changelog_reformat_delete_diff ();
787
+                //booleans
788
+                foreach ($this->object_old as $k=>$v) {
789
+                    $this->changelog_make_booleans ($k, $v);
790
+                }
791
+                $log['details'] = "<br>".$this->array_to_log ($this->object_old, true);
792
+            }
793
+            elseif($action == "truncate") {
794
+                $log['truncate'] = "Subnet truncated";
795
+            }
796
+            elseif($action == "resize") {
797
+                $log['resize'] = "Subnet Resized";
798
+                $log['mask'] = $this->object_old['mask']."/".$this->object_new['mask'];
799
+            }
800
+            elseif($action == "perm_change") {
801
+                $log = $this->changelog_format_permission_change ();
802
+            }
803
+
804
+            # if change happened write it!
805
+            if(is_array($log) && sizeof($log)>0) {
806
+                // reformat null
807
+                foreach ($log as $k=>$v) {
808
+                    $log[$k] = str_replace(": <br>", ": / <br>", $v);
809
+                }
810
+                // execute
811
+                if ($this->log_type == "syslog")	{ $this->syslog_write_changelog ($log); }
812
+                elseif ($this->log_type == "both")	{ $this->changelog_write_to_db ($log); $this->syslog_write_changelog ($log); }
813
+                else								{ $this->changelog_write_to_db ($log); }
814
+            }
815
+        }
816
+        # not enabled
817
+        else {
818
+            return true;
819
+        }
820
+    }
821
+
822
+    /**
823
+     * Writes changelog to database
824
+     *
825
+     * @access private
826
+     * @param mixed $changelog
827
+     * @return void
828
+     */
829
+    private function changelog_write_to_db ($changelog) {
830
+        # log to array
831
+        $changelog = str_replace("<br>", "\r\n", $this->array_to_log ($changelog, true));
832
+        # fetch user id
833
+        $this->get_active_user_id ();
834
+
835
+        # null and from cli, set admin user
836
+        if ($this->user===null && php_sapi_name()=="cli") { $this->user_id = 1; }
837 837
 
838 838
         # if user is not specify dont write changelog
839 839
         if (!isset($this->user) || $this->user == false || $this->user == null) {
840 840
             return true;
841 841
         }
842 842
 
843
-		# set update id based on action
844
-		if ($this->object_action=="add")	{ $obj_id = $this->object_new['id']; }
845
-		else								{ $obj_id = $this->object_old['id']; }
846
-
847
-		# set object type
848
-		$object_type = $this->object_type=="folder" ? "subnet" : $this->object_type;
849
-
850
-		# if required values are missing dont save changelog
851
-		if(is_null($obj_id) || $obj_id=="NULL")	{ return false; }
852
-
853
-	    # set values
854
-	    $values = array(
855
-	    			"ctype"	 => $object_type,
856
-	    			"coid"	 => $obj_id,
857
-	    			"cuser"	 => $this->user_id,
858
-	    			"caction"=> $this->object_action,
859
-	    			"cresult"=> $this->object_result,
860
-	    			"cdate"	 => date("Y-m-d H:i:s"),
861
-	    			"cdiff"	 => $changelog
862
-					);
863
-		# null empty values
864
-		$values = $this->reformat_empty_array_fields ($values, null);
865
-
866
-		# execute
867
-		try { $this->Database->insertObject("changelog", $values); }
868
-		catch (Exception $e) {
869
-			$this->Result->show("danger", _("Error: ").$e->getMessage(), false);
870
-			return false;
871
-		}
872
-		# mail
873
-		if ($this->mail_changelog && strlen($changelog)>0) {
874
-			$this->changelog_send_mail ($changelog);
875
-		}
876
-		# ok
877
-		return true;
878
-	}
879
-
880
-	/**
881
-	 * Checks if object should write changelog
882
-	 *
883
-	 * @access private
884
-	 * @return boolean
885
-	 */
886
-	private function changelog_validate_object () {
887
-		# set valid objects
888
-		$objects = array(
889
-						"ip_addr",
890
-						"subnet",
891
-						"folder",
892
-						"section"
893
-						);
894
-		# check
895
-		return in_array($this->object_type, $objects) ? true : false;
896
-	}
897
-
898
-	/**
899
-	 * Formats values on creation
900
-	 *
901
-	 * @access private
902
-	 * @return void
903
-	 */
904
-	private function changelog_reformat_add_diff () {
905
-		foreach ($this->object_new as $k=>$v) {
906
-			//tag change
907
-			if($k == 'state') 				{ $this->object_new[$k] = $this->changelog_format_tag_diff ($k, $v); }
908
-			//section change
909
-			elseif($k == 'sectionId') 		{ $this->object_new[$k] = $this->changelog_format_section_diff ($k, $v); }
910
-			//section change
911
-			elseif($k == 'section') 		{ $this->object_new[$k] = $this->changelog_format_section_diff ($k, $v); }
912
-			//master subnet change
913
-			elseif($k == "subnetId") 		{ $this->object_new[$k] = $this->changelog_format_master_subnet_diff ($k, $v); }
914
-			//master subnet change
915
-			elseif($k == "masterSubnetId") 	{ $this->object_new[$k] = $this->changelog_format_master_subnet_diff ($k, $v); }
916
-			//device change
917
-			elseif($k == 'switch') 			{ $this->object_new[$k] = $this->changelog_format_device_diff ($k, $v); }
918
-			//device change
919
-			elseif($k == 'device') 			{ $this->object_new[$k] = $this->changelog_format_device_diff ($k, $v); }
920
-			//vlan
921
-			elseif($k == 'vlanId') 			{ $this->object_new[$k] = $this->changelog_format_vlan_diff ($k, $v); }
922
-			//vrf
923
-			elseif($k == 'vrfId') 			{ $this->object_new[$k] = $this->changelog_format_vrf_diff ($k, $v); }
924
-			//location
925
-			elseif($k == 'location_item')   { $this->object_new[$k] = $this->changelog_format_location_diff ($k, $v); }
926
-			//location
927
-			elseif($k == 'location') 	    { $this->object_new[$k] = $this->changelog_format_location_diff ($k, $v); }
928
-			//master section change
929
-			elseif($k == 'masterSection') 	{ $this->object_new[$k] = $this->changelog_format_master_section_diff ($k, $v); }
930
-			//permission change
931
-			elseif($k == "permissions") 	{ $this->object_new[$k] = $this->changelog_format_permission_diff ($k, $v); }
932
-			// nameserver index
933
-			elseif($k == "nameserverId") 	{ $this->object_new[$k] = $this->changelog_format_ns_diff ($k, $v); }
934
-		}
935
-	}
936
-
937
-
938
-	/**
939
-	 * Formats values on delete
940
-	 *
941
-	 * @access private
942
-	 * @return void
943
-	 */
944
-	private function changelog_reformat_delete_diff () {
945
-		foreach ($this->object_old as $k=>$v) {
946
-			//tag change
947
-			if($k == 'state') 				{ $this->object_old[$k] = $this->changelog_format_tag_diff ($k, $v); }
948
-			//section change
949
-			elseif($k == 'section') 		{ $this->object_old[$k] = $this->changelog_format_section_diff ($k, $v); }
950
-			//section change
951
-			elseif($k == 'sectionId') 		{ $this->object_old[$k] = $this->changelog_format_section_diff ($k, $v); }
952
-			//subnet change
953
-			elseif($k == "subnetId") 		{ $this->object_old[$k] = $this->changelog_format_master_subnet_diff ($k, $v); }
954
-			//master subnet change
955
-			elseif($k == "masterSubnetId") 	{ $this->object_old[$k] = $this->changelog_format_master_subnet_diff ($k, $v); }
956
-			//device change
957
-			elseif($k == 'switch') 			{ $this->object_old[$k] = $this->changelog_format_device_diff ($k, $v); }
958
-			//device change
959
-			elseif($k == 'device') 			{ $this->object_old[$k] = $this->changelog_format_device_diff ($k, $v); }
960
-			//vlan
961
-			elseif($k == 'vlanId') 			{ $this->object_old[$k] = $this->changelog_format_vlan_diff ($k, $v); }
962
-			//vrf
963
-			elseif($k == 'vrfId') 			{ $this->object_old[$k] = $this->changelog_format_vrf_diff ($k, $v); }
964
-			//location
965
-			elseif($k == 'location_item') 	{ $this->object_old[$k] = $this->changelog_format_location_diff ($k, $v); }
966
-			//location
967
-			elseif($k == 'location') 	    { $this->object_old[$k] = $this->changelog_format_location_diff ($k, $v); }
968
-			//master section change
969
-			elseif($k == 'masterSection') 	{ $this->object_old[$k] = $this->changelog_format_master_section_diff ($k, $v); }
970
-			//permission change
971
-			elseif($k == "permissions") 	{ $this->object_old[$k] = $this->changelog_format_permission_diff ($k, $v); }
972
-			// nameserver index
973
-			elseif($k == "nameserverId") 	{ $this->object_old[$k] = $this->changelog_format_ns_diff ($k, $v); }
974
-		}
975
-	}
976
-
977
-	/**
978
-	 * Calculate possible chages on edit
979
-	 *
980
-	 * @access private
981
-	 * @return array
982
-	 */
983
-	private function changelog_calculate_edit_diff () {
984
-		//old object - checkboxes that are not present, set them as 0
985
-		foreach($this->object_old as $k=>$v) {
986
-			if(!isset($this->object_new[$k]) && $v=="1") {
987
-				$this->object_new[$k] = 0;
988
-			}
989
-		}
990
-		foreach ($this->object_new as $k=>$v) {
991
-			if(!isset($this->object_old[$k]) && $v=="1") {
992
-				$this->object_old[$k] = 0;
993
-			}
994
-		}
995
-		// ip address - old needs to be transformed to dotted format
996
-		$this->object_old['ip_addr'] = $this->Subnets->transform_address($this->object_old['ip_addr'], "dotted");
997
-		$this->object_new['ip_addr'] = $this->Subnets->transform_address($this->object_new['ip_addr'], "dotted");
998
-
999
-		// check each value
1000
-		foreach($this->object_new as $k=>$v) {
1001
-			//change
1002
-			if($this->object_old[$k]!=$v && ($this->object_old[$k] != str_replace("\'", "'", $v)))	{
1003
-				//empty
1004
-				if(strlen(@$this->object_old[$k])==0)	{ $this->object_old[$k] = "NULL"; }
1005
-				if(strlen(@$v)==0)						{ $v = "NULL"; }
1006
-
1007
-				//tag change
1008
-				if($k == 'state') 				{ $v = $this->changelog_format_tag_diff ($k, $v); }
1009
-				//section change
1010
-				elseif($k == 'sectionIdNew') 	{ $v = $this->changelog_format_section_diff ($k, $v); }
1011
-				//section change
1012
-				elseif($k == 'sectionId') 		{ $v = $this->changelog_format_section_diff ($k, $v); }
1013
-				//subnet change
1014
-				elseif($k == "subnet") 			{ $v = $this->changelog_format_master_subnet_diff ($k, $v); }
1015
-				//master subnet change
1016
-				elseif($k == "masterSubnetId") 	{ $v = $this->changelog_format_master_subnet_diff ($k, $v); }
1017
-				//device change
1018
-				elseif($k == 'switch') 			{ $v = $this->changelog_format_device_diff ($k, $v); }
1019
-				//device change
1020
-				elseif($k == 'device') 			{ $v = $this->changelog_format_device_diff ($k, $v); }
1021
-				//vlan
1022
-				elseif($k == 'vlanId') 			{ $v = $this->changelog_format_vlan_diff ($k, $v); }
1023
-				//vrf
1024
-				elseif($k == 'vrfId') 			{ $v = $this->changelog_format_vrf_diff ($k, $v); }
1025
-				//location
1026
-				elseif($k == 'location_item') 	{ $v = $this->changelog_format_location_diff ($k, $v); }
1027
-				//location
1028
-				elseif($k == 'location') 	    { $v = $this->changelog_format_location_diff ($k, $v); }
1029
-				//master section change
1030
-				elseif($k == 'masterSection') 	{ $v = $this->changelog_format_master_section_diff ($k, $v); }
1031
-				//permission change
1032
-				elseif($k == "permissions") 	{ $v = $this->changelog_format_permission_diff ($k, $v); }
1033
-				// nameserver index
1034
-				elseif($k == "nameserverId") 	{ $v = $this->changelog_format_ns_diff ($k, $v); }
1035
-				// make booleans
1036
-				$v = $this->changelog_make_booleans ($k, $v);
1037
-				//set log
1038
-				if ($k!=="id")
1039
-				$log["$k"] = $this->object_old[$k]." => $v";
1040
-			}
1041
-		}
1042
-		// result
1043
-		return $log;
1044
-	}
1045
-
1046
-	/**
1047
-	 * Removes unneeded values from changelog based on log type
1048
-	 *
1049
-	 * @access private
1050
-	 * @return void
1051
-	 */
1052
-	private function changelog_unset_unneeded_values () {
1053
-		# remove ip address fields
1054
-		if($this->object_type == "ip_addr") {
1055
-			unset(	$this->object_new['subnet'],
1056
-					$this->object_new['type'],
1057
-					$this->object_new['ip_addr_old'],
1058
-					$this->object_new['nostrict'],
1059
-					$this->object_new['start'],
1060
-					$this->object_new['stop'],
1061
-					$this->object_new['ip'],
1062
-					$this->object_new['subnetvlan'],
1063
-					$this->object_new['addressId']
1064
-					);
1065
-			unset(	$this->object_old['subnet'],
1066
-					$this->object_old['type'],
1067
-					$this->object_old['ip_addr_old'],
1068
-					$this->object_old['nostrict'],
1069
-					$this->object_old['start'],
1070
-					$this->object_old['stop'],
1071
-					$this->object_old['ip'],
1072
-					$this->object_old['subnetvlan'],
1073
-					$this->object_old['addressId']
1074
-					);
843
+        # set update id based on action
844
+        if ($this->object_action=="add")	{ $obj_id = $this->object_new['id']; }
845
+        else								{ $obj_id = $this->object_old['id']; }
846
+
847
+        # set object type
848
+        $object_type = $this->object_type=="folder" ? "subnet" : $this->object_type;
849
+
850
+        # if required values are missing dont save changelog
851
+        if(is_null($obj_id) || $obj_id=="NULL")	{ return false; }
852
+
853
+        # set values
854
+        $values = array(
855
+                    "ctype"	 => $object_type,
856
+                    "coid"	 => $obj_id,
857
+                    "cuser"	 => $this->user_id,
858
+                    "caction"=> $this->object_action,
859
+                    "cresult"=> $this->object_result,
860
+                    "cdate"	 => date("Y-m-d H:i:s"),
861
+                    "cdiff"	 => $changelog
862
+                    );
863
+        # null empty values
864
+        $values = $this->reformat_empty_array_fields ($values, null);
865
+
866
+        # execute
867
+        try { $this->Database->insertObject("changelog", $values); }
868
+        catch (Exception $e) {
869
+            $this->Result->show("danger", _("Error: ").$e->getMessage(), false);
870
+            return false;
871
+        }
872
+        # mail
873
+        if ($this->mail_changelog && strlen($changelog)>0) {
874
+            $this->changelog_send_mail ($changelog);
875
+        }
876
+        # ok
877
+        return true;
878
+    }
879
+
880
+    /**
881
+     * Checks if object should write changelog
882
+     *
883
+     * @access private
884
+     * @return boolean
885
+     */
886
+    private function changelog_validate_object () {
887
+        # set valid objects
888
+        $objects = array(
889
+                        "ip_addr",
890
+                        "subnet",
891
+                        "folder",
892
+                        "section"
893
+                        );
894
+        # check
895
+        return in_array($this->object_type, $objects) ? true : false;
896
+    }
897
+
898
+    /**
899
+     * Formats values on creation
900
+     *
901
+     * @access private
902
+     * @return void
903
+     */
904
+    private function changelog_reformat_add_diff () {
905
+        foreach ($this->object_new as $k=>$v) {
906
+            //tag change
907
+            if($k == 'state') 				{ $this->object_new[$k] = $this->changelog_format_tag_diff ($k, $v); }
908
+            //section change
909
+            elseif($k == 'sectionId') 		{ $this->object_new[$k] = $this->changelog_format_section_diff ($k, $v); }
910
+            //section change
911
+            elseif($k == 'section') 		{ $this->object_new[$k] = $this->changelog_format_section_diff ($k, $v); }
912
+            //master subnet change
913
+            elseif($k == "subnetId") 		{ $this->object_new[$k] = $this->changelog_format_master_subnet_diff ($k, $v); }
914
+            //master subnet change
915
+            elseif($k == "masterSubnetId") 	{ $this->object_new[$k] = $this->changelog_format_master_subnet_diff ($k, $v); }
916
+            //device change
917
+            elseif($k == 'switch') 			{ $this->object_new[$k] = $this->changelog_format_device_diff ($k, $v); }
918
+            //device change
919
+            elseif($k == 'device') 			{ $this->object_new[$k] = $this->changelog_format_device_diff ($k, $v); }
920
+            //vlan
921
+            elseif($k == 'vlanId') 			{ $this->object_new[$k] = $this->changelog_format_vlan_diff ($k, $v); }
922
+            //vrf
923
+            elseif($k == 'vrfId') 			{ $this->object_new[$k] = $this->changelog_format_vrf_diff ($k, $v); }
924
+            //location
925
+            elseif($k == 'location_item')   { $this->object_new[$k] = $this->changelog_format_location_diff ($k, $v); }
926
+            //location
927
+            elseif($k == 'location') 	    { $this->object_new[$k] = $this->changelog_format_location_diff ($k, $v); }
928
+            //master section change
929
+            elseif($k == 'masterSection') 	{ $this->object_new[$k] = $this->changelog_format_master_section_diff ($k, $v); }
930
+            //permission change
931
+            elseif($k == "permissions") 	{ $this->object_new[$k] = $this->changelog_format_permission_diff ($k, $v); }
932
+            // nameserver index
933
+            elseif($k == "nameserverId") 	{ $this->object_new[$k] = $this->changelog_format_ns_diff ($k, $v); }
934
+        }
935
+    }
936
+
937
+
938
+    /**
939
+     * Formats values on delete
940
+     *
941
+     * @access private
942
+     * @return void
943
+     */
944
+    private function changelog_reformat_delete_diff () {
945
+        foreach ($this->object_old as $k=>$v) {
946
+            //tag change
947
+            if($k == 'state') 				{ $this->object_old[$k] = $this->changelog_format_tag_diff ($k, $v); }
948
+            //section change
949
+            elseif($k == 'section') 		{ $this->object_old[$k] = $this->changelog_format_section_diff ($k, $v); }
950
+            //section change
951
+            elseif($k == 'sectionId') 		{ $this->object_old[$k] = $this->changelog_format_section_diff ($k, $v); }
952
+            //subnet change
953
+            elseif($k == "subnetId") 		{ $this->object_old[$k] = $this->changelog_format_master_subnet_diff ($k, $v); }
954
+            //master subnet change
955
+            elseif($k == "masterSubnetId") 	{ $this->object_old[$k] = $this->changelog_format_master_subnet_diff ($k, $v); }
956
+            //device change
957
+            elseif($k == 'switch') 			{ $this->object_old[$k] = $this->changelog_format_device_diff ($k, $v); }
958
+            //device change
959
+            elseif($k == 'device') 			{ $this->object_old[$k] = $this->changelog_format_device_diff ($k, $v); }
960
+            //vlan
961
+            elseif($k == 'vlanId') 			{ $this->object_old[$k] = $this->changelog_format_vlan_diff ($k, $v); }
962
+            //vrf
963
+            elseif($k == 'vrfId') 			{ $this->object_old[$k] = $this->changelog_format_vrf_diff ($k, $v); }
964
+            //location
965
+            elseif($k == 'location_item') 	{ $this->object_old[$k] = $this->changelog_format_location_diff ($k, $v); }
966
+            //location
967
+            elseif($k == 'location') 	    { $this->object_old[$k] = $this->changelog_format_location_diff ($k, $v); }
968
+            //master section change
969
+            elseif($k == 'masterSection') 	{ $this->object_old[$k] = $this->changelog_format_master_section_diff ($k, $v); }
970
+            //permission change
971
+            elseif($k == "permissions") 	{ $this->object_old[$k] = $this->changelog_format_permission_diff ($k, $v); }
972
+            // nameserver index
973
+            elseif($k == "nameserverId") 	{ $this->object_old[$k] = $this->changelog_format_ns_diff ($k, $v); }
974
+        }
975
+    }
976
+
977
+    /**
978
+     * Calculate possible chages on edit
979
+     *
980
+     * @access private
981
+     * @return array
982
+     */
983
+    private function changelog_calculate_edit_diff () {
984
+        //old object - checkboxes that are not present, set them as 0
985
+        foreach($this->object_old as $k=>$v) {
986
+            if(!isset($this->object_new[$k]) && $v=="1") {
987
+                $this->object_new[$k] = 0;
988
+            }
989
+        }
990
+        foreach ($this->object_new as $k=>$v) {
991
+            if(!isset($this->object_old[$k]) && $v=="1") {
992
+                $this->object_old[$k] = 0;
993
+            }
994
+        }
995
+        // ip address - old needs to be transformed to dotted format
996
+        $this->object_old['ip_addr'] = $this->Subnets->transform_address($this->object_old['ip_addr'], "dotted");
997
+        $this->object_new['ip_addr'] = $this->Subnets->transform_address($this->object_new['ip_addr'], "dotted");
998
+
999
+        // check each value
1000
+        foreach($this->object_new as $k=>$v) {
1001
+            //change
1002
+            if($this->object_old[$k]!=$v && ($this->object_old[$k] != str_replace("\'", "'", $v)))	{
1003
+                //empty
1004
+                if(strlen(@$this->object_old[$k])==0)	{ $this->object_old[$k] = "NULL"; }
1005
+                if(strlen(@$v)==0)						{ $v = "NULL"; }
1006
+
1007
+                //tag change
1008
+                if($k == 'state') 				{ $v = $this->changelog_format_tag_diff ($k, $v); }
1009
+                //section change
1010
+                elseif($k == 'sectionIdNew') 	{ $v = $this->changelog_format_section_diff ($k, $v); }
1011
+                //section change
1012
+                elseif($k == 'sectionId') 		{ $v = $this->changelog_format_section_diff ($k, $v); }
1013
+                //subnet change
1014
+                elseif($k == "subnet") 			{ $v = $this->changelog_format_master_subnet_diff ($k, $v); }
1015
+                //master subnet change
1016
+                elseif($k == "masterSubnetId") 	{ $v = $this->changelog_format_master_subnet_diff ($k, $v); }
1017
+                //device change
1018
+                elseif($k == 'switch') 			{ $v = $this->changelog_format_device_diff ($k, $v); }
1019
+                //device change
1020
+                elseif($k == 'device') 			{ $v = $this->changelog_format_device_diff ($k, $v); }
1021
+                //vlan
1022
+                elseif($k == 'vlanId') 			{ $v = $this->changelog_format_vlan_diff ($k, $v); }
1023
+                //vrf
1024
+                elseif($k == 'vrfId') 			{ $v = $this->changelog_format_vrf_diff ($k, $v); }
1025
+                //location
1026
+                elseif($k == 'location_item') 	{ $v = $this->changelog_format_location_diff ($k, $v); }
1027
+                //location
1028
+                elseif($k == 'location') 	    { $v = $this->changelog_format_location_diff ($k, $v); }
1029
+                //master section change
1030
+                elseif($k == 'masterSection') 	{ $v = $this->changelog_format_master_section_diff ($k, $v); }
1031
+                //permission change
1032
+                elseif($k == "permissions") 	{ $v = $this->changelog_format_permission_diff ($k, $v); }
1033
+                // nameserver index
1034
+                elseif($k == "nameserverId") 	{ $v = $this->changelog_format_ns_diff ($k, $v); }
1035
+                // make booleans
1036
+                $v = $this->changelog_make_booleans ($k, $v);
1037
+                //set log
1038
+                if ($k!=="id")
1039
+                $log["$k"] = $this->object_old[$k]." => $v";
1040
+            }
1041
+        }
1042
+        // result
1043
+        return $log;
1044
+    }
1045
+
1046
+    /**
1047
+     * Removes unneeded values from changelog based on log type
1048
+     *
1049
+     * @access private
1050
+     * @return void
1051
+     */
1052
+    private function changelog_unset_unneeded_values () {
1053
+        # remove ip address fields
1054
+        if($this->object_type == "ip_addr") {
1055
+            unset(	$this->object_new['subnet'],
1056
+                    $this->object_new['type'],
1057
+                    $this->object_new['ip_addr_old'],
1058
+                    $this->object_new['nostrict'],
1059
+                    $this->object_new['start'],
1060
+                    $this->object_new['stop'],
1061
+                    $this->object_new['ip'],
1062
+                    $this->object_new['subnetvlan'],
1063
+                    $this->object_new['addressId']
1064
+                    );
1065
+            unset(	$this->object_old['subnet'],
1066
+                    $this->object_old['type'],
1067
+                    $this->object_old['ip_addr_old'],
1068
+                    $this->object_old['nostrict'],
1069
+                    $this->object_old['start'],
1070
+                    $this->object_old['stop'],
1071
+                    $this->object_old['ip'],
1072
+                    $this->object_old['subnetvlan'],
1073
+                    $this->object_old['addressId']
1074
+                    );
1075 1075
             # remove mac
1076 1076
             if ($this->object_action=="add") {
1077 1077
                 unset ($this->object_new['mac_old'], $this->object_new['addressId']);
1078 1078
             }
1079
-			# reformat ip
1080
-			if (isset($this->object_old['ip_addr']))	{ $this->object_old['ip_addr'] = $this->Subnets->transform_address ($this->object_old['ip_addr'],"dotted"); }
1081
-			if (isset($this->object_new['ip_addr']))	{ $this->object_new['ip_addr'] = $this->Subnets->transform_address ($this->object_new['ip_addr'],"dotted"); }
1082
-
1083
-		}
1084
-		# remove subnet fields
1085
-		elseif($this->object_type == "subnet" || $this->object_type == "folder")	{
1086
-			// remove unneeded values
1087
-			unset(	$this->object_new['subnetId'],
1088
-					$this->object_new['vrfIdOld'],
1089
-					$this->object_new['permissions'],
1090
-					$this->object_new['state'],
1091
-					$this->object_new['ip']
1092
-				);
1093
-			unset(	$this->object_old['subnetId'],
1094
-					$this->object_old['vrfIdOld'],
1095
-					$this->object_old['permissions'],
1096
-					$this->object_old['state'],
1097
-					$this->object_old['ip']
1098
-				);
1099
-
1100
-			# folder
1101
-			if($this->object_type == "folder") {
1102
-				unset(
1103
-					$this->object_new['linked_subnet'],
1104
-					$this->object_new['firewallAddressObject'],
1105
-					$this->object_new['vrfId'],
1106
-					$this->object_new['allowRequests'],
1107
-					$this->object_new['vlanId'],
1108
-					$this->object_new['showName'],
1109
-					$this->object_new['device'],
1110
-					$this->object_new['pingSubnet'],
1111
-					$this->object_new['discoverSubnet'],
1112
-					$this->object_new['DNSrecursive'],
1113
-					$this->object_new['DNSrecords'],
1114
-					$this->object_new['nameserverId'],
1115
-					$this->object_new['scanAgent'],
1116
-					$this->object_new['isFull'],
1117
-					$this->object_new['threshold'],
1118
-					$this->object_new['lastScan'],
1119
-					$this->object_new['lastDiscovery']
1120
-				);
1121
-				unset(
1122
-					$this->object_old['linked_subnet'],
1123
-					$this->object_old['firewallAddressObject'],
1124
-					$this->object_old['vrfId'],
1125
-					$this->object_old['allowRequests'],
1126
-					$this->object_old['vlanId'],
1127
-					$this->object_old['showName'],
1128
-					$this->object_old['device'],
1129
-					$this->object_old['pingSubnet'],
1130
-					$this->object_old['discoverSubnet'],
1131
-					$this->object_old['DNSrecursive'],
1132
-					$this->object_old['DNSrecords'],
1133
-					$this->object_old['nameserverId'],
1134
-					$this->object_old['scanAgent'],
1135
-					$this->object_old['isFull'],
1136
-					$this->object_old['threshold'],
1137
-					$this->object_old['lastScan'],
1138
-					$this->object_old['lastDiscovery']
1139
-				);
1140
-			}
1141
-
1142
-			# if section does not change
1143
-			if($this->object_new['sectionId']==$this->object_new['sectionIdNew']) {
1144
-				unset(	$this->object_new['sectionIdNew']);
1145
-			}
1146
-			else {
1147
-				$this->object_old['sectionIdNew'] = $this->object_old['sectionId'];
1148
-			}
1149
-
1150
-			//transform subnet to IP address format
1151
-			if(strlen($this->object_new['subnet'])>0) 	{ $this->object_new['subnet'] = $this->Subnets->transform_address ($this->object_new['subnet'], "dotted");}
1152
-			if(strlen($this->object_old['subnet'])>0) 	{ $this->object_old['subnet'] = $this->Subnets->transform_address ($this->object_old['subnet'], "dotted");}
1153
-
1154
-			//remove subnet/mask for folders
1155
-			if (@$this->object_new['isFolder']=="1")	{ unset($this->object_new['subnet'], $this->object_new['mask']); }
1156
-			if (@$this->object_old['isFolder']=="1")	{ unset($this->object_old['subnet'], $this->object_old['mask']); }
1157
-		}
1158
-		# remove order fields
1159
-		elseif($this->object_type == "section") {
1160
-			unset($this->object_old['order']);
1161
-		}
1162
-
1163
-		# common
1164
-		unset($this->object_new['action']);
1165
-		unset($this->object_new['editDate'], $this->object_old['editDate']);
1166
-		unset($this->object_new['csrf_cookie']);
1167
-	}
1168
-
1169
-	/**
1170
-	 * Formats tag from int to nam.
1171
-	 *
1172
-	 * @access private
1173
-	 * @param string $k
1174
-	 * @param mixed $v
1175
-	 * @return void
1176
-	 */
1177
-	private function changelog_format_tag_diff ($k, $v) {
1178
-		$this->object_old[$k] = $this->Addresses->address_type_index_to_type($this->object_old[$k]);
1179
-		$v 					  = $this->Addresses->address_type_index_to_type($v);
1180
-		//result
1181
-		return $v;
1182
-	}
1183
-
1184
-	/**
1185
-	 * Formats section if change
1186
-	 *
1187
-	 * @access private
1188
-	 * @param string $k
1189
-	 * @param mixed $v
1190
-	 * @return void
1191
-	 */
1192
-	private function changelog_format_section_diff ($k, $v) {
1193
-		//get old and new device
1194
-		if($this->object_old[$k] != "NULL") {
1195
-			$section = $this->Sections->fetch_section ("id", $this->object_old[$k]);
1196
-			$this->object_old[$k] = $section->name." (id ".$section->id.")";
1197
-		}
1198
-		if($v != "NULL")	{
1199
-			$section = $this->Sections->fetch_section ("id", $v);
1200
-			$v = $section->name." (id ".$section->id.")";
1201
-		}
1202
-		//result
1203
-		return $v;
1204
-	}
1205
-
1206
-	/**
1207
-	 * Formats master subnet if change
1208
-	 *
1209
-	 * @access private
1210
-	 * @param string $k
1211
-	 * @param mixed $v
1212
-	 * @return string
1213
-	 */
1214
-	private function changelog_format_master_subnet_diff ($k, $v) {
1215
-		//Old root or not
1216
-		if($this->object_old[$k]==0){
1217
-			$this->object_old[$k] = "Root";
1218
-		}
1219
-		else {
1220
-			$subnet = $this->Subnets->fetch_subnet("id", $this->object_old[$k]);
1221
-			$this->object_old[$k] = strlen($subnet->description)>0 ? $this->Subnets->transform_address($subnet->subnet, "dotted")."/$subnet->mask [$subnet->description]" : $this->Subnets->transform_address($subnet->subnet, "dotted")."/".$subnet->mask;
1222
-			$this->object_old[$k] .= " (id ".$subnet->id.")";
1223
-		}
1224
-		//New root or not
1225
-		if($v==0) {
1226
-			$v = "Root";
1227
-		}
1228
-		else {
1229
-			$subnet = $this->Subnets->fetch_subnet("id", $v);
1230
-			$v  = strlen($subnet->description)>0 ? $this->Subnets->transform_address($subnet->subnet, "dotted")."/$subnet->mask [$subnet->description]" : $this->Subnets->transform_address($subnet->subnet, "dotted")."/".$subnet->mask;
1231
-			$v .= " (id ".$subnet->id.")";
1232
-		}
1233
-		//result
1234
-		return $v;
1235
-	}
1236
-
1237
-	/**
1238
-	 * Format device if change
1239
-	 *
1240
-	 * @access private
1241
-	 * @param string $k
1242
-	 * @param mixed $v
1243
-	 * @return void
1244
-	 */
1245
-	private function changelog_format_device_diff ($k, $v) {
1246
-		// old none
1247
-		if($this->object_old[$k] == 0)	{
1248
-			$this->object_old[$k] = "None";
1249
-		}
1250
-		elseif($this->object_old[$k] != "NULL") {
1251
-			$dev = $this->Tools->fetch_object("devices", "id", $this->object_old[$k]);
1252
-			$this->object_old[$k] = $dev->hostname;
1253
-		}
1254
-		// new none
1255
-		if($v == 0)	{
1256
-			$v = "None";
1257
-		}
1258
-		if($v != "NULL") {
1259
-			$dev = $this->Tools->fetch_object("devices", "id", $v);
1260
-			$v = $dev->hostname;
1261
-		}
1262
-		//result
1263
-		return $v;
1264
-	}
1265
-
1266
-	/**
1267
-	 * Format vlan if change
1268
-	 *
1269
-	 * @access private
1270
-	 * @param string $k
1271
-	 * @param mixed $v
1272
-	 * @return void
1273
-	 */
1274
-	private function changelog_format_vlan_diff ($k, $v) {
1275
-		//old none
1276
-		if($this->object_old[$k] == 0)	{
1277
-			$this->object_old[$k] = "None";
1278
-		}
1279
-		elseif($this->object_old[$k] != "NULL") {
1280
-			$vlan = $this->Tools->fetch_object("vlans", "vlanId", $this->object_old[$k]);
1281
-			$this->object_old[$k] = $vlan->name." [$vlan->number]";
1282
-		}
1283
-		//new none
1284
-		if($v == 0)	{
1285
-			$v = "None";
1286
-		}
1287
-		elseif($v != "NULL") {
1288
-			$vlan = $this->Tools->fetch_object("vlans", "vlanId", $v);
1289
-			$v = $vlan->name." [$vlan->number]";
1290
-		}
1291
-		//result
1292
-		return $v;
1293
-	}
1294
-
1295
-	/**
1296
-	 * Format vrf if change
1297
-	 *
1298
-	 * @access private
1299
-	 * @param string $k
1300
-	 * @param mixed $v
1301
-	 * @return void
1302
-	 */
1303
-	private function changelog_format_vrf_diff ($k, $v) {
1304
-		//old none
1305
-		if($this->object_old[$k] == 0)	{
1306
-			$this->object_old[$k] = "None";
1307
-		}
1308
-		elseif($this->object_old[$k] != "NULL") {
1309
-			$vrf = $this->Tools->fetch_object("vrf", "vrfId", $this->object_old[$k]);
1310
-			$this->object_old[$k] = $vrf->name." [$vrf->description]";
1311
-		}
1312
-		// new none
1313
-		if($v == 0)	{
1314
-			$v = "None";
1315
-		}
1316
-		elseif($v != "NULL") {
1317
-			$vrf = $this->Tools->fetch_object("vrf", "vrfId", $v);
1318
-			$v = $vrf->name." [$vrf->description]";
1319
-		}
1320
-		//result
1321
-		return $v;
1322
-	}
1323
-
1324
-	/**
1325
-	 * Format NS if change
1326
-	 *
1327
-	 * @access private
1328
-	 * @param string $k
1329
-	 * @param mixed $v
1330
-	 * @return void
1331
-	 */
1332
-	private function changelog_format_ns_diff ($k, $v) {
1333
-		//old none
1334
-		if($this->object_old[$k] == 0)	{
1335
-			$this->object_old[$k] = "None";
1336
-		}
1337
-		elseif($this->object_old[$k] != "NULL") {
1338
-			$ns = $this->Tools->fetch_object("nameservers", "id", $this->object_old[$k]);
1339
-			$this->object_old[$k] = $ns->name." [".$ns->namesrv1."]";
1340
-		}
1341
-		// new none
1342
-		if($v == 0)	{
1343
-			$v = "None";
1344
-		}
1345
-		elseif($v != "NULL") {
1346
-			$ns = $this->Tools->fetch_object("nameservers", "id", $v);
1347
-			$v = $ns->name." [".$ns->namesrv1."]";
1348
-		}
1349
-		//result
1350
-		return $v;
1351
-	}
1352
-
1353
-	/**
1354
-	 * Format location change
1355
-	 *
1356
-	 * @access private
1357
-	 * @param string $k
1358
-	 * @param mixed $v
1359
-	 * @return void
1360
-	 */
1361
-	private function changelog_format_location_diff ($k, $v) {
1362
-		//old none
1363
-		if($this->object_old[$k] == 0)	{
1364
-			$this->object_old[$k] = "None";
1365
-		}
1366
-		elseif($this->object_old[$k] != "NULL") {
1367
-			$location = $this->Tools->fetch_object("locations", "id", $this->object_old[$k]);
1368
-			$this->object_old[$k] = strlen($location->description>0) ? $location->name." [$location->description]" : $location->name;
1369
-		}
1370
-		// new none
1371
-		if($v == 0)	{
1372
-			$v = "None";
1373
-		}
1374
-		elseif($v != "NULL") {
1375
-			$location = $this->Tools->fetch_object("locations", "id", $v);
1376
-			$v = strlen($location->description>0) ? $location->name." [$location->description]" : $location->name;
1377
-		}
1378
-		//result
1379
-		return $v;
1380
-	}
1381
-
1382
-	/**
1383
-	 * Format master section ifchange
1384
-	 *
1385
-	 * @access private
1386
-	 * @param string $k
1387
-	 * @param mixed $v
1388
-	 * @return void
1389
-	 */
1390
-	private function changelog_format_master_section_diff ($k, $v) {
1391
-		// old root
1392
-		if($this->object_old[$k]==0) {
1393
-			$this->object_old[$k] = "Root";
1394
-		}
1395
-		else {
1396
-			$section = $this->Sections->fetch_section ("id", $this->object_old[$k]);
1397
-			$this->object_old[$k] = $section->name;
1398
-		}
1399
-		// new root
1400
-		if($v==0) {
1401
-			$v = "Root";
1402
-		}
1403
-		else {
1404
-			$section = $this->Sections->fetch_section ("id", $v);
1405
-			$v = $section->name;
1406
-		}
1407
-		//result
1408
-		return $v;
1409
-	}
1410
-
1411
-	/**
1412
-	 * Format permissions on change - EDIT
1413
-	 *
1414
-	 * @access private
1415
-	 * @param string $k
1416
-	 * @param mixed $v
1417
-	 * @return string
1418
-	 */
1419
-	private function changelog_format_permission_diff ($k, $v) {
1420
-		// get old and compare
1421
-		$this->object_new['permissions'] = json_decode(str_replace("\\", "", $this->object_new['permissions']), true);		//Remove /
1422
-		$this->object_old['permissions'] = json_decode(str_replace("\\", "", $this->object_old['permissions']), true);		//Remove /
1423
-
1424
-		# Get all groups:
1425
-		$groups = (array) $this->Tools->fetch_all_objects("userGroups", "g_id");
1426
-		// rekey
1427
-		$out = array();
1428
-		foreach($groups as $g) {
1429
-			$out[$g->g_id]['g_name'] = $g->g_name;
1430
-		}
1431
-		$groups = $out;
1432
-
1433
-		// loop
1434
-		$val = array();
1435
-		if(is_array($this->object_new['permissions'])) {
1436
-			foreach($this->object_new['permissions'] as $group_id=>$p) {
1437
-				$val[] = $groups[$group_id]['g_name'] ." : ".$this->Subnets->parse_permissions($p);
1438
-			}
1439
-		}
1440
-		$this->object_old[$k] = "";
1441
-
1442
-		//result
1443
-		return implode(" ; ", $val);
1444
-	}
1445
-
1446
-	/**
1447
-	 * Make true / false from 0/1
1448
-	 *
1449
-	 * @access private
1450
-	 * @param mixed $k
1451
-	 * @param mixed $v
1452
-	 * @return void
1453
-	 */
1454
-	private function changelog_make_booleans ($k, $v) {
1455
-    	// init
1456
-    	$keys = array();
1457
-		// list of keys to be changed per object
1458
-		$keys['section'] = array("strictMode", "showVLAN", "showVRF");
1459
-		$keys['subnet']  = array("allowRequests", "showName", "pingSubnet", "discoverSubnet", "DNSrecursive", "DNSrecords", "isFull");
1460
-		$keys['ip_addr'] = array("is_gateway", "excludePing", "PTRignore");
1461
-
1462
-		// check
1463
-		if (array_key_exists($this->object_type, $keys)) {
1464
-			if (in_array($k, $keys[$this->object_type])) {
1465
-				if ($v=="0") { $this->object_old[$k] = "True";	return "False"; }
1466
-				else 		 { $this->object_old[$k] = "False"; return "True"; }
1467
-			}
1468
-			else {
1469
-				return $v;
1470
-			}
1471
-		}
1472
-		else {
1473
-			return $v;
1474
-		}
1475
-	}
1476
-
1477
-	/**
1478
-	 * Format permission on permission only change
1479
-	 *
1480
-	 * @access private
1481
-	 * @return void
1482
-	 */
1483
-	private function changelog_format_permission_change () {
1484
-		# get old and compare
1485
-		$this->object_new['permissions_change'] = json_decode(str_replace("\\", "", $this->object_new['permissions_change']), true);		//Remove /
1486
-
1487
-		# Get all groups:
1488
-		$groups = (array) $this->Tools->fetch_all_objects("userGroups", "g_id");
1489
-		// rekey
1490
-		$out = array();
1491
-		$log = array();
1492
-
1493
-		foreach($groups as $k=>$g) {
1494
-			// save
1495
-			$out[$g->g_id]['g_name'] = $g->g_name;
1496
-		}
1497
-		$groups = $out;
1498
-
1499
-		# reformat
1500
-		if($this->object_new['permissions_change']!="null") {
1501
-			$new_permissions = json_decode($this->object_new['permissions_change']);
1502
-			foreach($new_permissions as $group_id=>$p) {
1503
-				$log['Permissions'] .= "<br>". $groups[$group_id]['g_name'] ." : ".$this->Subnets->parse_permissions($p);
1504
-			}
1505
-		}
1506
-		//result
1507
-		return $log;
1508
-	}
1509
-
1510
-	/**
1511
-	 * fetches all changelogs
1512
-	 *
1513
-	 * @access public
1514
-	 * @param bool $filter (default: false)
1515
-	 * @param mixed $expr
1516
-	 * @param int $limit (default: 100)
1517
-	 * @return void
1518
-	 */
1519
-	public function fetch_all_changelogs ($filter = false, $expr, $limit = 100) {
1520
-    	# limit check
1521
-    	if(!is_numeric($limit))        { $this->Result->show("danger", "Invalid limit", true);	return false; }
1522
-
1523
-    	# begin query
1524
-			$subquery_filter1 = ""; $subquery_filter2 ="";
1525
-			if($filter) {
1526
-				/* replace * with % */
1527
-				if(substr($expr, 0, 1)=="*")								{ $expr[0] = "%"; }
1528
-				if(substr($expr, -1, 1)=="*")								{ $expr = substr_replace($expr, "%", -1);  }
1529
-				if(substr($expr, 0, 1)!="*" && substr($expr, -1, 1)!="*")	{ $expr = "%".$expr."%"; }
1530
-
1531
-				$subquery_filter1 = "AND (`coid`=:expr or `ctype`=:expr or `real_name` like :expr or `cdate` like :expr or `cdiff` like :expr or INET_NTOA(`ip_addr`) like :expr)";
1532
-				$subquery_filter2 = "AND (`coid`=:expr or `ctype`=:expr or `real_name` like :expr or `cdate` like :expr or `cdiff` like :expr)";
1533
-			}
1534
-			$query = "
1079
+            # reformat ip
1080
+            if (isset($this->object_old['ip_addr']))	{ $this->object_old['ip_addr'] = $this->Subnets->transform_address ($this->object_old['ip_addr'],"dotted"); }
1081
+            if (isset($this->object_new['ip_addr']))	{ $this->object_new['ip_addr'] = $this->Subnets->transform_address ($this->object_new['ip_addr'],"dotted"); }
1082
+
1083
+        }
1084
+        # remove subnet fields
1085
+        elseif($this->object_type == "subnet" || $this->object_type == "folder")	{
1086
+            // remove unneeded values
1087
+            unset(	$this->object_new['subnetId'],
1088
+                    $this->object_new['vrfIdOld'],
1089
+                    $this->object_new['permissions'],
1090
+                    $this->object_new['state'],
1091
+                    $this->object_new['ip']
1092
+                );
1093
+            unset(	$this->object_old['subnetId'],
1094
+                    $this->object_old['vrfIdOld'],
1095
+                    $this->object_old['permissions'],
1096
+                    $this->object_old['state'],
1097
+                    $this->object_old['ip']
1098
+                );
1099
+
1100
+            # folder
1101
+            if($this->object_type == "folder") {
1102
+                unset(
1103
+                    $this->object_new['linked_subnet'],
1104
+                    $this->object_new['firewallAddressObject'],
1105
+                    $this->object_new['vrfId'],
1106
+                    $this->object_new['allowRequests'],
1107
+                    $this->object_new['vlanId'],
1108
+                    $this->object_new['showName'],
1109
+                    $this->object_new['device'],
1110
+                    $this->object_new['pingSubnet'],
1111
+                    $this->object_new['discoverSubnet'],
1112
+                    $this->object_new['DNSrecursive'],
1113
+                    $this->object_new['DNSrecords'],
1114
+                    $this->object_new['nameserverId'],
1115
+                    $this->object_new['scanAgent'],
1116
+                    $this->object_new['isFull'],
1117
+                    $this->object_new['threshold'],
1118
+                    $this->object_new['lastScan'],
1119
+                    $this->object_new['lastDiscovery']
1120
+                );
1121
+                unset(
1122
+                    $this->object_old['linked_subnet'],
1123
+                    $this->object_old['firewallAddressObject'],
1124
+                    $this->object_old['vrfId'],
1125
+                    $this->object_old['allowRequests'],
1126
+                    $this->object_old['vlanId'],
1127
+                    $this->object_old['showName'],
1128
+                    $this->object_old['device'],
1129
+                    $this->object_old['pingSubnet'],
1130
+                    $this->object_old['discoverSubnet'],
1131
+                    $this->object_old['DNSrecursive'],
1132
+                    $this->object_old['DNSrecords'],
1133
+                    $this->object_old['nameserverId'],
1134
+                    $this->object_old['scanAgent'],
1135
+                    $this->object_old['isFull'],
1136
+                    $this->object_old['threshold'],
1137
+                    $this->object_old['lastScan'],
1138
+                    $this->object_old['lastDiscovery']
1139
+                );
1140
+            }
1141
+
1142
+            # if section does not change
1143
+            if($this->object_new['sectionId']==$this->object_new['sectionIdNew']) {
1144
+                unset(	$this->object_new['sectionIdNew']);
1145
+            }
1146
+            else {
1147
+                $this->object_old['sectionIdNew'] = $this->object_old['sectionId'];
1148
+            }
1149
+
1150
+            //transform subnet to IP address format
1151
+            if(strlen($this->object_new['subnet'])>0) 	{ $this->object_new['subnet'] = $this->Subnets->transform_address ($this->object_new['subnet'], "dotted");}
1152
+            if(strlen($this->object_old['subnet'])>0) 	{ $this->object_old['subnet'] = $this->Subnets->transform_address ($this->object_old['subnet'], "dotted");}
1153
+
1154
+            //remove subnet/mask for folders
1155
+            if (@$this->object_new['isFolder']=="1")	{ unset($this->object_new['subnet'], $this->object_new['mask']); }
1156
+            if (@$this->object_old['isFolder']=="1")	{ unset($this->object_old['subnet'], $this->object_old['mask']); }
1157
+        }
1158
+        # remove order fields
1159
+        elseif($this->object_type == "section") {
1160
+            unset($this->object_old['order']);
1161
+        }
1162
+
1163
+        # common
1164
+        unset($this->object_new['action']);
1165
+        unset($this->object_new['editDate'], $this->object_old['editDate']);
1166
+        unset($this->object_new['csrf_cookie']);
1167
+    }
1168
+
1169
+    /**
1170
+     * Formats tag from int to nam.
1171
+     *
1172
+     * @access private
1173
+     * @param string $k
1174
+     * @param mixed $v
1175
+     * @return void
1176
+     */
1177
+    private function changelog_format_tag_diff ($k, $v) {
1178
+        $this->object_old[$k] = $this->Addresses->address_type_index_to_type($this->object_old[$k]);
1179
+        $v 					  = $this->Addresses->address_type_index_to_type($v);
1180
+        //result
1181
+        return $v;
1182
+    }
1183
+
1184
+    /**
1185
+     * Formats section if change
1186
+     *
1187
+     * @access private
1188
+     * @param string $k
1189
+     * @param mixed $v
1190
+     * @return void
1191
+     */
1192
+    private function changelog_format_section_diff ($k, $v) {
1193
+        //get old and new device
1194
+        if($this->object_old[$k] != "NULL") {
1195
+            $section = $this->Sections->fetch_section ("id", $this->object_old[$k]);
1196
+            $this->object_old[$k] = $section->name." (id ".$section->id.")";
1197
+        }
1198
+        if($v != "NULL")	{
1199
+            $section = $this->Sections->fetch_section ("id", $v);
1200
+            $v = $section->name." (id ".$section->id.")";
1201
+        }
1202
+        //result
1203
+        return $v;
1204
+    }
1205
+
1206
+    /**
1207
+     * Formats master subnet if change
1208
+     *
1209
+     * @access private
1210
+     * @param string $k
1211
+     * @param mixed $v
1212
+     * @return string
1213
+     */
1214
+    private function changelog_format_master_subnet_diff ($k, $v) {
1215
+        //Old root or not
1216
+        if($this->object_old[$k]==0){
1217
+            $this->object_old[$k] = "Root";
1218
+        }
1219
+        else {
1220
+            $subnet = $this->Subnets->fetch_subnet("id", $this->object_old[$k]);
1221
+            $this->object_old[$k] = strlen($subnet->description)>0 ? $this->Subnets->transform_address($subnet->subnet, "dotted")."/$subnet->mask [$subnet->description]" : $this->Subnets->transform_address($subnet->subnet, "dotted")."/".$subnet->mask;
1222
+            $this->object_old[$k] .= " (id ".$subnet->id.")";
1223
+        }
1224
+        //New root or not
1225
+        if($v==0) {
1226
+            $v = "Root";
1227
+        }
1228
+        else {
1229
+            $subnet = $this->Subnets->fetch_subnet("id", $v);
1230
+            $v  = strlen($subnet->description)>0 ? $this->Subnets->transform_address($subnet->subnet, "dotted")."/$subnet->mask [$subnet->description]" : $this->Subnets->transform_address($subnet->subnet, "dotted")."/".$subnet->mask;
1231
+            $v .= " (id ".$subnet->id.")";
1232
+        }
1233
+        //result
1234
+        return $v;
1235
+    }
1236
+
1237
+    /**
1238
+     * Format device if change
1239
+     *
1240
+     * @access private
1241
+     * @param string $k
1242
+     * @param mixed $v
1243
+     * @return void
1244
+     */
1245
+    private function changelog_format_device_diff ($k, $v) {
1246
+        // old none
1247
+        if($this->object_old[$k] == 0)	{
1248
+            $this->object_old[$k] = "None";
1249
+        }
1250
+        elseif($this->object_old[$k] != "NULL") {
1251
+            $dev = $this->Tools->fetch_object("devices", "id", $this->object_old[$k]);
1252
+            $this->object_old[$k] = $dev->hostname;
1253
+        }
1254
+        // new none
1255
+        if($v == 0)	{
1256
+            $v = "None";
1257
+        }
1258
+        if($v != "NULL") {
1259
+            $dev = $this->Tools->fetch_object("devices", "id", $v);
1260
+            $v = $dev->hostname;
1261
+        }
1262
+        //result
1263
+        return $v;
1264
+    }
1265
+
1266
+    /**
1267
+     * Format vlan if change
1268
+     *
1269
+     * @access private
1270
+     * @param string $k
1271
+     * @param mixed $v
1272
+     * @return void
1273
+     */
1274
+    private function changelog_format_vlan_diff ($k, $v) {
1275
+        //old none
1276
+        if($this->object_old[$k] == 0)	{
1277
+            $this->object_old[$k] = "None";
1278
+        }
1279
+        elseif($this->object_old[$k] != "NULL") {
1280
+            $vlan = $this->Tools->fetch_object("vlans", "vlanId", $this->object_old[$k]);
1281
+            $this->object_old[$k] = $vlan->name." [$vlan->number]";
1282
+        }
1283
+        //new none
1284
+        if($v == 0)	{
1285
+            $v = "None";
1286
+        }
1287
+        elseif($v != "NULL") {
1288
+            $vlan = $this->Tools->fetch_object("vlans", "vlanId", $v);
1289
+            $v = $vlan->name." [$vlan->number]";
1290
+        }
1291
+        //result
1292
+        return $v;
1293
+    }
1294
+
1295
+    /**
1296
+     * Format vrf if change
1297
+     *
1298
+     * @access private
1299
+     * @param string $k
1300
+     * @param mixed $v
1301
+     * @return void
1302
+     */
1303
+    private function changelog_format_vrf_diff ($k, $v) {
1304
+        //old none
1305
+        if($this->object_old[$k] == 0)	{
1306
+            $this->object_old[$k] = "None";
1307
+        }
1308
+        elseif($this->object_old[$k] != "NULL") {
1309
+            $vrf = $this->Tools->fetch_object("vrf", "vrfId", $this->object_old[$k]);
1310
+            $this->object_old[$k] = $vrf->name." [$vrf->description]";
1311
+        }
1312
+        // new none
1313
+        if($v == 0)	{
1314
+            $v = "None";
1315
+        }
1316
+        elseif($v != "NULL") {
1317
+            $vrf = $this->Tools->fetch_object("vrf", "vrfId", $v);
1318
+            $v = $vrf->name." [$vrf->description]";
1319
+        }
1320
+        //result
1321
+        return $v;
1322
+    }
1323
+
1324
+    /**
1325
+     * Format NS if change
1326
+     *
1327
+     * @access private
1328
+     * @param string $k
1329
+     * @param mixed $v
1330
+     * @return void
1331
+     */
1332
+    private function changelog_format_ns_diff ($k, $v) {
1333
+        //old none
1334
+        if($this->object_old[$k] == 0)	{
1335
+            $this->object_old[$k] = "None";
1336
+        }
1337
+        elseif($this->object_old[$k] != "NULL") {
1338
+            $ns = $this->Tools->fetch_object("nameservers", "id", $this->object_old[$k]);
1339
+            $this->object_old[$k] = $ns->name." [".$ns->namesrv1."]";
1340
+        }
1341
+        // new none
1342
+        if($v == 0)	{
1343
+            $v = "None";
1344
+        }
1345
+        elseif($v != "NULL") {
1346
+            $ns = $this->Tools->fetch_object("nameservers", "id", $v);
1347
+            $v = $ns->name." [".$ns->namesrv1."]";
1348
+        }
1349
+        //result
1350
+        return $v;
1351
+    }
1352
+
1353
+    /**
1354
+     * Format location change
1355
+     *
1356
+     * @access private
1357
+     * @param string $k
1358
+     * @param mixed $v
1359
+     * @return void
1360
+     */
1361
+    private function changelog_format_location_diff ($k, $v) {
1362
+        //old none
1363
+        if($this->object_old[$k] == 0)	{
1364
+            $this->object_old[$k] = "None";
1365
+        }
1366
+        elseif($this->object_old[$k] != "NULL") {
1367
+            $location = $this->Tools->fetch_object("locations", "id", $this->object_old[$k]);
1368
+            $this->object_old[$k] = strlen($location->description>0) ? $location->name." [$location->description]" : $location->name;
1369
+        }
1370
+        // new none
1371
+        if($v == 0)	{
1372
+            $v = "None";
1373
+        }
1374
+        elseif($v != "NULL") {
1375
+            $location = $this->Tools->fetch_object("locations", "id", $v);
1376
+            $v = strlen($location->description>0) ? $location->name." [$location->description]" : $location->name;
1377
+        }
1378
+        //result
1379
+        return $v;
1380
+    }
1381
+
1382
+    /**
1383
+     * Format master section ifchange
1384
+     *
1385
+     * @access private
1386
+     * @param string $k
1387
+     * @param mixed $v
1388
+     * @return void
1389
+     */
1390
+    private function changelog_format_master_section_diff ($k, $v) {
1391
+        // old root
1392
+        if($this->object_old[$k]==0) {
1393
+            $this->object_old[$k] = "Root";
1394
+        }
1395
+        else {
1396
+            $section = $this->Sections->fetch_section ("id", $this->object_old[$k]);
1397
+            $this->object_old[$k] = $section->name;
1398
+        }
1399
+        // new root
1400
+        if($v==0) {
1401
+            $v = "Root";
1402
+        }
1403
+        else {
1404
+            $section = $this->Sections->fetch_section ("id", $v);
1405
+            $v = $section->name;
1406
+        }
1407
+        //result
1408
+        return $v;
1409
+    }
1410
+
1411
+    /**
1412
+     * Format permissions on change - EDIT
1413
+     *
1414
+     * @access private
1415
+     * @param string $k
1416
+     * @param mixed $v
1417
+     * @return string
1418
+     */
1419
+    private function changelog_format_permission_diff ($k, $v) {
1420
+        // get old and compare
1421
+        $this->object_new['permissions'] = json_decode(str_replace("\\", "", $this->object_new['permissions']), true);		//Remove /
1422
+        $this->object_old['permissions'] = json_decode(str_replace("\\", "", $this->object_old['permissions']), true);		//Remove /
1423
+
1424
+        # Get all groups:
1425
+        $groups = (array) $this->Tools->fetch_all_objects("userGroups", "g_id");
1426
+        // rekey
1427
+        $out = array();
1428
+        foreach($groups as $g) {
1429
+            $out[$g->g_id]['g_name'] = $g->g_name;
1430
+        }
1431
+        $groups = $out;
1432
+
1433
+        // loop
1434
+        $val = array();
1435
+        if(is_array($this->object_new['permissions'])) {
1436
+            foreach($this->object_new['permissions'] as $group_id=>$p) {
1437
+                $val[] = $groups[$group_id]['g_name'] ." : ".$this->Subnets->parse_permissions($p);
1438
+            }
1439
+        }
1440
+        $this->object_old[$k] = "";
1441
+
1442
+        //result
1443
+        return implode(" ; ", $val);
1444
+    }
1445
+
1446
+    /**
1447
+     * Make true / false from 0/1
1448
+     *
1449
+     * @access private
1450
+     * @param mixed $k
1451
+     * @param mixed $v
1452
+     * @return void
1453
+     */
1454
+    private function changelog_make_booleans ($k, $v) {
1455
+        // init
1456
+        $keys = array();
1457
+        // list of keys to be changed per object
1458
+        $keys['section'] = array("strictMode", "showVLAN", "showVRF");
1459
+        $keys['subnet']  = array("allowRequests", "showName", "pingSubnet", "discoverSubnet", "DNSrecursive", "DNSrecords", "isFull");
1460
+        $keys['ip_addr'] = array("is_gateway", "excludePing", "PTRignore");
1461
+
1462
+        // check
1463
+        if (array_key_exists($this->object_type, $keys)) {
1464
+            if (in_array($k, $keys[$this->object_type])) {
1465
+                if ($v=="0") { $this->object_old[$k] = "True";	return "False"; }
1466
+                else 		 { $this->object_old[$k] = "False"; return "True"; }
1467
+            }
1468
+            else {
1469
+                return $v;
1470
+            }
1471
+        }
1472
+        else {
1473
+            return $v;
1474
+        }
1475
+    }
1476
+
1477
+    /**
1478
+     * Format permission on permission only change
1479
+     *
1480
+     * @access private
1481
+     * @return void
1482
+     */
1483
+    private function changelog_format_permission_change () {
1484
+        # get old and compare
1485
+        $this->object_new['permissions_change'] = json_decode(str_replace("\\", "", $this->object_new['permissions_change']), true);		//Remove /
1486
+
1487
+        # Get all groups:
1488
+        $groups = (array) $this->Tools->fetch_all_objects("userGroups", "g_id");
1489
+        // rekey
1490
+        $out = array();
1491
+        $log = array();
1492
+
1493
+        foreach($groups as $k=>$g) {
1494
+            // save
1495
+            $out[$g->g_id]['g_name'] = $g->g_name;
1496
+        }
1497
+        $groups = $out;
1498
+
1499
+        # reformat
1500
+        if($this->object_new['permissions_change']!="null") {
1501
+            $new_permissions = json_decode($this->object_new['permissions_change']);
1502
+            foreach($new_permissions as $group_id=>$p) {
1503
+                $log['Permissions'] .= "<br>". $groups[$group_id]['g_name'] ." : ".$this->Subnets->parse_permissions($p);
1504
+            }
1505
+        }
1506
+        //result
1507
+        return $log;
1508
+    }
1509
+
1510
+    /**
1511
+     * fetches all changelogs
1512
+     *
1513
+     * @access public
1514
+     * @param bool $filter (default: false)
1515
+     * @param mixed $expr
1516
+     * @param int $limit (default: 100)
1517
+     * @return void
1518
+     */
1519
+    public function fetch_all_changelogs ($filter = false, $expr, $limit = 100) {
1520
+        # limit check
1521
+        if(!is_numeric($limit))        { $this->Result->show("danger", "Invalid limit", true);	return false; }
1522
+
1523
+        # begin query
1524
+            $subquery_filter1 = ""; $subquery_filter2 ="";
1525
+            if($filter) {
1526
+                /* replace * with % */
1527
+                if(substr($expr, 0, 1)=="*")								{ $expr[0] = "%"; }
1528
+                if(substr($expr, -1, 1)=="*")								{ $expr = substr_replace($expr, "%", -1);  }
1529
+                if(substr($expr, 0, 1)!="*" && substr($expr, -1, 1)!="*")	{ $expr = "%".$expr."%"; }
1530
+
1531
+                $subquery_filter1 = "AND (`coid`=:expr or `ctype`=:expr or `real_name` like :expr or `cdate` like :expr or `cdiff` like :expr or INET_NTOA(`ip_addr`) like :expr)";
1532
+                $subquery_filter2 = "AND (`coid`=:expr or `ctype`=:expr or `real_name` like :expr or `cdate` like :expr or `cdiff` like :expr)";
1533
+            }
1534
+            $query = "
1535 1535
 					select * from (
1536 1536
 					(select `cid`, `coid`,`ctype`,`real_name`,`caction`,`cresult`,`cdate`,`cdiff`,`ip_addr`,'mask',`sectionId`,`subnetId`,`ipaddresses`.`id` as `tid`,`users`.`id` as `userid`,`subnets`.`isFolder` as `isFolder`,`subnets`.`description` as `sDescription`
1537 1537
 					FROM `changelog`
@@ -1564,27 +1564,27 @@  discard block
 block discarded – undo
1564 1564
 
1565 1565
 					) as `ips` order by `cid` desc limit $limit;";
1566 1566
 
1567
-	    # fetch
1568
-	    try { $logs = $this->Database->getObjectsQuery($query, array("expr"=>$expr)); }
1569
-		catch (Exception $e) { $this->Result->show("danger", $e->getMessage(), false);	return false; }
1570
-
1571
-	    # return results
1572
-	    return $logs;
1573
-	}
1574
-
1575
-	/**
1576
-	 * fetches single changelog
1577
-	 *
1578
-	 * @access public
1579
-	 * @param int $id
1580
-	 * @return void
1581
-	 */
1582
-	public function fetch_changelog ($id) {
1583
-    	# limit check
1584
-    	if(!is_numeric($id))        { $this->Result->show("danger", "Invalid ID", true);	return false; }
1585
-
1586
-	    # set query
1587
-	    $query = "select * from (
1567
+        # fetch
1568
+        try { $logs = $this->Database->getObjectsQuery($query, array("expr"=>$expr)); }
1569
+        catch (Exception $e) { $this->Result->show("danger", $e->getMessage(), false);	return false; }
1570
+
1571
+        # return results
1572
+        return $logs;
1573
+    }
1574
+
1575
+    /**
1576
+     * fetches single changelog
1577
+     *
1578
+     * @access public
1579
+     * @param int $id
1580
+     * @return void
1581
+     */
1582
+    public function fetch_changelog ($id) {
1583
+        # limit check
1584
+        if(!is_numeric($id))        { $this->Result->show("danger", "Invalid ID", true);	return false; }
1585
+
1586
+        # set query
1587
+        $query = "select * from (
1588 1588
 					select `cid`, `coid`,`ctype`,`real_name`,`caction`,`cresult`,`cdate`,`cdiff`,`ip_addr`,'mask',`sectionId`,`subnetId`,`ipaddresses`.`id` as `tid`,`users`.`id` as `userid`,`subnets`.`isFolder` as `isFolder`,`subnets`.`description` as `sDescription`
1589 1589
 					FROM `changelog`
1590 1590
 					LEFT JOIN `users` ON `users`.`id`=`changelog`.`cuser`
@@ -1608,330 +1608,330 @@  discard block
 block discarded – undo
1608 1608
 					LEFT JOIN `sections` ON `sections`.`id`=`changelog`.`coid`
1609 1609
 					where `changelog`.`ctype` = 'section' and `changelog`.`cid` = :id
1610 1610
 				) as `ips`  order by `cid` desc limit 1;";
1611
-	    # fetch
1612
-	    try { $logs = $this->Database->getObjectQuery($query, array("id"=>$id)); }
1613
-		catch (Exception $e) {
1614
-			$this->Result->show("danger", $e->getMessage(), false);
1615
-			return false;
1616
-		}
1617
-
1618
-	    # return results
1619
-	    return $logs;
1620
-	}
1621
-
1622
-	/**
1623
-	 * Fetches changelog for addresses in subnet for all slave subnets
1624
-	 *
1625
-	 * @access public
1626
-	 * @param mixed $subnetId
1627
-	 * @param int $limit (default: 50)
1628
-	 * @return void
1629
-	 */
1630
-	public function fetch_subnet_addresses_changelog_recursive ($subnetId, $limit = 50) {
1631
-	    # get all addresses ids
1632
-	    $ips  = array();
1633
-	    if (!is_object($this->Addresses)) $this->Addresses = new Addresses ($this->Database);
1634
-	    $ips = $this->Addresses->fetch_subnet_addresses_recursive ($subnetId, false);
1635
-
1636
-	    # fetch changelog for IPs
1637
-	    if(sizeof($ips) > 0) {
1638
-		    # query
1639
-		    $query  = "select
1611
+        # fetch
1612
+        try { $logs = $this->Database->getObjectQuery($query, array("id"=>$id)); }
1613
+        catch (Exception $e) {
1614
+            $this->Result->show("danger", $e->getMessage(), false);
1615
+            return false;
1616
+        }
1617
+
1618
+        # return results
1619
+        return $logs;
1620
+    }
1621
+
1622
+    /**
1623
+     * Fetches changelog for addresses in subnet for all slave subnets
1624
+     *
1625
+     * @access public
1626
+     * @param mixed $subnetId
1627
+     * @param int $limit (default: 50)
1628
+     * @return void
1629
+     */
1630
+    public function fetch_subnet_addresses_changelog_recursive ($subnetId, $limit = 50) {
1631
+        # get all addresses ids
1632
+        $ips  = array();
1633
+        if (!is_object($this->Addresses)) $this->Addresses = new Addresses ($this->Database);
1634
+        $ips = $this->Addresses->fetch_subnet_addresses_recursive ($subnetId, false);
1635
+
1636
+        # fetch changelog for IPs
1637
+        if(sizeof($ips) > 0) {
1638
+            # query
1639
+            $query  = "select
1640 1640
 		    			`u`.`real_name`,`o`.`id`,`o`.`ip_addr`,`o`.`description`,`o`.`id`,`o`.`subnetId`,`c`.`caction`,`c`.`cresult`,`c`.`cdate`,`c`.`cdiff`
1641 1641
 						from `changelog` as `c`, `users` as `u`, `ipaddresses` as `o`
1642 1642
 						where `c`.`cuser` = `u`.`id` and `c`.`coid`=`o`.`id`
1643 1643
 						and (";
1644 1644
 
1645 1645
             $args = array();
1646
-			foreach($ips as $ip) {
1647
-			$query .= "`c`.`coid` = ? or ";
1648
-			$args[] = $ip->id;
1649
-			}
1650
-			$query  = substr($query, 0, -3);
1651
-			$query .= ") and `c`.`ctype` = 'ip_addr' order by `c`.`cid` desc limit $limit;";
1652
-
1653
-			# fetch
1654
-		    try { $logs = $this->Database->getObjectsQuery($query, array_filter($args)); }
1655
-			catch (Exception $e) { $this->Result->show("danger", $e->getMessage(), false);	return false; }
1656
-
1657
-		    # return result
1658
-		    return $logs;
1659
-	    }
1660
-		else {
1661
-			return false;
1662
-		}
1663
-	}
1664
-
1665
-	/**
1666
-	 * fetch changelog entries for specified type entry
1667
-	 *
1668
-	 * @param $object_type = 'ip_addr','subnet','section'
1669
-	 * @param $coid = objectId from ctype definition
1670
-	 * @param $long (default: false)
1671
-	 * @param $limit (default: 50)
1672
-	 */
1673
-	public function fetch_changlog_entries ($object_type, $coid, $long = false, $limit = 50) {
1674
-    	# limit check
1675
-    	if(!is_numeric($limit))        { $this->Result->show("danger", "Invalid limit", true);	return false; }
1676
-
1677
-	    # change ctype to match table
1678
-	    switch ($object_type) {
1679
-    	    // ip
1680
-    	    case "ip_addr":
1681
-    	        $object_typeTable = "ipaddresses";
1682
-    	        break;
1683
-    	    // section
1684
-     	    case "section":
1685
-    	        $object_typeTable = "sections";
1686
-    	        break;
1687
-    	    // subnet
1688
-     	    case "subnet":
1689
-    	        $object_typeTable = "subnets";
1690
-    	        break;
1691
-    	    // error
1692
-    	    default:
1693
-    	        $this->Result->show("danger", "Invalid object type", true);	return false;
1694
-	    }
1695
-
1696
-	    # query
1697
-	    if($long) {
1698
-		    $query = "select *
1646
+            foreach($ips as $ip) {
1647
+            $query .= "`c`.`coid` = ? or ";
1648
+            $args[] = $ip->id;
1649
+            }
1650
+            $query  = substr($query, 0, -3);
1651
+            $query .= ") and `c`.`ctype` = 'ip_addr' order by `c`.`cid` desc limit $limit;";
1652
+
1653
+            # fetch
1654
+            try { $logs = $this->Database->getObjectsQuery($query, array_filter($args)); }
1655
+            catch (Exception $e) { $this->Result->show("danger", $e->getMessage(), false);	return false; }
1656
+
1657
+            # return result
1658
+            return $logs;
1659
+        }
1660
+        else {
1661
+            return false;
1662
+        }
1663
+    }
1664
+
1665
+    /**
1666
+     * fetch changelog entries for specified type entry
1667
+     *
1668
+     * @param $object_type = 'ip_addr','subnet','section'
1669
+     * @param $coid = objectId from ctype definition
1670
+     * @param $long (default: false)
1671
+     * @param $limit (default: 50)
1672
+     */
1673
+    public function fetch_changlog_entries ($object_type, $coid, $long = false, $limit = 50) {
1674
+        # limit check
1675
+        if(!is_numeric($limit))        { $this->Result->show("danger", "Invalid limit", true);	return false; }
1676
+
1677
+        # change ctype to match table
1678
+        switch ($object_type) {
1679
+            // ip
1680
+            case "ip_addr":
1681
+                $object_typeTable = "ipaddresses";
1682
+                break;
1683
+            // section
1684
+                case "section":
1685
+                $object_typeTable = "sections";
1686
+                break;
1687
+            // subnet
1688
+                case "subnet":
1689
+                $object_typeTable = "subnets";
1690
+                break;
1691
+            // error
1692
+            default:
1693
+                $this->Result->show("danger", "Invalid object type", true);	return false;
1694
+        }
1695
+
1696
+        # query
1697
+        if($long) {
1698
+            $query = "select *
1699 1699
 						from `changelog` as `c`, `users` as `u`, `$object_typeTable` as `o`
1700 1700
 						where `c`.`cuser` = `u`.`id` and `c`.`coid`=`o`.`id`
1701 1701
 						and `c`.`coid` = ? and `c`.`ctype` = ? order by `c`.`cid` desc limit $limit;";
1702
-		}
1703
-		else {
1704
-		    $query = "select *
1702
+        }
1703
+        else {
1704
+            $query = "select *
1705 1705
 						from `changelog` as `c`, `users` as `u`
1706 1706
 						where `c`.`cuser` = `u`.`id`
1707 1707
 						and `c`.`coid` = ? and `c`.`ctype` = ? order by `c`.`cid` desc limit $limit;";
1708
-		}
1709
-	    # fetch
1710
-	    try { $logs = $this->Database->getObjectsQuery($query, array($coid, $object_type)); }
1711
-		catch (Exception $e) { $this->Result->show("danger", $e->getMessage(), false); return false; }
1712
-
1713
-	    # return result
1714
-	    return $logs;
1715
-	}
1716
-
1717
-	/**
1718
-	 * Fetches changelog entries for all slave subnets recursive
1719
-	 *
1720
-	 * @access public
1721
-	 * @param mixed $subnetId
1722
-	 * @param int $limit (default: 50)
1723
-	 * @return void
1724
-	 */
1725
-	public function fetch_subnet_slaves_changlog_entries_recursive($subnetId, $limit = 50) {
1726
-    	# limit check
1727
-    	if(!is_numeric($limit))        { $this->Result->show("danger", "Invalid limit", true);	return false; }
1728
-    	# $subnetId check
1729
-    	if(!is_numeric($subnetId))     { $this->Result->show("danger", "Invalid subnet Id", true);	return false; }
1730
-
1731
-		# fetch all slave subnet ids
1732
-		if (!is_object($this->Subnets)) $this->Subnets = new Subnets ($this->Database);
1733
-		$this->Subnets->reset_subnet_slaves_recursive ();
1734
-		$this->Subnets->fetch_subnet_slaves_recursive ($subnetId);
1735
-		# remove master subnet ID
1736
-		$key = array_search($subnetId, $this->Subnets->slaves);
1737
-		unset($this->Subnets->slaves[$key]);
1738
-		$this->Subnets->slaves = array_unique($this->Subnets->slaves);
1739
-
1740
-	    # if some slaves are present get changelog
1741
-	    if(sizeof($this->Subnets->slaves) > 0) {
1742
-		    # set query
1743
-		    $query  = "select
1708
+        }
1709
+        # fetch
1710
+        try { $logs = $this->Database->getObjectsQuery($query, array($coid, $object_type)); }
1711
+        catch (Exception $e) { $this->Result->show("danger", $e->getMessage(), false); return false; }
1712
+
1713
+        # return result
1714
+        return $logs;
1715
+    }
1716
+
1717
+    /**
1718
+     * Fetches changelog entries for all slave subnets recursive
1719
+     *
1720
+     * @access public
1721
+     * @param mixed $subnetId
1722
+     * @param int $limit (default: 50)
1723
+     * @return void
1724
+     */
1725
+    public function fetch_subnet_slaves_changlog_entries_recursive($subnetId, $limit = 50) {
1726
+        # limit check
1727
+        if(!is_numeric($limit))        { $this->Result->show("danger", "Invalid limit", true);	return false; }
1728
+        # $subnetId check
1729
+        if(!is_numeric($subnetId))     { $this->Result->show("danger", "Invalid subnet Id", true);	return false; }
1730
+
1731
+        # fetch all slave subnet ids
1732
+        if (!is_object($this->Subnets)) $this->Subnets = new Subnets ($this->Database);
1733
+        $this->Subnets->reset_subnet_slaves_recursive ();
1734
+        $this->Subnets->fetch_subnet_slaves_recursive ($subnetId);
1735
+        # remove master subnet ID
1736
+        $key = array_search($subnetId, $this->Subnets->slaves);
1737
+        unset($this->Subnets->slaves[$key]);
1738
+        $this->Subnets->slaves = array_unique($this->Subnets->slaves);
1739
+
1740
+        # if some slaves are present get changelog
1741
+        if(sizeof($this->Subnets->slaves) > 0) {
1742
+            # set query
1743
+            $query  = "select
1744 1744
 						`u`.`real_name`,`o`.`sectionId`,`o`.`subnet`,`o`.`mask`,`o`.`isFolder`,`o`.`description`,`o`.`id`,`c`.`caction`,`c`.`cresult`,`c`.`cdate`,`c`.`cdiff`  from `changelog` as `c`, `users` as `u`, `subnets` as `o`
1745 1745
 						where `c`.`cuser` = `u`.`id` and `c`.`coid`=`o`.`id`
1746 1746
 						and (";
1747
-			foreach($this->Subnets->slaves as $slaveId) {
1748
-			if(!isset($args)) $args = array();
1749
-			$query .= "`c`.`coid` = ? or ";
1750
-			$args[] = $slaveId;							//set keys
1751
-			}
1752
-			$query  = substr($query, 0, -3);
1753
-			$query .= ") and `c`.`ctype` = 'subnet' order by `c`.`cid` desc limit $limit;";
1747
+            foreach($this->Subnets->slaves as $slaveId) {
1748
+            if(!isset($args)) $args = array();
1749
+            $query .= "`c`.`coid` = ? or ";
1750
+            $args[] = $slaveId;							//set keys
1751
+            }
1752
+            $query  = substr($query, 0, -3);
1753
+            $query .= ") and `c`.`ctype` = 'subnet' order by `c`.`cid` desc limit $limit;";
1754
+
1755
+            # fetch
1756
+            try { $logs = $this->Database->getObjectsQuery($query, $args); }
1757
+            catch (Exception $e) { $this->Result->show("danger", $e->getMessage(), false);	return false; }
1758
+
1759
+            # return result
1760
+            return $logs;
1761
+        }
1762
+        else {
1763
+            return false;
1764
+        }
1765
+    }
1766
+
1767
+
1768
+
1769
+
1770
+
1771
+
1772
+
1773
+
1774
+
1775
+
1776
+
1777
+
1778
+    /**
1779
+     *	@changelog mail methods
1780
+     *	--------------------------------
1781
+     */
1782
+
1783
+    /**
1784
+     * Send mail on new changelog
1785
+     *
1786
+     * @access public
1787
+     * @param string $changelog
1788
+     * @return boolean
1789
+     */
1790
+    public function changelog_send_mail ($changelog) {
1791
+
1792
+        # initialize tools class
1793
+        if (!is_object($this->Tools)) $this->Tools = new Tools ($this->Database);
1794
+
1795
+        # set object
1796
+        $obj_details = $this->object_action == "add" ? $this->object_new : $this->object_old;
1797
+
1798
+        # change ip_addr
1799
+        $this->object_type = str_replace("ip_addr", "address", $this->object_type);
1800
+        $this->object_type = str_replace("ip_range", "address range", $this->object_type);
1801
+
1802
+        # folder
1803
+        if ( $this->object_new['isFolder']=="1" || $this->object_old['isFolder']=="1" )	{ $this->object_type = "folder"; }
1804
+
1805
+        # set subject
1806
+        $subject = "";
1807
+        if($this->object_action == "add") 		{ $subject = ucwords($this->object_type)." create notification"; }
1808
+        elseif($this->object_action == "edit") 	{ $subject = ucwords($this->object_type)." change notification"; }
1809
+        elseif($this->object_action == "delete"){ $subject = ucwords($this->object_type)." delete notification"; }
1810
+
1811
+        // if address we need subnet details !
1812
+        $address_subnet = array();
1813
+        if ($this->object_type=="address")		{ $address_subnet = (array) $this->Tools->fetch_object("subnets", "id", $obj_details['subnetId']); }
1814
+
1815
+        # set object details
1816
+        $details = "";
1817
+        if ($this->object_type=="section") 		{ $details = "<a style='font-family:Helvetica, Verdana, Arial, sans-serif; font-size:12px;color:#a0ce4e;' href='".$this->createURL().create_link("subnets",$obj_details['id'])."'>".$obj_details['name'] . "(".$obj_details['description'].") - id ".$obj_details['id']."</a>"; }
1818
+        elseif ($this->object_type=="subnet")	{ $details = "<a style='font-family:Helvetica, Verdana, Arial, sans-serif; font-size:12px;color:#a0ce4e;' href='".$this->createURL().create_link("subnets",$this->object_orig['sectionId'],$obj_details['id'])."'>".$this->Subnets->transform_address ($obj_details['subnet'], "dotted")."/".$obj_details['mask']." (".$obj_details['description'].") - id ".$obj_details['id']."</a>"; }
1819
+        elseif ($this->object_type=="folder")	{ $details = "<a style='font-family:Helvetica, Verdana, Arial, sans-serif; font-size:12px;color:#a0ce4e;' href='".$this->createURL().create_link("folder",$this->object_orig['sectionId'],$obj_details['id'])."'>".$obj_details['description']." - id ".$obj_details['id']."</a>"; }
1820
+        elseif ($this->object_type=="address")	{ $details = "<a style='font-family:Helvetica, Verdana, Arial, sans-serif; font-size:12px;color:#a0ce4e;' href='".$this->createURL().create_link("subnets",$this->object_orig['section'],$this->object_orig['subnetId'],"address-details",$this->object_orig['id'])."'>".$this->Subnets->transform_address ($obj_details['ip_addr'], "dotted")." ( hostname ".$obj_details['hostname'].", subnet: ".$this->Subnets->transform_address ($address_subnet['subnet'], "dotted")."/".$address_subnet['mask'].")- id ".$obj_details['id']."</a>"; }
1821
+        elseif ($this->object_type=="address range")	{ $details = $changelog; }
1822
+
1823
+        # remove subnet sectionId
1824
+        if($this->object_type=="subnet" && $this->object_action == "edit") {
1825
+            unset($obj_details['sectionId']);
1826
+        }
1827
+
1828
+        # set content
1829
+        $content = array();
1830
+        $content[] = "<div style='padding:10px;'>";
1831
+        $content[] = "<table>";
1832
+        $content[] = "<tr><td colspan='2'>$this->mail_font_style<strong>The following change was made on ipam:</strong></font></td></tr>";
1833
+        $content[] = "<tr><td colspan='2'>&nbsp;</td></tr>";
1834
+        $content[] = "<tr><td>$this->mail_font_style Object type:</font><td>$this->mail_font_style".ucwords($this->object_type)."</font></td></tr>";
1835
+        $content[] = "<tr><td>$this->mail_font_style Object details:</font><td>$this->mail_font_style_href".$details."</font></td></tr>";
1836
+        $content[] = "<tr><td>$this->mail_font_style User:</font><td>$this->mail_font_style".$this->user->real_name." (".$this->user->username.")"."</font></td></tr>";
1837
+        $content[] = "<tr><td>$this->mail_font_style Action:</font><td>$this->mail_font_style".$this->object_action."</font></td></tr>";
1838
+        $content[] = "<tr><td>$this->mail_font_style Date:</font><td>$this->mail_font_style".date("Y-m-d H:i:s")."</font></td></tr>";
1839
+        $content[] = "<tr><td colspan='2'><hr style='height:0px;border-top:0px;border-bottom:1px solid #ddd;'></td></tr>";
1840
+        $content[] = "<tr><td style='vertical-align:top;'>$this->mail_font_style Changes:</td>";
1841
+        $content[] = "<td>";
1842
+        // add changelog
1843
+        $changelog = str_replace("\r\n", "<br>",$changelog);
1844
+        $changelog = array_filter(explode("<br>", $changelog));
1845
+        $content[] = "<table>";
1846
+
1847
+        foreach ($changelog as $c) {
1848
+            // field
1849
+            $field = explode(":", $c);
1850
+            $value = explode("=>", $field[1]);
1851
+
1852
+            // format field
1853
+            $field = trim(str_replace(array("[","]"), "", $field[0]));
1854
+
1855
+            // no isFolder
1856
+            if($field!=="isFolder") {
1857
+                if(is_array($this->changelog_keys[$this->object_type])) {
1858
+                    if (array_key_exists($field, $this->changelog_keys[$this->object_type])) {
1859
+                        $field = $this->changelog_keys[$this->object_type][$field];
1860
+                    }
1861
+                }
1862
+
1863
+                $content[] = "<tr>";
1864
+                $content[] = "  <td>$this->mail_font_style<strong> $field</strong>: </font></td>";
1865
+                $content[] = "  <td>$this->mail_font_style ".trim($value[0])." </font></td>";
1866
+                if($this->object_action=="edit") {
1867
+                $content[] = "  <td>$this->mail_font_style => </font></td>";
1868
+                $content[] = "  <td>$this->mail_font_style ".trim($value[1])." </font></td>";
1869
+                }
1870
+                $content[] = "</tr>";
1871
+            }
1872
+        }
1873
+        $content[] = "</table>";
1874
+
1875
+        $content[] = "</font></td></tr>";
1876
+        $content[] = "</table>";
1877
+        $content[] = "</div>";
1878
+
1879
+        # set plain content
1880
+        $content_plain = array();
1881
+        $content_plain[] = "Object type: ".$this->object_type;
1882
+        $content_plain[] = "Object details: ".strip_tags($details);
1883
+        $content_plain[] = "User: ".$this->user->real_name." (".$this->user->username.")";
1884
+        $content_plain[] = "Action: ".$this->object_action;
1885
+        $content_plain[] = "Date: ".date("Y-m-d H:i:s");
1886
+        $content_plain[] = "\r\n--------------------\r\n";
1887
+        $content_plain[] = implode("\r\n", (array) $changelog);
1888
+
1889
+
1890
+        # get all admins and check who to end mail to
1891
+        //subnets, addresses - send mail to normal users also
1892
+        if ($this->object_type=="subnet" || $this->object_type=="address") {
1893
+            if($this->object_type=="subnet") {
1894
+                $recipients = $this->changelog_mail_get_recipients ($obj_details['id']);
1895
+            }
1896
+            else {
1897
+                $recipients = $this->changelog_mail_get_recipients ($obj_details['subnetId']);
1898
+            }
1899
+        }
1900
+        else {
1901
+            $recipients = $this->changelog_mail_get_recipients (false);
1902
+        }
1903
+        if($recipients ===false) {
1904
+            return true;
1905
+        }
1906
+
1907
+        # try to send
1908
+        try {
1909
+            # fetch mailer settings
1910
+            $mail_settings = $this->Tools->fetch_object("settingsMail", "id", 1);
1911
+
1912
+            # initialize mailer
1913
+            $phpipam_mail = new phpipam_mail($this->settings, $mail_settings);
1914
+
1915
+            // set content
1916
+            $content 		= $phpipam_mail->generate_message (implode("\r\n", $content));
1917
+            $content_plain = implode("\r\n",$content_plain);
1918
+
1919
+            $phpipam_mail->Php_mailer->setFrom($mail_settings->mAdminMail, $mail_settings->mAdminName);
1920
+            foreach($recipients as $r) {
1921
+            $phpipam_mail->Php_mailer->addAddress(addslashes(trim($r->email)));
1922
+            }
1923
+            $phpipam_mail->Php_mailer->Subject = $subject;
1924
+            $phpipam_mail->Php_mailer->msgHTML($content);
1925
+            $phpipam_mail->Php_mailer->AltBody = $content_plain;
1926
+            //send
1927
+            $phpipam_mail->Php_mailer->send();
1928
+        } catch (phpmailerException $e) {
1929
+            $this->Result->show("danger", "Mailer Error: ".$e->errorMessage(), true);
1930
+        } catch (Exception $e) {
1931
+            $this->Result->show("danger", "Mailer Error: ".$e->getMessage(), true);
1932
+        }
1754 1933
 
1755
-			# fetch
1756
-		    try { $logs = $this->Database->getObjectsQuery($query, $args); }
1757
-			catch (Exception $e) { $this->Result->show("danger", $e->getMessage(), false);	return false; }
1758
-
1759
-		    # return result
1760
-		    return $logs;
1761
-	    }
1762
-		else {
1763
-			return false;
1764
-		}
1765
-	}
1766
-
1767
-
1768
-
1769
-
1770
-
1771
-
1772
-
1773
-
1774
-
1775
-
1776
-
1777
-
1778
-	/**
1779
-	 *	@changelog mail methods
1780
-	 *	--------------------------------
1781
-	 */
1782
-
1783
-	/**
1784
-	 * Send mail on new changelog
1785
-	 *
1786
-	 * @access public
1787
-	 * @param string $changelog
1788
-	 * @return boolean
1789
-	 */
1790
-	public function changelog_send_mail ($changelog) {
1791
-
1792
-		# initialize tools class
1793
-		if (!is_object($this->Tools)) $this->Tools = new Tools ($this->Database);
1794
-
1795
-		# set object
1796
-		$obj_details = $this->object_action == "add" ? $this->object_new : $this->object_old;
1797
-
1798
-		# change ip_addr
1799
-		$this->object_type = str_replace("ip_addr", "address", $this->object_type);
1800
-		$this->object_type = str_replace("ip_range", "address range", $this->object_type);
1801
-
1802
-		# folder
1803
-		if ( $this->object_new['isFolder']=="1" || $this->object_old['isFolder']=="1" )	{ $this->object_type = "folder"; }
1804
-
1805
-		# set subject
1806
-		$subject = "";
1807
-		if($this->object_action == "add") 		{ $subject = ucwords($this->object_type)." create notification"; }
1808
-		elseif($this->object_action == "edit") 	{ $subject = ucwords($this->object_type)." change notification"; }
1809
-		elseif($this->object_action == "delete"){ $subject = ucwords($this->object_type)." delete notification"; }
1810
-
1811
-		// if address we need subnet details !
1812
-		$address_subnet = array();
1813
-		if ($this->object_type=="address")		{ $address_subnet = (array) $this->Tools->fetch_object("subnets", "id", $obj_details['subnetId']); }
1814
-
1815
-		# set object details
1816
-		$details = "";
1817
-		if ($this->object_type=="section") 		{ $details = "<a style='font-family:Helvetica, Verdana, Arial, sans-serif; font-size:12px;color:#a0ce4e;' href='".$this->createURL().create_link("subnets",$obj_details['id'])."'>".$obj_details['name'] . "(".$obj_details['description'].") - id ".$obj_details['id']."</a>"; }
1818
-		elseif ($this->object_type=="subnet")	{ $details = "<a style='font-family:Helvetica, Verdana, Arial, sans-serif; font-size:12px;color:#a0ce4e;' href='".$this->createURL().create_link("subnets",$this->object_orig['sectionId'],$obj_details['id'])."'>".$this->Subnets->transform_address ($obj_details['subnet'], "dotted")."/".$obj_details['mask']." (".$obj_details['description'].") - id ".$obj_details['id']."</a>"; }
1819
-		elseif ($this->object_type=="folder")	{ $details = "<a style='font-family:Helvetica, Verdana, Arial, sans-serif; font-size:12px;color:#a0ce4e;' href='".$this->createURL().create_link("folder",$this->object_orig['sectionId'],$obj_details['id'])."'>".$obj_details['description']." - id ".$obj_details['id']."</a>"; }
1820
-		elseif ($this->object_type=="address")	{ $details = "<a style='font-family:Helvetica, Verdana, Arial, sans-serif; font-size:12px;color:#a0ce4e;' href='".$this->createURL().create_link("subnets",$this->object_orig['section'],$this->object_orig['subnetId'],"address-details",$this->object_orig['id'])."'>".$this->Subnets->transform_address ($obj_details['ip_addr'], "dotted")." ( hostname ".$obj_details['hostname'].", subnet: ".$this->Subnets->transform_address ($address_subnet['subnet'], "dotted")."/".$address_subnet['mask'].")- id ".$obj_details['id']."</a>"; }
1821
-		elseif ($this->object_type=="address range")	{ $details = $changelog; }
1822
-
1823
-		# remove subnet sectionId
1824
-		if($this->object_type=="subnet" && $this->object_action == "edit") {
1825
-			unset($obj_details['sectionId']);
1826
-		}
1827
-
1828
-		# set content
1829
-		$content = array();
1830
-		$content[] = "<div style='padding:10px;'>";
1831
-		$content[] = "<table>";
1832
-		$content[] = "<tr><td colspan='2'>$this->mail_font_style<strong>The following change was made on ipam:</strong></font></td></tr>";
1833
-		$content[] = "<tr><td colspan='2'>&nbsp;</td></tr>";
1834
-		$content[] = "<tr><td>$this->mail_font_style Object type:</font><td>$this->mail_font_style".ucwords($this->object_type)."</font></td></tr>";
1835
-		$content[] = "<tr><td>$this->mail_font_style Object details:</font><td>$this->mail_font_style_href".$details."</font></td></tr>";
1836
-		$content[] = "<tr><td>$this->mail_font_style User:</font><td>$this->mail_font_style".$this->user->real_name." (".$this->user->username.")"."</font></td></tr>";
1837
-		$content[] = "<tr><td>$this->mail_font_style Action:</font><td>$this->mail_font_style".$this->object_action."</font></td></tr>";
1838
-		$content[] = "<tr><td>$this->mail_font_style Date:</font><td>$this->mail_font_style".date("Y-m-d H:i:s")."</font></td></tr>";
1839
-		$content[] = "<tr><td colspan='2'><hr style='height:0px;border-top:0px;border-bottom:1px solid #ddd;'></td></tr>";
1840
-		$content[] = "<tr><td style='vertical-align:top;'>$this->mail_font_style Changes:</td>";
1841
-		$content[] = "<td>";
1842
-		// add changelog
1843
-		$changelog = str_replace("\r\n", "<br>",$changelog);
1844
-		$changelog = array_filter(explode("<br>", $changelog));
1845
-		$content[] = "<table>";
1846
-
1847
-		foreach ($changelog as $c) {
1848
-    		// field
1849
-    		$field = explode(":", $c);
1850
-    	    $value = explode("=>", $field[1]);
1851
-
1852
-    	    // format field
1853
-    	    $field = trim(str_replace(array("[","]"), "", $field[0]));
1854
-
1855
-    	    // no isFolder
1856
-    	    if($field!=="isFolder") {
1857
-	    	    if(is_array($this->changelog_keys[$this->object_type])) {
1858
-	        	    if (array_key_exists($field, $this->changelog_keys[$this->object_type])) {
1859
-	            	    $field = $this->changelog_keys[$this->object_type][$field];
1860
-	        	    }
1861
-	    	    }
1862
-
1863
-	    		$content[] = "<tr>";
1864
-	    		$content[] = "  <td>$this->mail_font_style<strong> $field</strong>: </font></td>";
1865
-	    		$content[] = "  <td>$this->mail_font_style ".trim($value[0])." </font></td>";
1866
-	    		if($this->object_action=="edit") {
1867
-	    		$content[] = "  <td>$this->mail_font_style => </font></td>";
1868
-	    		$content[] = "  <td>$this->mail_font_style ".trim($value[1])." </font></td>";
1869
-	    		}
1870
-	    		$content[] = "</tr>";
1871
-	    	}
1872
-		}
1873
-		$content[] = "</table>";
1874
-
1875
-		$content[] = "</font></td></tr>";
1876
-		$content[] = "</table>";
1877
-		$content[] = "</div>";
1878
-
1879
-		# set plain content
1880
-		$content_plain = array();
1881
-		$content_plain[] = "Object type: ".$this->object_type;
1882
-		$content_plain[] = "Object details: ".strip_tags($details);
1883
-		$content_plain[] = "User: ".$this->user->real_name." (".$this->user->username.")";
1884
-		$content_plain[] = "Action: ".$this->object_action;
1885
-		$content_plain[] = "Date: ".date("Y-m-d H:i:s");
1886
-		$content_plain[] = "\r\n--------------------\r\n";
1887
-		$content_plain[] = implode("\r\n", (array) $changelog);
1888
-
1889
-
1890
-		# get all admins and check who to end mail to
1891
-		//subnets, addresses - send mail to normal users also
1892
-		if ($this->object_type=="subnet" || $this->object_type=="address") {
1893
-    		if($this->object_type=="subnet") {
1894
-        		$recipients = $this->changelog_mail_get_recipients ($obj_details['id']);
1895
-    		}
1896
-    		else {
1897
-        		$recipients = $this->changelog_mail_get_recipients ($obj_details['subnetId']);
1898
-    		}
1899
-		}
1900
-		else {
1901
-    		$recipients = $this->changelog_mail_get_recipients (false);
1902
-		}
1903
-		if($recipients ===false) {
1904
-    		return true;
1905
-        }
1906
-
1907
-		# try to send
1908
-		try {
1909
-			# fetch mailer settings
1910
-			$mail_settings = $this->Tools->fetch_object("settingsMail", "id", 1);
1911
-
1912
-			# initialize mailer
1913
-			$phpipam_mail = new phpipam_mail($this->settings, $mail_settings);
1914
-
1915
-			// set content
1916
-			$content 		= $phpipam_mail->generate_message (implode("\r\n", $content));
1917
-			$content_plain = implode("\r\n",$content_plain);
1918
-
1919
-			$phpipam_mail->Php_mailer->setFrom($mail_settings->mAdminMail, $mail_settings->mAdminName);
1920
-			foreach($recipients as $r) {
1921
-			$phpipam_mail->Php_mailer->addAddress(addslashes(trim($r->email)));
1922
-			}
1923
-			$phpipam_mail->Php_mailer->Subject = $subject;
1924
-			$phpipam_mail->Php_mailer->msgHTML($content);
1925
-			$phpipam_mail->Php_mailer->AltBody = $content_plain;
1926
-			//send
1927
-			$phpipam_mail->Php_mailer->send();
1928
-		} catch (phpmailerException $e) {
1929
-			$this->Result->show("danger", "Mailer Error: ".$e->errorMessage(), true);
1930
-		} catch (Exception $e) {
1931
-			$this->Result->show("danger", "Mailer Error: ".$e->getMessage(), true);
1932
-		}
1933
-
1934
-		# ok
1935
-		return true;
1936
-	}
1934
+        # ok
1935
+        return true;
1936
+    }
1937 1937
 }
Please login to merge, or discard this patch.
Spacing   +293 added lines, -293 removed lines patch added patch discarded remove patch
@@ -147,7 +147,7 @@  discard block
 block discarded – undo
147 147
 	 * @var mixed
148 148
 	 * @access protected
149 149
 	 */
150
-	protected $log_username	= null;
150
+	protected $log_username = null;
151 151
 
152 152
 	/**
153 153
 	 * user details
@@ -165,7 +165,7 @@  discard block
 block discarded – undo
165 165
 	 * @var mixed
166 166
 	 * @access protected
167 167
 	 */
168
-	protected $user_id	= null;
168
+	protected $user_id = null;
169 169
 
170 170
 	/**
171 171
 	 * Changelog keys for nicer display fo changelog
@@ -313,16 +313,16 @@  discard block
 block discarded – undo
313 313
 	 * @param Database_PDO $database
314 314
 	 * @param mixed $settings (default: null)
315 315
 	 */
316
-	public function __construct (Database_PDO $database, $settings = null) {
316
+	public function __construct(Database_PDO $database, $settings = null) {
317 317
 		# Save database object
318 318
 		$this->Database = $database;
319 319
 		# Result
320
-		$this->Result = new Result ();
320
+		$this->Result = new Result();
321 321
 		# User
322 322
 		$this->log_username = @$_SESSION['ipamusername'];
323 323
 
324 324
 		# settings
325
-		if ($settings===null || $settings===false) {
325
+		if ($settings === null || $settings === false) {
326 326
 			$this->get_settings(); #assigns $this->settings internally
327 327
 		}
328 328
 		else {
@@ -331,7 +331,7 @@  discard block
 block discarded – undo
331 331
 		# debugging
332 332
 		$this->set_debugging();
333 333
 		# set log type
334
-		$this->set_log_type ();
334
+		$this->set_log_type();
335 335
 	}
336 336
 
337 337
 
@@ -349,7 +349,7 @@  discard block
 block discarded – undo
349 349
 	 * @access private
350 350
 	 * @return void
351 351
 	 */
352
-	private function set_log_type () {
352
+	private function set_log_type() {
353 353
 		# check settings
354 354
 		$this->log_type = $this->settings->log;
355 355
 	}
@@ -360,9 +360,9 @@  discard block
 block discarded – undo
360 360
 	 * @access private
361 361
 	 * @return void
362 362
 	 */
363
-	private function get_active_user_id () {
363
+	private function get_active_user_id() {
364 364
 		# cache
365
-		if ($this->user_id===null) {
365
+		if ($this->user_id === null) {
366 366
 			# null
367 367
 			$user_id = null;
368 368
 			if (!isset($_SESSION['ipamusername'])) {
@@ -371,7 +371,7 @@  discard block
 block discarded – undo
371 371
 				// so let's get a user_id
372 372
 				if (array_key_exists("HTTP_PHPIPAM_TOKEN", $_SERVER)) {
373 373
 					$admin = new Admin($this->Database, False);
374
-					$token = $admin->fetch_object ("users", "token", $_SERVER['HTTP_PHPIPAM_TOKEN']);
374
+					$token = $admin->fetch_object("users", "token", $_SERVER['HTTP_PHPIPAM_TOKEN']);
375 375
 					if ($token === False) {
376 376
 						$this->user_id = null;
377 377
 					}
@@ -409,20 +409,20 @@  discard block
 block discarded – undo
409 409
 	 * @param mixed $username (default: NULL)
410 410
 	 * @return void
411 411
 	 */
412
-	public function write ($command, $details = NULL, $severity = 0, $username = null) {
412
+	public function write($command, $details = NULL, $severity = 0, $username = null) {
413 413
 		// save provided values
414 414
 		$this->log_command = $command;
415 415
 		$this->log_details = $details;
416 416
 		$this->log_severity = $severity;
417
-		$this->log_username	= $username===null ? $this->log_username : $username;
417
+		$this->log_username	= $username === null ? $this->log_username : $username;
418 418
 
419 419
 		// validate
420
-		!is_null($this->log_command) ? : $this->Result->show("danger", _("Invalid log command"));
420
+		!is_null($this->log_command) ?: $this->Result->show("danger", _("Invalid log command"));
421 421
 
422 422
 		// execute
423
-		if ($this->log_type == "syslog")	{ $this->syslog_write (); }
424
-		elseif ($this->log_type == "both")	{ $this->database_write_log (); $this->syslog_write (); }
425
-		else								{ $this->database_write_log (); }
423
+		if ($this->log_type == "syslog") { $this->syslog_write(); }
424
+		elseif ($this->log_type == "both") { $this->database_write_log(); $this->syslog_write(); }
425
+		else { $this->database_write_log(); }
426 426
 	}
427 427
 
428 428
 
@@ -462,16 +462,16 @@  discard block
 block discarded – undo
462 462
 	 * @access private
463 463
 	 * @return void
464 464
 	 */
465
-	private function syslog_write () {
465
+	private function syslog_write() {
466 466
 		# set facility
467
-		$this->syslog_set_facility ();
467
+		$this->syslog_set_facility();
468 468
 		# set priority
469
-		$this->syslog_set_priority ();
469
+		$this->syslog_set_priority();
470 470
 		# format details
471
-		$this->syslog_format_details ();
471
+		$this->syslog_format_details();
472 472
 
473 473
 		# add username if present
474
-		$username = $this->log_username!==null ? $this->log_username." | " : "";
474
+		$username = $this->log_username !== null ? $this->log_username." | " : "";
475 475
 
476 476
 		# open syslog and write log
477 477
 		openlog('phpipam', LOG_NDELAY | LOG_PID, $this->syslog_facility);
@@ -487,14 +487,14 @@  discard block
 block discarded – undo
487 487
 	 * @access private
488 488
 	 * @return void
489 489
 	 */
490
-	private function syslog_set_facility () {
490
+	private function syslog_set_facility() {
491 491
 		# for windows we can only use LOG_USER
492
-		if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN')		{ $facility = "LOG_USER"; }
492
+		if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') { $facility = "LOG_USER"; }
493 493
 		else {
494 494
 			//login, logout
495
-			if (strpos($this->log_command, "login")>0 ||
496
-				strpos($this->log_command, "logged out")>0) { $facility = "LOG_AUTH"; }
497
-			else 											{ $facility = "LOG_USER"; }
495
+			if (strpos($this->log_command, "login") > 0 ||
496
+				strpos($this->log_command, "logged out") > 0) { $facility = "LOG_AUTH"; }
497
+			else { $facility = "LOG_USER"; }
498 498
 		}
499 499
 		# save
500 500
 		$this->syslog_facility = constant($facility);
@@ -506,7 +506,7 @@  discard block
 block discarded – undo
506 506
 	 * @access private
507 507
 	 * @return void
508 508
 	 */
509
-	private function syslog_set_priority () {
509
+	private function syslog_set_priority() {
510 510
     	// init
511 511
     	$priorities = array();
512 512
 		# definitions
@@ -519,9 +519,9 @@  discard block
 block discarded – undo
519 519
 		$priorities[] = "LOG_INFO";
520 520
 		$priorities[] = "LOG_DEBUG";
521 521
 		# set
522
-		if ($this->log_severity == "2")		{ $priority = "LOG_ALERT"; }
523
-		elseif ($this->log_severity == "1")	{ $priority = "LOG_WARNING"; }
524
-		else								{ $priority = "LOG_DEBUG"; }
522
+		if ($this->log_severity == "2") { $priority = "LOG_ALERT"; }
523
+		elseif ($this->log_severity == "1") { $priority = "LOG_WARNING"; }
524
+		else { $priority = "LOG_DEBUG"; }
525 525
 		# set
526 526
 		$this->syslog_priority = constant($priority);
527 527
 	}
@@ -532,10 +532,10 @@  discard block
 block discarded – undo
532 532
 	 * @access private
533 533
 	 * @return void
534 534
 	 */
535
-	private function syslog_format_details () {
535
+	private function syslog_format_details() {
536 536
 		// replace <br>
537
-		$this->log_details = str_replace("<br>", ",",$this->log_details);
538
-		$this->log_details = str_replace("<hr>", ",",$this->log_details);
537
+		$this->log_details = str_replace("<br>", ",", $this->log_details);
538
+		$this->log_details = str_replace("<hr>", ",", $this->log_details);
539 539
 		// replace spaces
540 540
 		$this->log_details = trim($this->log_details, ",");
541 541
 	}
@@ -547,29 +547,29 @@  discard block
 block discarded – undo
547 547
 	 * @param mixed $changelog
548 548
 	 * @return void
549 549
 	 */
550
-	private function syslog_write_changelog ($changelog) {
550
+	private function syslog_write_changelog($changelog) {
551 551
 		# fetch user id
552
-		$this->get_active_user_id ();
552
+		$this->get_active_user_id();
553 553
 		# set update id based on action
554
-		if ($this->object_action=="add")	{ $obj_id = $this->object_new['id']; }
555
-		else								{ $obj_id = $this->object_old['id']; }
554
+		if ($this->object_action == "add") { $obj_id = $this->object_new['id']; }
555
+		else { $obj_id = $this->object_old['id']; }
556 556
 
557 557
 		# format
558
-		$changelog = str_replace("<br>", ",",$changelog);
559
-		$changelog = str_replace("<hr>", ",",$changelog);
558
+		$changelog = str_replace("<br>", ",", $changelog);
559
+		$changelog = str_replace("<hr>", ",", $changelog);
560 560
 
561 561
 		# formulate
562 562
 		$log = array();
563
-        if(isset($changelog)) {
563
+        if (isset($changelog)) {
564 564
             if (is_array($changelog)) {
565
-        		foreach($changelog as $k=>$l) {
565
+        		foreach ($changelog as $k=>$l) {
566 566
     	    		$log[] = "$k: $l";
567 567
     		    }
568 568
 		    }
569 569
 
570 570
     		# open syslog and write log
571 571
     		openlog('phpipam-changelog', LOG_NDELAY | LOG_PID, LOG_USER);
572
-    		syslog(LOG_DEBUG, "changelog | $this->log_username | $this->object_type | $obj_id | $this->object_action | ".date("Y-m-d H:i:s")." | ".implode(", ",$log));
572
+    		syslog(LOG_DEBUG, "changelog | $this->log_username | $this->object_type | $obj_id | $this->object_action | ".date("Y-m-d H:i:s")." | ".implode(", ", $log));
573 573
     		# close
574 574
     		closelog();
575 575
         }
@@ -596,7 +596,7 @@  discard block
 block discarded – undo
596 596
 	 * @access private
597 597
 	 * @return boolean
598 598
 	 */
599
-	private function database_write_log () {
599
+	private function database_write_log() {
600 600
 	    # set values
601 601
 	    $values = array(
602 602
 	    			"command"=>$this->log_command,
@@ -633,42 +633,42 @@  discard block
 block discarded – undo
633 633
 	 * @param mixed $warning (default: Off)
634 634
 	 * @return void
635 635
 	 */
636
-	public function fetch_logs ($logCount, $direction = NULL, $lastId = NULL, $highestId = NULL, $informational = "off", $notice = "off", $warning = "off") {
636
+	public function fetch_logs($logCount, $direction = NULL, $lastId = NULL, $highestId = NULL, $informational = "off", $notice = "off", $warning = "off") {
637 637
 
638 638
     	# check for lastId - must be numeric
639
-    	if(!is_numeric($logCount))      { $this->Result->show("danger", "Invalid logcount value", true);	return false; }
640
-    	if($direction!==NULL) {
641
-            if($direction!="next" && $direction!="prev" && $direction!="") {
642
-                                        { $this->Result->show("danger", "Invalid direction", true);	return false; }
639
+    	if (!is_numeric($logCount)) { $this->Result->show("danger", "Invalid logcount value", true); return false; }
640
+    	if ($direction !== NULL) {
641
+            if ($direction != "next" && $direction != "prev" && $direction != "") {
642
+                                        { $this->Result->show("danger", "Invalid direction", true); return false; }
643 643
             }
644 644
     	}
645 645
 
646 646
 		# query
647
-		$query = array();               // query
648
-		$query_severities = array();    // severities
649
-		$params = array();              // sql bind parameters
647
+		$query = array(); // query
648
+		$query_severities = array(); // severities
649
+		$params = array(); // sql bind parameters
650 650
 
651 651
         $query[] = "select * from (";
652 652
 		$query[] = "select * from logs ";
653 653
 		$query[] = "where (";
654 654
 		// severities
655
-		if($informational=="on")
655
+		if ($informational == "on")
656 656
 		$query_severities[] = "`severity` = 0";
657
-		if($notice=="on")
657
+		if ($notice == "on")
658 658
 		$query_severities[] = "`severity` = 1";
659
-		if($warning=="on")
659
+		if ($warning == "on")
660 660
 		$query_severities[] = "`severity` = 2";
661 661
         // join severities
662 662
         $query[] = implode(" or ", $query_severities);
663 663
         $query[] = ")";
664 664
 
665 665
 		// direction
666
-		if( ($direction=="next") && ($lastId!=$highestId) ) {
666
+		if (($direction == "next") && ($lastId != $highestId)) {
667 667
 			$query[] = "and `id` < :lastId";
668 668
 			$query[] = "order by `id` desc limit $logCount";
669 669
 			$params['lastId'] = $lastId;
670 670
 		}
671
-		elseif( $direction=="prev" && $lastId!=$highestId) {
671
+		elseif ($direction == "prev" && $lastId != $highestId) {
672 672
 			$query[] = "and `id` > :lastId";
673 673
 			$query[] = "order by `id` asc limit $logCount";
674 674
 			$params['lastId'] = $lastId;
@@ -681,7 +681,7 @@  discard block
 block discarded – undo
681 681
 
682 682
 	    # fetch
683 683
 	    try { $logs = $this->Database->getObjectsQuery(implode("\n", $query), $params); }
684
-		catch (Exception $e) { $this->Result->show("danger", $e->getMessage(), false);	return false; }
684
+		catch (Exception $e) { $this->Result->show("danger", $e->getMessage(), false); return false; }
685 685
 
686 686
 	    # return results
687 687
 	    return $logs;
@@ -693,10 +693,10 @@  discard block
 block discarded – undo
693 693
 	 * @access public
694 694
 	 * @return void
695 695
 	 */
696
-	public function log_fetch_highest_id () {
696
+	public function log_fetch_highest_id() {
697 697
 		# fetch
698 698
 	    try { $id = $this->Database->getObjectQuery("select id from logs order by id desc limit 1;"); }
699
-		catch (Exception $e) { $this->Result->show("danger", $e->getMessage(), false);	return false; }
699
+		catch (Exception $e) { $this->Result->show("danger", $e->getMessage(), false); return false; }
700 700
 		# return result
701 701
 		return $id->id;
702 702
 	}
@@ -727,90 +727,90 @@  discard block
 block discarded – undo
727 727
 	 * @param bool $mail_changelog (default: true)
728 728
 	 * @return boolean|null
729 729
 	 */
730
-	public function write_changelog ($object_type, $action, $result, $old = array(), $new = array(), $mail_changelog = true) {
730
+	public function write_changelog($object_type, $action, $result, $old = array(), $new = array(), $mail_changelog = true) {
731 731
 		//set values
732 732
 		$this->object_type 	  = $object_type;
733 733
 		$this->object_action  = $action;
734 734
 		$this->object_result  = $result;
735 735
 		$this->mail_changelog = $mail_changelog;
736 736
 		//cast diff objects as array
737
-		$this->object_old = (array) $old;		// new object
738
-		$this->object_new = (array) $new;		// old object
737
+		$this->object_old = (array) $old; // new object
738
+		$this->object_new = (array) $new; // old object
739 739
 		// Save original unmodified values to construct URLs.
740 740
 		$this->object_orig = ($action == "add") ? $this->object_new : $this->object_old;
741 741
 
742 742
 		// validate - if object should write changelog or not
743
-		if ($this->changelog_validate_object () === false) {
743
+		if ($this->changelog_validate_object() === false) {
744 744
 			return true;
745 745
 		}
746 746
 
747 747
 		// folder
748
-		if($this->object_type == "subnet") {
748
+		if ($this->object_type == "subnet") {
749 749
 			if ($this->object_old['isFolder'] || $this->object_new['isFolder']) {
750 750
 				$this->object_type = "folder";
751 751
 			}
752 752
 		}
753 753
 
754 754
 		// make sure we have settings
755
-		$this->get_settings ();
755
+		$this->get_settings();
756 756
 
757 757
 		# default log
758 758
 		$log = array();
759 759
 
760 760
 		// check if syslog globally enabled and write log
761
-	    if($this->settings->enableChangelog==1) {
761
+	    if ($this->settings->enableChangelog == 1) {
762 762
 		    # get user details and initialize required objects
763
-		    if (!is_object($this->Addresses)) $this->Addresses = new Addresses ($this->Database);
764
-		    if (!is_object($this->Subnets))   $this->Subnets   = new Subnets ($this->Database);
765
-		    if (!is_object($this->Sections))  $this->Sections  = new Sections ($this->Database);
766
-		    if (!is_object($this->Tools))     $this->Tools     = new Tools ($this->Database);
763
+		    if (!is_object($this->Addresses)) $this->Addresses = new Addresses($this->Database);
764
+		    if (!is_object($this->Subnets))   $this->Subnets   = new Subnets($this->Database);
765
+		    if (!is_object($this->Sections))  $this->Sections  = new Sections($this->Database);
766
+		    if (!is_object($this->Tools))     $this->Tools     = new Tools($this->Database);
767 767
 
768 768
 		    # unset unneeded values and format
769
-		    $this->changelog_unset_unneeded_values ();
769
+		    $this->changelog_unset_unneeded_values();
770 770
 
771 771
 		    # calculate diff
772
-		    if($action == "edit") {
773
-				$log = $this->changelog_calculate_edit_diff ();
772
+		    if ($action == "edit") {
773
+				$log = $this->changelog_calculate_edit_diff();
774 774
 			}
775
-			elseif($action == "add") {
775
+			elseif ($action == "add") {
776 776
 				// format
777
-				$this->changelog_reformat_add_diff ();
777
+				$this->changelog_reformat_add_diff();
778 778
 				//booleans
779 779
 				foreach ($this->object_new as $k=>$v) {
780
-					$this->object_new[$k] = $this->changelog_make_booleans ($k, $v);
780
+					$this->object_new[$k] = $this->changelog_make_booleans($k, $v);
781 781
 				}
782
-				$log['details'] = "<br>".$this->array_to_log ($this->object_new, true);
782
+				$log['details'] = "<br>".$this->array_to_log($this->object_new, true);
783 783
 			}
784
-			elseif($action == "delete") {
784
+			elseif ($action == "delete") {
785 785
 				// format
786
-				$this->changelog_reformat_delete_diff ();
786
+				$this->changelog_reformat_delete_diff();
787 787
 				//booleans
788 788
 				foreach ($this->object_old as $k=>$v) {
789
-					$this->changelog_make_booleans ($k, $v);
789
+					$this->changelog_make_booleans($k, $v);
790 790
 				}
791
-				$log['details'] = "<br>".$this->array_to_log ($this->object_old, true);
791
+				$log['details'] = "<br>".$this->array_to_log($this->object_old, true);
792 792
 			}
793
-			elseif($action == "truncate") {
793
+			elseif ($action == "truncate") {
794 794
 				$log['truncate'] = "Subnet truncated";
795 795
 			}
796
-			elseif($action == "resize") {
796
+			elseif ($action == "resize") {
797 797
 				$log['resize'] = "Subnet Resized";
798 798
 				$log['mask'] = $this->object_old['mask']."/".$this->object_new['mask'];
799 799
 			}
800
-			elseif($action == "perm_change") {
801
-				$log = $this->changelog_format_permission_change ();
800
+			elseif ($action == "perm_change") {
801
+				$log = $this->changelog_format_permission_change();
802 802
 			}
803 803
 
804 804
 			# if change happened write it!
805
-			if(is_array($log) && sizeof($log)>0) {
805
+			if (is_array($log) && sizeof($log) > 0) {
806 806
 				// reformat null
807 807
 				foreach ($log as $k=>$v) {
808 808
 					$log[$k] = str_replace(": <br>", ": / <br>", $v);
809 809
 				}
810 810
 				// execute
811
-				if ($this->log_type == "syslog")	{ $this->syslog_write_changelog ($log); }
812
-				elseif ($this->log_type == "both")	{ $this->changelog_write_to_db ($log); $this->syslog_write_changelog ($log); }
813
-				else								{ $this->changelog_write_to_db ($log); }
811
+				if ($this->log_type == "syslog") { $this->syslog_write_changelog($log); }
812
+				elseif ($this->log_type == "both") { $this->changelog_write_to_db($log); $this->syslog_write_changelog($log); }
813
+				else { $this->changelog_write_to_db($log); }
814 814
 			}
815 815
 		}
816 816
 		# not enabled
@@ -826,14 +826,14 @@  discard block
 block discarded – undo
826 826
 	 * @param mixed $changelog
827 827
 	 * @return void
828 828
 	 */
829
-	private function changelog_write_to_db ($changelog) {
829
+	private function changelog_write_to_db($changelog) {
830 830
 		# log to array
831
-		$changelog = str_replace("<br>", "\r\n", $this->array_to_log ($changelog, true));
831
+		$changelog = str_replace("<br>", "\r\n", $this->array_to_log($changelog, true));
832 832
 		# fetch user id
833
-		$this->get_active_user_id ();
833
+		$this->get_active_user_id();
834 834
 
835 835
 		# null and from cli, set admin user
836
-		if ($this->user===null && php_sapi_name()=="cli") { $this->user_id = 1; }
836
+		if ($this->user === null && php_sapi_name() == "cli") { $this->user_id = 1; }
837 837
 
838 838
         # if user is not specify dont write changelog
839 839
         if (!isset($this->user) || $this->user == false || $this->user == null) {
@@ -841,14 +841,14 @@  discard block
 block discarded – undo
841 841
         }
842 842
 
843 843
 		# set update id based on action
844
-		if ($this->object_action=="add")	{ $obj_id = $this->object_new['id']; }
845
-		else								{ $obj_id = $this->object_old['id']; }
844
+		if ($this->object_action == "add") { $obj_id = $this->object_new['id']; }
845
+		else { $obj_id = $this->object_old['id']; }
846 846
 
847 847
 		# set object type
848
-		$object_type = $this->object_type=="folder" ? "subnet" : $this->object_type;
848
+		$object_type = $this->object_type == "folder" ? "subnet" : $this->object_type;
849 849
 
850 850
 		# if required values are missing dont save changelog
851
-		if(is_null($obj_id) || $obj_id=="NULL")	{ return false; }
851
+		if (is_null($obj_id) || $obj_id == "NULL") { return false; }
852 852
 
853 853
 	    # set values
854 854
 	    $values = array(
@@ -861,7 +861,7 @@  discard block
 block discarded – undo
861 861
 	    			"cdiff"	 => $changelog
862 862
 					);
863 863
 		# null empty values
864
-		$values = $this->reformat_empty_array_fields ($values, null);
864
+		$values = $this->reformat_empty_array_fields($values, null);
865 865
 
866 866
 		# execute
867 867
 		try { $this->Database->insertObject("changelog", $values); }
@@ -870,8 +870,8 @@  discard block
 block discarded – undo
870 870
 			return false;
871 871
 		}
872 872
 		# mail
873
-		if ($this->mail_changelog && strlen($changelog)>0) {
874
-			$this->changelog_send_mail ($changelog);
873
+		if ($this->mail_changelog && strlen($changelog) > 0) {
874
+			$this->changelog_send_mail($changelog);
875 875
 		}
876 876
 		# ok
877 877
 		return true;
@@ -883,7 +883,7 @@  discard block
 block discarded – undo
883 883
 	 * @access private
884 884
 	 * @return boolean
885 885
 	 */
886
-	private function changelog_validate_object () {
886
+	private function changelog_validate_object() {
887 887
 		# set valid objects
888 888
 		$objects = array(
889 889
 						"ip_addr",
@@ -901,36 +901,36 @@  discard block
 block discarded – undo
901 901
 	 * @access private
902 902
 	 * @return void
903 903
 	 */
904
-	private function changelog_reformat_add_diff () {
904
+	private function changelog_reformat_add_diff() {
905 905
 		foreach ($this->object_new as $k=>$v) {
906 906
 			//tag change
907
-			if($k == 'state') 				{ $this->object_new[$k] = $this->changelog_format_tag_diff ($k, $v); }
907
+			if ($k == 'state') { $this->object_new[$k] = $this->changelog_format_tag_diff($k, $v); }
908 908
 			//section change
909
-			elseif($k == 'sectionId') 		{ $this->object_new[$k] = $this->changelog_format_section_diff ($k, $v); }
909
+			elseif ($k == 'sectionId') { $this->object_new[$k] = $this->changelog_format_section_diff($k, $v); }
910 910
 			//section change
911
-			elseif($k == 'section') 		{ $this->object_new[$k] = $this->changelog_format_section_diff ($k, $v); }
911
+			elseif ($k == 'section') { $this->object_new[$k] = $this->changelog_format_section_diff($k, $v); }
912 912
 			//master subnet change
913
-			elseif($k == "subnetId") 		{ $this->object_new[$k] = $this->changelog_format_master_subnet_diff ($k, $v); }
913
+			elseif ($k == "subnetId") { $this->object_new[$k] = $this->changelog_format_master_subnet_diff($k, $v); }
914 914
 			//master subnet change
915
-			elseif($k == "masterSubnetId") 	{ $this->object_new[$k] = $this->changelog_format_master_subnet_diff ($k, $v); }
915
+			elseif ($k == "masterSubnetId") { $this->object_new[$k] = $this->changelog_format_master_subnet_diff($k, $v); }
916 916
 			//device change
917
-			elseif($k == 'switch') 			{ $this->object_new[$k] = $this->changelog_format_device_diff ($k, $v); }
917
+			elseif ($k == 'switch') { $this->object_new[$k] = $this->changelog_format_device_diff($k, $v); }
918 918
 			//device change
919
-			elseif($k == 'device') 			{ $this->object_new[$k] = $this->changelog_format_device_diff ($k, $v); }
919
+			elseif ($k == 'device') { $this->object_new[$k] = $this->changelog_format_device_diff($k, $v); }
920 920
 			//vlan
921
-			elseif($k == 'vlanId') 			{ $this->object_new[$k] = $this->changelog_format_vlan_diff ($k, $v); }
921
+			elseif ($k == 'vlanId') { $this->object_new[$k] = $this->changelog_format_vlan_diff($k, $v); }
922 922
 			//vrf
923
-			elseif($k == 'vrfId') 			{ $this->object_new[$k] = $this->changelog_format_vrf_diff ($k, $v); }
923
+			elseif ($k == 'vrfId') { $this->object_new[$k] = $this->changelog_format_vrf_diff($k, $v); }
924 924
 			//location
925
-			elseif($k == 'location_item')   { $this->object_new[$k] = $this->changelog_format_location_diff ($k, $v); }
925
+			elseif ($k == 'location_item') { $this->object_new[$k] = $this->changelog_format_location_diff($k, $v); }
926 926
 			//location
927
-			elseif($k == 'location') 	    { $this->object_new[$k] = $this->changelog_format_location_diff ($k, $v); }
927
+			elseif ($k == 'location') { $this->object_new[$k] = $this->changelog_format_location_diff($k, $v); }
928 928
 			//master section change
929
-			elseif($k == 'masterSection') 	{ $this->object_new[$k] = $this->changelog_format_master_section_diff ($k, $v); }
929
+			elseif ($k == 'masterSection') { $this->object_new[$k] = $this->changelog_format_master_section_diff($k, $v); }
930 930
 			//permission change
931
-			elseif($k == "permissions") 	{ $this->object_new[$k] = $this->changelog_format_permission_diff ($k, $v); }
931
+			elseif ($k == "permissions") { $this->object_new[$k] = $this->changelog_format_permission_diff($k, $v); }
932 932
 			// nameserver index
933
-			elseif($k == "nameserverId") 	{ $this->object_new[$k] = $this->changelog_format_ns_diff ($k, $v); }
933
+			elseif ($k == "nameserverId") { $this->object_new[$k] = $this->changelog_format_ns_diff($k, $v); }
934 934
 		}
935 935
 	}
936 936
 
@@ -941,36 +941,36 @@  discard block
 block discarded – undo
941 941
 	 * @access private
942 942
 	 * @return void
943 943
 	 */
944
-	private function changelog_reformat_delete_diff () {
944
+	private function changelog_reformat_delete_diff() {
945 945
 		foreach ($this->object_old as $k=>$v) {
946 946
 			//tag change
947
-			if($k == 'state') 				{ $this->object_old[$k] = $this->changelog_format_tag_diff ($k, $v); }
947
+			if ($k == 'state') { $this->object_old[$k] = $this->changelog_format_tag_diff($k, $v); }
948 948
 			//section change
949
-			elseif($k == 'section') 		{ $this->object_old[$k] = $this->changelog_format_section_diff ($k, $v); }
949
+			elseif ($k == 'section') { $this->object_old[$k] = $this->changelog_format_section_diff($k, $v); }
950 950
 			//section change
951
-			elseif($k == 'sectionId') 		{ $this->object_old[$k] = $this->changelog_format_section_diff ($k, $v); }
951
+			elseif ($k == 'sectionId') { $this->object_old[$k] = $this->changelog_format_section_diff($k, $v); }
952 952
 			//subnet change
953
-			elseif($k == "subnetId") 		{ $this->object_old[$k] = $this->changelog_format_master_subnet_diff ($k, $v); }
953
+			elseif ($k == "subnetId") { $this->object_old[$k] = $this->changelog_format_master_subnet_diff($k, $v); }
954 954
 			//master subnet change
955
-			elseif($k == "masterSubnetId") 	{ $this->object_old[$k] = $this->changelog_format_master_subnet_diff ($k, $v); }
955
+			elseif ($k == "masterSubnetId") { $this->object_old[$k] = $this->changelog_format_master_subnet_diff($k, $v); }
956 956
 			//device change
957
-			elseif($k == 'switch') 			{ $this->object_old[$k] = $this->changelog_format_device_diff ($k, $v); }
957
+			elseif ($k == 'switch') { $this->object_old[$k] = $this->changelog_format_device_diff($k, $v); }
958 958
 			//device change
959
-			elseif($k == 'device') 			{ $this->object_old[$k] = $this->changelog_format_device_diff ($k, $v); }
959
+			elseif ($k == 'device') { $this->object_old[$k] = $this->changelog_format_device_diff($k, $v); }
960 960
 			//vlan
961
-			elseif($k == 'vlanId') 			{ $this->object_old[$k] = $this->changelog_format_vlan_diff ($k, $v); }
961
+			elseif ($k == 'vlanId') { $this->object_old[$k] = $this->changelog_format_vlan_diff($k, $v); }
962 962
 			//vrf
963
-			elseif($k == 'vrfId') 			{ $this->object_old[$k] = $this->changelog_format_vrf_diff ($k, $v); }
963
+			elseif ($k == 'vrfId') { $this->object_old[$k] = $this->changelog_format_vrf_diff($k, $v); }
964 964
 			//location
965
-			elseif($k == 'location_item') 	{ $this->object_old[$k] = $this->changelog_format_location_diff ($k, $v); }
965
+			elseif ($k == 'location_item') { $this->object_old[$k] = $this->changelog_format_location_diff($k, $v); }
966 966
 			//location
967
-			elseif($k == 'location') 	    { $this->object_old[$k] = $this->changelog_format_location_diff ($k, $v); }
967
+			elseif ($k == 'location') { $this->object_old[$k] = $this->changelog_format_location_diff($k, $v); }
968 968
 			//master section change
969
-			elseif($k == 'masterSection') 	{ $this->object_old[$k] = $this->changelog_format_master_section_diff ($k, $v); }
969
+			elseif ($k == 'masterSection') { $this->object_old[$k] = $this->changelog_format_master_section_diff($k, $v); }
970 970
 			//permission change
971
-			elseif($k == "permissions") 	{ $this->object_old[$k] = $this->changelog_format_permission_diff ($k, $v); }
971
+			elseif ($k == "permissions") { $this->object_old[$k] = $this->changelog_format_permission_diff($k, $v); }
972 972
 			// nameserver index
973
-			elseif($k == "nameserverId") 	{ $this->object_old[$k] = $this->changelog_format_ns_diff ($k, $v); }
973
+			elseif ($k == "nameserverId") { $this->object_old[$k] = $this->changelog_format_ns_diff($k, $v); }
974 974
 		}
975 975
 	}
976 976
 
@@ -980,15 +980,15 @@  discard block
 block discarded – undo
980 980
 	 * @access private
981 981
 	 * @return array
982 982
 	 */
983
-	private function changelog_calculate_edit_diff () {
983
+	private function changelog_calculate_edit_diff() {
984 984
 		//old object - checkboxes that are not present, set them as 0
985
-		foreach($this->object_old as $k=>$v) {
986
-			if(!isset($this->object_new[$k]) && $v=="1") {
985
+		foreach ($this->object_old as $k=>$v) {
986
+			if (!isset($this->object_new[$k]) && $v == "1") {
987 987
 				$this->object_new[$k] = 0;
988 988
 			}
989 989
 		}
990 990
 		foreach ($this->object_new as $k=>$v) {
991
-			if(!isset($this->object_old[$k]) && $v=="1") {
991
+			if (!isset($this->object_old[$k]) && $v == "1") {
992 992
 				$this->object_old[$k] = 0;
993 993
 			}
994 994
 		}
@@ -997,45 +997,45 @@  discard block
 block discarded – undo
997 997
 		$this->object_new['ip_addr'] = $this->Subnets->transform_address($this->object_new['ip_addr'], "dotted");
998 998
 
999 999
 		// check each value
1000
-		foreach($this->object_new as $k=>$v) {
1000
+		foreach ($this->object_new as $k=>$v) {
1001 1001
 			//change
1002
-			if($this->object_old[$k]!=$v && ($this->object_old[$k] != str_replace("\'", "'", $v)))	{
1002
+			if ($this->object_old[$k] != $v && ($this->object_old[$k] != str_replace("\'", "'", $v))) {
1003 1003
 				//empty
1004
-				if(strlen(@$this->object_old[$k])==0)	{ $this->object_old[$k] = "NULL"; }
1005
-				if(strlen(@$v)==0)						{ $v = "NULL"; }
1004
+				if (strlen(@$this->object_old[$k]) == 0) { $this->object_old[$k] = "NULL"; }
1005
+				if (strlen(@$v) == 0) { $v = "NULL"; }
1006 1006
 
1007 1007
 				//tag change
1008
-				if($k == 'state') 				{ $v = $this->changelog_format_tag_diff ($k, $v); }
1008
+				if ($k == 'state') { $v = $this->changelog_format_tag_diff($k, $v); }
1009 1009
 				//section change
1010
-				elseif($k == 'sectionIdNew') 	{ $v = $this->changelog_format_section_diff ($k, $v); }
1010
+				elseif ($k == 'sectionIdNew') { $v = $this->changelog_format_section_diff($k, $v); }
1011 1011
 				//section change
1012
-				elseif($k == 'sectionId') 		{ $v = $this->changelog_format_section_diff ($k, $v); }
1012
+				elseif ($k == 'sectionId') { $v = $this->changelog_format_section_diff($k, $v); }
1013 1013
 				//subnet change
1014
-				elseif($k == "subnet") 			{ $v = $this->changelog_format_master_subnet_diff ($k, $v); }
1014
+				elseif ($k == "subnet") { $v = $this->changelog_format_master_subnet_diff($k, $v); }
1015 1015
 				//master subnet change
1016
-				elseif($k == "masterSubnetId") 	{ $v = $this->changelog_format_master_subnet_diff ($k, $v); }
1016
+				elseif ($k == "masterSubnetId") { $v = $this->changelog_format_master_subnet_diff($k, $v); }
1017 1017
 				//device change
1018
-				elseif($k == 'switch') 			{ $v = $this->changelog_format_device_diff ($k, $v); }
1018
+				elseif ($k == 'switch') { $v = $this->changelog_format_device_diff($k, $v); }
1019 1019
 				//device change
1020
-				elseif($k == 'device') 			{ $v = $this->changelog_format_device_diff ($k, $v); }
1020
+				elseif ($k == 'device') { $v = $this->changelog_format_device_diff($k, $v); }
1021 1021
 				//vlan
1022
-				elseif($k == 'vlanId') 			{ $v = $this->changelog_format_vlan_diff ($k, $v); }
1022
+				elseif ($k == 'vlanId') { $v = $this->changelog_format_vlan_diff($k, $v); }
1023 1023
 				//vrf
1024
-				elseif($k == 'vrfId') 			{ $v = $this->changelog_format_vrf_diff ($k, $v); }
1024
+				elseif ($k == 'vrfId') { $v = $this->changelog_format_vrf_diff($k, $v); }
1025 1025
 				//location
1026
-				elseif($k == 'location_item') 	{ $v = $this->changelog_format_location_diff ($k, $v); }
1026
+				elseif ($k == 'location_item') { $v = $this->changelog_format_location_diff($k, $v); }
1027 1027
 				//location
1028
-				elseif($k == 'location') 	    { $v = $this->changelog_format_location_diff ($k, $v); }
1028
+				elseif ($k == 'location') { $v = $this->changelog_format_location_diff($k, $v); }
1029 1029
 				//master section change
1030
-				elseif($k == 'masterSection') 	{ $v = $this->changelog_format_master_section_diff ($k, $v); }
1030
+				elseif ($k == 'masterSection') { $v = $this->changelog_format_master_section_diff($k, $v); }
1031 1031
 				//permission change
1032
-				elseif($k == "permissions") 	{ $v = $this->changelog_format_permission_diff ($k, $v); }
1032
+				elseif ($k == "permissions") { $v = $this->changelog_format_permission_diff($k, $v); }
1033 1033
 				// nameserver index
1034
-				elseif($k == "nameserverId") 	{ $v = $this->changelog_format_ns_diff ($k, $v); }
1034
+				elseif ($k == "nameserverId") { $v = $this->changelog_format_ns_diff($k, $v); }
1035 1035
 				// make booleans
1036
-				$v = $this->changelog_make_booleans ($k, $v);
1036
+				$v = $this->changelog_make_booleans($k, $v);
1037 1037
 				//set log
1038
-				if ($k!=="id")
1038
+				if ($k !== "id")
1039 1039
 				$log["$k"] = $this->object_old[$k]." => $v";
1040 1040
 			}
1041 1041
 		}
@@ -1049,10 +1049,10 @@  discard block
 block discarded – undo
1049 1049
 	 * @access private
1050 1050
 	 * @return void
1051 1051
 	 */
1052
-	private function changelog_unset_unneeded_values () {
1052
+	private function changelog_unset_unneeded_values() {
1053 1053
 		# remove ip address fields
1054
-		if($this->object_type == "ip_addr") {
1055
-			unset(	$this->object_new['subnet'],
1054
+		if ($this->object_type == "ip_addr") {
1055
+			unset($this->object_new['subnet'],
1056 1056
 					$this->object_new['type'],
1057 1057
 					$this->object_new['ip_addr_old'],
1058 1058
 					$this->object_new['nostrict'],
@@ -1062,7 +1062,7 @@  discard block
 block discarded – undo
1062 1062
 					$this->object_new['subnetvlan'],
1063 1063
 					$this->object_new['addressId']
1064 1064
 					);
1065
-			unset(	$this->object_old['subnet'],
1065
+			unset($this->object_old['subnet'],
1066 1066
 					$this->object_old['type'],
1067 1067
 					$this->object_old['ip_addr_old'],
1068 1068
 					$this->object_old['nostrict'],
@@ -1073,24 +1073,24 @@  discard block
 block discarded – undo
1073 1073
 					$this->object_old['addressId']
1074 1074
 					);
1075 1075
             # remove mac
1076
-            if ($this->object_action=="add") {
1076
+            if ($this->object_action == "add") {
1077 1077
                 unset ($this->object_new['mac_old'], $this->object_new['addressId']);
1078 1078
             }
1079 1079
 			# reformat ip
1080
-			if (isset($this->object_old['ip_addr']))	{ $this->object_old['ip_addr'] = $this->Subnets->transform_address ($this->object_old['ip_addr'],"dotted"); }
1081
-			if (isset($this->object_new['ip_addr']))	{ $this->object_new['ip_addr'] = $this->Subnets->transform_address ($this->object_new['ip_addr'],"dotted"); }
1080
+			if (isset($this->object_old['ip_addr'])) { $this->object_old['ip_addr'] = $this->Subnets->transform_address($this->object_old['ip_addr'], "dotted"); }
1081
+			if (isset($this->object_new['ip_addr'])) { $this->object_new['ip_addr'] = $this->Subnets->transform_address($this->object_new['ip_addr'], "dotted"); }
1082 1082
 
1083 1083
 		}
1084 1084
 		# remove subnet fields
1085
-		elseif($this->object_type == "subnet" || $this->object_type == "folder")	{
1085
+		elseif ($this->object_type == "subnet" || $this->object_type == "folder") {
1086 1086
 			// remove unneeded values
1087
-			unset(	$this->object_new['subnetId'],
1087
+			unset($this->object_new['subnetId'],
1088 1088
 					$this->object_new['vrfIdOld'],
1089 1089
 					$this->object_new['permissions'],
1090 1090
 					$this->object_new['state'],
1091 1091
 					$this->object_new['ip']
1092 1092
 				);
1093
-			unset(	$this->object_old['subnetId'],
1093
+			unset($this->object_old['subnetId'],
1094 1094
 					$this->object_old['vrfIdOld'],
1095 1095
 					$this->object_old['permissions'],
1096 1096
 					$this->object_old['state'],
@@ -1098,7 +1098,7 @@  discard block
 block discarded – undo
1098 1098
 				);
1099 1099
 
1100 1100
 			# folder
1101
-			if($this->object_type == "folder") {
1101
+			if ($this->object_type == "folder") {
1102 1102
 				unset(
1103 1103
 					$this->object_new['linked_subnet'],
1104 1104
 					$this->object_new['firewallAddressObject'],
@@ -1140,23 +1140,23 @@  discard block
 block discarded – undo
1140 1140
 			}
1141 1141
 
1142 1142
 			# if section does not change
1143
-			if($this->object_new['sectionId']==$this->object_new['sectionIdNew']) {
1144
-				unset(	$this->object_new['sectionIdNew']);
1143
+			if ($this->object_new['sectionId'] == $this->object_new['sectionIdNew']) {
1144
+				unset($this->object_new['sectionIdNew']);
1145 1145
 			}
1146 1146
 			else {
1147 1147
 				$this->object_old['sectionIdNew'] = $this->object_old['sectionId'];
1148 1148
 			}
1149 1149
 
1150 1150
 			//transform subnet to IP address format
1151
-			if(strlen($this->object_new['subnet'])>0) 	{ $this->object_new['subnet'] = $this->Subnets->transform_address ($this->object_new['subnet'], "dotted");}
1152
-			if(strlen($this->object_old['subnet'])>0) 	{ $this->object_old['subnet'] = $this->Subnets->transform_address ($this->object_old['subnet'], "dotted");}
1151
+			if (strlen($this->object_new['subnet']) > 0) { $this->object_new['subnet'] = $this->Subnets->transform_address($this->object_new['subnet'], "dotted"); }
1152
+			if (strlen($this->object_old['subnet']) > 0) { $this->object_old['subnet'] = $this->Subnets->transform_address($this->object_old['subnet'], "dotted"); }
1153 1153
 
1154 1154
 			//remove subnet/mask for folders
1155
-			if (@$this->object_new['isFolder']=="1")	{ unset($this->object_new['subnet'], $this->object_new['mask']); }
1156
-			if (@$this->object_old['isFolder']=="1")	{ unset($this->object_old['subnet'], $this->object_old['mask']); }
1155
+			if (@$this->object_new['isFolder'] == "1") { unset($this->object_new['subnet'], $this->object_new['mask']); }
1156
+			if (@$this->object_old['isFolder'] == "1") { unset($this->object_old['subnet'], $this->object_old['mask']); }
1157 1157
 		}
1158 1158
 		# remove order fields
1159
-		elseif($this->object_type == "section") {
1159
+		elseif ($this->object_type == "section") {
1160 1160
 			unset($this->object_old['order']);
1161 1161
 		}
1162 1162
 
@@ -1174,9 +1174,9 @@  discard block
 block discarded – undo
1174 1174
 	 * @param mixed $v
1175 1175
 	 * @return void
1176 1176
 	 */
1177
-	private function changelog_format_tag_diff ($k, $v) {
1177
+	private function changelog_format_tag_diff($k, $v) {
1178 1178
 		$this->object_old[$k] = $this->Addresses->address_type_index_to_type($this->object_old[$k]);
1179
-		$v 					  = $this->Addresses->address_type_index_to_type($v);
1179
+		$v = $this->Addresses->address_type_index_to_type($v);
1180 1180
 		//result
1181 1181
 		return $v;
1182 1182
 	}
@@ -1189,14 +1189,14 @@  discard block
 block discarded – undo
1189 1189
 	 * @param mixed $v
1190 1190
 	 * @return void
1191 1191
 	 */
1192
-	private function changelog_format_section_diff ($k, $v) {
1192
+	private function changelog_format_section_diff($k, $v) {
1193 1193
 		//get old and new device
1194
-		if($this->object_old[$k] != "NULL") {
1195
-			$section = $this->Sections->fetch_section ("id", $this->object_old[$k]);
1194
+		if ($this->object_old[$k] != "NULL") {
1195
+			$section = $this->Sections->fetch_section("id", $this->object_old[$k]);
1196 1196
 			$this->object_old[$k] = $section->name." (id ".$section->id.")";
1197 1197
 		}
1198
-		if($v != "NULL")	{
1199
-			$section = $this->Sections->fetch_section ("id", $v);
1198
+		if ($v != "NULL") {
1199
+			$section = $this->Sections->fetch_section("id", $v);
1200 1200
 			$v = $section->name." (id ".$section->id.")";
1201 1201
 		}
1202 1202
 		//result
@@ -1211,23 +1211,23 @@  discard block
 block discarded – undo
1211 1211
 	 * @param mixed $v
1212 1212
 	 * @return string
1213 1213
 	 */
1214
-	private function changelog_format_master_subnet_diff ($k, $v) {
1214
+	private function changelog_format_master_subnet_diff($k, $v) {
1215 1215
 		//Old root or not
1216
-		if($this->object_old[$k]==0){
1216
+		if ($this->object_old[$k] == 0) {
1217 1217
 			$this->object_old[$k] = "Root";
1218 1218
 		}
1219 1219
 		else {
1220 1220
 			$subnet = $this->Subnets->fetch_subnet("id", $this->object_old[$k]);
1221
-			$this->object_old[$k] = strlen($subnet->description)>0 ? $this->Subnets->transform_address($subnet->subnet, "dotted")."/$subnet->mask [$subnet->description]" : $this->Subnets->transform_address($subnet->subnet, "dotted")."/".$subnet->mask;
1221
+			$this->object_old[$k] = strlen($subnet->description) > 0 ? $this->Subnets->transform_address($subnet->subnet, "dotted")."/$subnet->mask [$subnet->description]" : $this->Subnets->transform_address($subnet->subnet, "dotted")."/".$subnet->mask;
1222 1222
 			$this->object_old[$k] .= " (id ".$subnet->id.")";
1223 1223
 		}
1224 1224
 		//New root or not
1225
-		if($v==0) {
1225
+		if ($v == 0) {
1226 1226
 			$v = "Root";
1227 1227
 		}
1228 1228
 		else {
1229 1229
 			$subnet = $this->Subnets->fetch_subnet("id", $v);
1230
-			$v  = strlen($subnet->description)>0 ? $this->Subnets->transform_address($subnet->subnet, "dotted")."/$subnet->mask [$subnet->description]" : $this->Subnets->transform_address($subnet->subnet, "dotted")."/".$subnet->mask;
1230
+			$v  = strlen($subnet->description) > 0 ? $this->Subnets->transform_address($subnet->subnet, "dotted")."/$subnet->mask [$subnet->description]" : $this->Subnets->transform_address($subnet->subnet, "dotted")."/".$subnet->mask;
1231 1231
 			$v .= " (id ".$subnet->id.")";
1232 1232
 		}
1233 1233
 		//result
@@ -1242,20 +1242,20 @@  discard block
 block discarded – undo
1242 1242
 	 * @param mixed $v
1243 1243
 	 * @return void
1244 1244
 	 */
1245
-	private function changelog_format_device_diff ($k, $v) {
1245
+	private function changelog_format_device_diff($k, $v) {
1246 1246
 		// old none
1247
-		if($this->object_old[$k] == 0)	{
1247
+		if ($this->object_old[$k] == 0) {
1248 1248
 			$this->object_old[$k] = "None";
1249 1249
 		}
1250
-		elseif($this->object_old[$k] != "NULL") {
1250
+		elseif ($this->object_old[$k] != "NULL") {
1251 1251
 			$dev = $this->Tools->fetch_object("devices", "id", $this->object_old[$k]);
1252 1252
 			$this->object_old[$k] = $dev->hostname;
1253 1253
 		}
1254 1254
 		// new none
1255
-		if($v == 0)	{
1255
+		if ($v == 0) {
1256 1256
 			$v = "None";
1257 1257
 		}
1258
-		if($v != "NULL") {
1258
+		if ($v != "NULL") {
1259 1259
 			$dev = $this->Tools->fetch_object("devices", "id", $v);
1260 1260
 			$v = $dev->hostname;
1261 1261
 		}
@@ -1271,20 +1271,20 @@  discard block
 block discarded – undo
1271 1271
 	 * @param mixed $v
1272 1272
 	 * @return void
1273 1273
 	 */
1274
-	private function changelog_format_vlan_diff ($k, $v) {
1274
+	private function changelog_format_vlan_diff($k, $v) {
1275 1275
 		//old none
1276
-		if($this->object_old[$k] == 0)	{
1276
+		if ($this->object_old[$k] == 0) {
1277 1277
 			$this->object_old[$k] = "None";
1278 1278
 		}
1279
-		elseif($this->object_old[$k] != "NULL") {
1279
+		elseif ($this->object_old[$k] != "NULL") {
1280 1280
 			$vlan = $this->Tools->fetch_object("vlans", "vlanId", $this->object_old[$k]);
1281 1281
 			$this->object_old[$k] = $vlan->name." [$vlan->number]";
1282 1282
 		}
1283 1283
 		//new none
1284
-		if($v == 0)	{
1284
+		if ($v == 0) {
1285 1285
 			$v = "None";
1286 1286
 		}
1287
-		elseif($v != "NULL") {
1287
+		elseif ($v != "NULL") {
1288 1288
 			$vlan = $this->Tools->fetch_object("vlans", "vlanId", $v);
1289 1289
 			$v = $vlan->name." [$vlan->number]";
1290 1290
 		}
@@ -1300,20 +1300,20 @@  discard block
 block discarded – undo
1300 1300
 	 * @param mixed $v
1301 1301
 	 * @return void
1302 1302
 	 */
1303
-	private function changelog_format_vrf_diff ($k, $v) {
1303
+	private function changelog_format_vrf_diff($k, $v) {
1304 1304
 		//old none
1305
-		if($this->object_old[$k] == 0)	{
1305
+		if ($this->object_old[$k] == 0) {
1306 1306
 			$this->object_old[$k] = "None";
1307 1307
 		}
1308
-		elseif($this->object_old[$k] != "NULL") {
1308
+		elseif ($this->object_old[$k] != "NULL") {
1309 1309
 			$vrf = $this->Tools->fetch_object("vrf", "vrfId", $this->object_old[$k]);
1310 1310
 			$this->object_old[$k] = $vrf->name." [$vrf->description]";
1311 1311
 		}
1312 1312
 		// new none
1313
-		if($v == 0)	{
1313
+		if ($v == 0) {
1314 1314
 			$v = "None";
1315 1315
 		}
1316
-		elseif($v != "NULL") {
1316
+		elseif ($v != "NULL") {
1317 1317
 			$vrf = $this->Tools->fetch_object("vrf", "vrfId", $v);
1318 1318
 			$v = $vrf->name." [$vrf->description]";
1319 1319
 		}
@@ -1329,20 +1329,20 @@  discard block
 block discarded – undo
1329 1329
 	 * @param mixed $v
1330 1330
 	 * @return void
1331 1331
 	 */
1332
-	private function changelog_format_ns_diff ($k, $v) {
1332
+	private function changelog_format_ns_diff($k, $v) {
1333 1333
 		//old none
1334
-		if($this->object_old[$k] == 0)	{
1334
+		if ($this->object_old[$k] == 0) {
1335 1335
 			$this->object_old[$k] = "None";
1336 1336
 		}
1337
-		elseif($this->object_old[$k] != "NULL") {
1337
+		elseif ($this->object_old[$k] != "NULL") {
1338 1338
 			$ns = $this->Tools->fetch_object("nameservers", "id", $this->object_old[$k]);
1339 1339
 			$this->object_old[$k] = $ns->name." [".$ns->namesrv1."]";
1340 1340
 		}
1341 1341
 		// new none
1342
-		if($v == 0)	{
1342
+		if ($v == 0) {
1343 1343
 			$v = "None";
1344 1344
 		}
1345
-		elseif($v != "NULL") {
1345
+		elseif ($v != "NULL") {
1346 1346
 			$ns = $this->Tools->fetch_object("nameservers", "id", $v);
1347 1347
 			$v = $ns->name." [".$ns->namesrv1."]";
1348 1348
 		}
@@ -1358,22 +1358,22 @@  discard block
 block discarded – undo
1358 1358
 	 * @param mixed $v
1359 1359
 	 * @return void
1360 1360
 	 */
1361
-	private function changelog_format_location_diff ($k, $v) {
1361
+	private function changelog_format_location_diff($k, $v) {
1362 1362
 		//old none
1363
-		if($this->object_old[$k] == 0)	{
1363
+		if ($this->object_old[$k] == 0) {
1364 1364
 			$this->object_old[$k] = "None";
1365 1365
 		}
1366
-		elseif($this->object_old[$k] != "NULL") {
1366
+		elseif ($this->object_old[$k] != "NULL") {
1367 1367
 			$location = $this->Tools->fetch_object("locations", "id", $this->object_old[$k]);
1368
-			$this->object_old[$k] = strlen($location->description>0) ? $location->name." [$location->description]" : $location->name;
1368
+			$this->object_old[$k] = strlen($location->description > 0) ? $location->name." [$location->description]" : $location->name;
1369 1369
 		}
1370 1370
 		// new none
1371
-		if($v == 0)	{
1371
+		if ($v == 0) {
1372 1372
 			$v = "None";
1373 1373
 		}
1374
-		elseif($v != "NULL") {
1374
+		elseif ($v != "NULL") {
1375 1375
 			$location = $this->Tools->fetch_object("locations", "id", $v);
1376
-			$v = strlen($location->description>0) ? $location->name." [$location->description]" : $location->name;
1376
+			$v = strlen($location->description > 0) ? $location->name." [$location->description]" : $location->name;
1377 1377
 		}
1378 1378
 		//result
1379 1379
 		return $v;
@@ -1387,21 +1387,21 @@  discard block
 block discarded – undo
1387 1387
 	 * @param mixed $v
1388 1388
 	 * @return void
1389 1389
 	 */
1390
-	private function changelog_format_master_section_diff ($k, $v) {
1390
+	private function changelog_format_master_section_diff($k, $v) {
1391 1391
 		// old root
1392
-		if($this->object_old[$k]==0) {
1392
+		if ($this->object_old[$k] == 0) {
1393 1393
 			$this->object_old[$k] = "Root";
1394 1394
 		}
1395 1395
 		else {
1396
-			$section = $this->Sections->fetch_section ("id", $this->object_old[$k]);
1396
+			$section = $this->Sections->fetch_section("id", $this->object_old[$k]);
1397 1397
 			$this->object_old[$k] = $section->name;
1398 1398
 		}
1399 1399
 		// new root
1400
-		if($v==0) {
1400
+		if ($v == 0) {
1401 1401
 			$v = "Root";
1402 1402
 		}
1403 1403
 		else {
1404
-			$section = $this->Sections->fetch_section ("id", $v);
1404
+			$section = $this->Sections->fetch_section("id", $v);
1405 1405
 			$v = $section->name;
1406 1406
 		}
1407 1407
 		//result
@@ -1416,25 +1416,25 @@  discard block
 block discarded – undo
1416 1416
 	 * @param mixed $v
1417 1417
 	 * @return string
1418 1418
 	 */
1419
-	private function changelog_format_permission_diff ($k, $v) {
1419
+	private function changelog_format_permission_diff($k, $v) {
1420 1420
 		// get old and compare
1421
-		$this->object_new['permissions'] = json_decode(str_replace("\\", "", $this->object_new['permissions']), true);		//Remove /
1422
-		$this->object_old['permissions'] = json_decode(str_replace("\\", "", $this->object_old['permissions']), true);		//Remove /
1421
+		$this->object_new['permissions'] = json_decode(str_replace("\\", "", $this->object_new['permissions']), true); //Remove /
1422
+		$this->object_old['permissions'] = json_decode(str_replace("\\", "", $this->object_old['permissions']), true); //Remove /
1423 1423
 
1424 1424
 		# Get all groups:
1425 1425
 		$groups = (array) $this->Tools->fetch_all_objects("userGroups", "g_id");
1426 1426
 		// rekey
1427 1427
 		$out = array();
1428
-		foreach($groups as $g) {
1428
+		foreach ($groups as $g) {
1429 1429
 			$out[$g->g_id]['g_name'] = $g->g_name;
1430 1430
 		}
1431 1431
 		$groups = $out;
1432 1432
 
1433 1433
 		// loop
1434 1434
 		$val = array();
1435
-		if(is_array($this->object_new['permissions'])) {
1436
-			foreach($this->object_new['permissions'] as $group_id=>$p) {
1437
-				$val[] = $groups[$group_id]['g_name'] ." : ".$this->Subnets->parse_permissions($p);
1435
+		if (is_array($this->object_new['permissions'])) {
1436
+			foreach ($this->object_new['permissions'] as $group_id=>$p) {
1437
+				$val[] = $groups[$group_id]['g_name']." : ".$this->Subnets->parse_permissions($p);
1438 1438
 			}
1439 1439
 		}
1440 1440
 		$this->object_old[$k] = "";
@@ -1451,7 +1451,7 @@  discard block
 block discarded – undo
1451 1451
 	 * @param mixed $v
1452 1452
 	 * @return void
1453 1453
 	 */
1454
-	private function changelog_make_booleans ($k, $v) {
1454
+	private function changelog_make_booleans($k, $v) {
1455 1455
     	// init
1456 1456
     	$keys = array();
1457 1457
 		// list of keys to be changed per object
@@ -1462,8 +1462,8 @@  discard block
 block discarded – undo
1462 1462
 		// check
1463 1463
 		if (array_key_exists($this->object_type, $keys)) {
1464 1464
 			if (in_array($k, $keys[$this->object_type])) {
1465
-				if ($v=="0") { $this->object_old[$k] = "True";	return "False"; }
1466
-				else 		 { $this->object_old[$k] = "False"; return "True"; }
1465
+				if ($v == "0") { $this->object_old[$k] = "True"; return "False"; }
1466
+				else { $this->object_old[$k] = "False"; return "True"; }
1467 1467
 			}
1468 1468
 			else {
1469 1469
 				return $v;
@@ -1480,9 +1480,9 @@  discard block
 block discarded – undo
1480 1480
 	 * @access private
1481 1481
 	 * @return void
1482 1482
 	 */
1483
-	private function changelog_format_permission_change () {
1483
+	private function changelog_format_permission_change() {
1484 1484
 		# get old and compare
1485
-		$this->object_new['permissions_change'] = json_decode(str_replace("\\", "", $this->object_new['permissions_change']), true);		//Remove /
1485
+		$this->object_new['permissions_change'] = json_decode(str_replace("\\", "", $this->object_new['permissions_change']), true); //Remove /
1486 1486
 
1487 1487
 		# Get all groups:
1488 1488
 		$groups = (array) $this->Tools->fetch_all_objects("userGroups", "g_id");
@@ -1490,17 +1490,17 @@  discard block
 block discarded – undo
1490 1490
 		$out = array();
1491 1491
 		$log = array();
1492 1492
 
1493
-		foreach($groups as $k=>$g) {
1493
+		foreach ($groups as $k=>$g) {
1494 1494
 			// save
1495 1495
 			$out[$g->g_id]['g_name'] = $g->g_name;
1496 1496
 		}
1497 1497
 		$groups = $out;
1498 1498
 
1499 1499
 		# reformat
1500
-		if($this->object_new['permissions_change']!="null") {
1500
+		if ($this->object_new['permissions_change'] != "null") {
1501 1501
 			$new_permissions = json_decode($this->object_new['permissions_change']);
1502
-			foreach($new_permissions as $group_id=>$p) {
1503
-				$log['Permissions'] .= "<br>". $groups[$group_id]['g_name'] ." : ".$this->Subnets->parse_permissions($p);
1502
+			foreach ($new_permissions as $group_id=>$p) {
1503
+				$log['Permissions'] .= "<br>".$groups[$group_id]['g_name']." : ".$this->Subnets->parse_permissions($p);
1504 1504
 			}
1505 1505
 		}
1506 1506
 		//result
@@ -1516,17 +1516,17 @@  discard block
 block discarded – undo
1516 1516
 	 * @param int $limit (default: 100)
1517 1517
 	 * @return void
1518 1518
 	 */
1519
-	public function fetch_all_changelogs ($filter = false, $expr, $limit = 100) {
1519
+	public function fetch_all_changelogs($filter = false, $expr, $limit = 100) {
1520 1520
     	# limit check
1521
-    	if(!is_numeric($limit))        { $this->Result->show("danger", "Invalid limit", true);	return false; }
1521
+    	if (!is_numeric($limit)) { $this->Result->show("danger", "Invalid limit", true); return false; }
1522 1522
 
1523 1523
     	# begin query
1524
-			$subquery_filter1 = ""; $subquery_filter2 ="";
1525
-			if($filter) {
1524
+			$subquery_filter1 = ""; $subquery_filter2 = "";
1525
+			if ($filter) {
1526 1526
 				/* replace * with % */
1527
-				if(substr($expr, 0, 1)=="*")								{ $expr[0] = "%"; }
1528
-				if(substr($expr, -1, 1)=="*")								{ $expr = substr_replace($expr, "%", -1);  }
1529
-				if(substr($expr, 0, 1)!="*" && substr($expr, -1, 1)!="*")	{ $expr = "%".$expr."%"; }
1527
+				if (substr($expr, 0, 1) == "*") { $expr[0] = "%"; }
1528
+				if (substr($expr, -1, 1) == "*") { $expr = substr_replace($expr, "%", -1); }
1529
+				if (substr($expr, 0, 1) != "*" && substr($expr, -1, 1) != "*") { $expr = "%".$expr."%"; }
1530 1530
 
1531 1531
 				$subquery_filter1 = "AND (`coid`=:expr or `ctype`=:expr or `real_name` like :expr or `cdate` like :expr or `cdiff` like :expr or INET_NTOA(`ip_addr`) like :expr)";
1532 1532
 				$subquery_filter2 = "AND (`coid`=:expr or `ctype`=:expr or `real_name` like :expr or `cdate` like :expr or `cdiff` like :expr)";
@@ -1566,7 +1566,7 @@  discard block
 block discarded – undo
1566 1566
 
1567 1567
 	    # fetch
1568 1568
 	    try { $logs = $this->Database->getObjectsQuery($query, array("expr"=>$expr)); }
1569
-		catch (Exception $e) { $this->Result->show("danger", $e->getMessage(), false);	return false; }
1569
+		catch (Exception $e) { $this->Result->show("danger", $e->getMessage(), false); return false; }
1570 1570
 
1571 1571
 	    # return results
1572 1572
 	    return $logs;
@@ -1579,9 +1579,9 @@  discard block
 block discarded – undo
1579 1579
 	 * @param int $id
1580 1580
 	 * @return void
1581 1581
 	 */
1582
-	public function fetch_changelog ($id) {
1582
+	public function fetch_changelog($id) {
1583 1583
     	# limit check
1584
-    	if(!is_numeric($id))        { $this->Result->show("danger", "Invalid ID", true);	return false; }
1584
+    	if (!is_numeric($id)) { $this->Result->show("danger", "Invalid ID", true); return false; }
1585 1585
 
1586 1586
 	    # set query
1587 1587
 	    $query = "select * from (
@@ -1627,23 +1627,23 @@  discard block
 block discarded – undo
1627 1627
 	 * @param int $limit (default: 50)
1628 1628
 	 * @return void
1629 1629
 	 */
1630
-	public function fetch_subnet_addresses_changelog_recursive ($subnetId, $limit = 50) {
1630
+	public function fetch_subnet_addresses_changelog_recursive($subnetId, $limit = 50) {
1631 1631
 	    # get all addresses ids
1632
-	    $ips  = array();
1633
-	    if (!is_object($this->Addresses)) $this->Addresses = new Addresses ($this->Database);
1634
-	    $ips = $this->Addresses->fetch_subnet_addresses_recursive ($subnetId, false);
1632
+	    $ips = array();
1633
+	    if (!is_object($this->Addresses)) $this->Addresses = new Addresses($this->Database);
1634
+	    $ips = $this->Addresses->fetch_subnet_addresses_recursive($subnetId, false);
1635 1635
 
1636 1636
 	    # fetch changelog for IPs
1637
-	    if(sizeof($ips) > 0) {
1637
+	    if (sizeof($ips) > 0) {
1638 1638
 		    # query
1639
-		    $query  = "select
1639
+		    $query = "select
1640 1640
 		    			`u`.`real_name`,`o`.`id`,`o`.`ip_addr`,`o`.`description`,`o`.`id`,`o`.`subnetId`,`c`.`caction`,`c`.`cresult`,`c`.`cdate`,`c`.`cdiff`
1641 1641
 						from `changelog` as `c`, `users` as `u`, `ipaddresses` as `o`
1642 1642
 						where `c`.`cuser` = `u`.`id` and `c`.`coid`=`o`.`id`
1643 1643
 						and (";
1644 1644
 
1645 1645
             $args = array();
1646
-			foreach($ips as $ip) {
1646
+			foreach ($ips as $ip) {
1647 1647
 			$query .= "`c`.`coid` = ? or ";
1648 1648
 			$args[] = $ip->id;
1649 1649
 			}
@@ -1652,7 +1652,7 @@  discard block
 block discarded – undo
1652 1652
 
1653 1653
 			# fetch
1654 1654
 		    try { $logs = $this->Database->getObjectsQuery($query, array_filter($args)); }
1655
-			catch (Exception $e) { $this->Result->show("danger", $e->getMessage(), false);	return false; }
1655
+			catch (Exception $e) { $this->Result->show("danger", $e->getMessage(), false); return false; }
1656 1656
 
1657 1657
 		    # return result
1658 1658
 		    return $logs;
@@ -1670,9 +1670,9 @@  discard block
 block discarded – undo
1670 1670
 	 * @param $long (default: false)
1671 1671
 	 * @param $limit (default: 50)
1672 1672
 	 */
1673
-	public function fetch_changlog_entries ($object_type, $coid, $long = false, $limit = 50) {
1673
+	public function fetch_changlog_entries($object_type, $coid, $long = false, $limit = 50) {
1674 1674
     	# limit check
1675
-    	if(!is_numeric($limit))        { $this->Result->show("danger", "Invalid limit", true);	return false; }
1675
+    	if (!is_numeric($limit)) { $this->Result->show("danger", "Invalid limit", true); return false; }
1676 1676
 
1677 1677
 	    # change ctype to match table
1678 1678
 	    switch ($object_type) {
@@ -1690,11 +1690,11 @@  discard block
 block discarded – undo
1690 1690
     	        break;
1691 1691
     	    // error
1692 1692
     	    default:
1693
-    	        $this->Result->show("danger", "Invalid object type", true);	return false;
1693
+    	        $this->Result->show("danger", "Invalid object type", true); return false;
1694 1694
 	    }
1695 1695
 
1696 1696
 	    # query
1697
-	    if($long) {
1697
+	    if ($long) {
1698 1698
 		    $query = "select *
1699 1699
 						from `changelog` as `c`, `users` as `u`, `$object_typeTable` as `o`
1700 1700
 						where `c`.`cuser` = `u`.`id` and `c`.`coid`=`o`.`id`
@@ -1724,37 +1724,37 @@  discard block
 block discarded – undo
1724 1724
 	 */
1725 1725
 	public function fetch_subnet_slaves_changlog_entries_recursive($subnetId, $limit = 50) {
1726 1726
     	# limit check
1727
-    	if(!is_numeric($limit))        { $this->Result->show("danger", "Invalid limit", true);	return false; }
1727
+    	if (!is_numeric($limit)) { $this->Result->show("danger", "Invalid limit", true); return false; }
1728 1728
     	# $subnetId check
1729
-    	if(!is_numeric($subnetId))     { $this->Result->show("danger", "Invalid subnet Id", true);	return false; }
1729
+    	if (!is_numeric($subnetId)) { $this->Result->show("danger", "Invalid subnet Id", true); return false; }
1730 1730
 
1731 1731
 		# fetch all slave subnet ids
1732
-		if (!is_object($this->Subnets)) $this->Subnets = new Subnets ($this->Database);
1733
-		$this->Subnets->reset_subnet_slaves_recursive ();
1734
-		$this->Subnets->fetch_subnet_slaves_recursive ($subnetId);
1732
+		if (!is_object($this->Subnets)) $this->Subnets = new Subnets($this->Database);
1733
+		$this->Subnets->reset_subnet_slaves_recursive();
1734
+		$this->Subnets->fetch_subnet_slaves_recursive($subnetId);
1735 1735
 		# remove master subnet ID
1736 1736
 		$key = array_search($subnetId, $this->Subnets->slaves);
1737 1737
 		unset($this->Subnets->slaves[$key]);
1738 1738
 		$this->Subnets->slaves = array_unique($this->Subnets->slaves);
1739 1739
 
1740 1740
 	    # if some slaves are present get changelog
1741
-	    if(sizeof($this->Subnets->slaves) > 0) {
1741
+	    if (sizeof($this->Subnets->slaves) > 0) {
1742 1742
 		    # set query
1743
-		    $query  = "select
1743
+		    $query = "select
1744 1744
 						`u`.`real_name`,`o`.`sectionId`,`o`.`subnet`,`o`.`mask`,`o`.`isFolder`,`o`.`description`,`o`.`id`,`c`.`caction`,`c`.`cresult`,`c`.`cdate`,`c`.`cdiff`  from `changelog` as `c`, `users` as `u`, `subnets` as `o`
1745 1745
 						where `c`.`cuser` = `u`.`id` and `c`.`coid`=`o`.`id`
1746 1746
 						and (";
1747
-			foreach($this->Subnets->slaves as $slaveId) {
1748
-			if(!isset($args)) $args = array();
1747
+			foreach ($this->Subnets->slaves as $slaveId) {
1748
+			if (!isset($args)) $args = array();
1749 1749
 			$query .= "`c`.`coid` = ? or ";
1750
-			$args[] = $slaveId;							//set keys
1750
+			$args[] = $slaveId; //set keys
1751 1751
 			}
1752 1752
 			$query  = substr($query, 0, -3);
1753 1753
 			$query .= ") and `c`.`ctype` = 'subnet' order by `c`.`cid` desc limit $limit;";
1754 1754
 
1755 1755
 			# fetch
1756 1756
 		    try { $logs = $this->Database->getObjectsQuery($query, $args); }
1757
-			catch (Exception $e) { $this->Result->show("danger", $e->getMessage(), false);	return false; }
1757
+			catch (Exception $e) { $this->Result->show("danger", $e->getMessage(), false); return false; }
1758 1758
 
1759 1759
 		    # return result
1760 1760
 		    return $logs;
@@ -1787,10 +1787,10 @@  discard block
 block discarded – undo
1787 1787
 	 * @param string $changelog
1788 1788
 	 * @return boolean
1789 1789
 	 */
1790
-	public function changelog_send_mail ($changelog) {
1790
+	public function changelog_send_mail($changelog) {
1791 1791
 
1792 1792
 		# initialize tools class
1793
-		if (!is_object($this->Tools)) $this->Tools = new Tools ($this->Database);
1793
+		if (!is_object($this->Tools)) $this->Tools = new Tools($this->Database);
1794 1794
 
1795 1795
 		# set object
1796 1796
 		$obj_details = $this->object_action == "add" ? $this->object_new : $this->object_old;
@@ -1800,28 +1800,28 @@  discard block
 block discarded – undo
1800 1800
 		$this->object_type = str_replace("ip_range", "address range", $this->object_type);
1801 1801
 
1802 1802
 		# folder
1803
-		if ( $this->object_new['isFolder']=="1" || $this->object_old['isFolder']=="1" )	{ $this->object_type = "folder"; }
1803
+		if ($this->object_new['isFolder'] == "1" || $this->object_old['isFolder'] == "1") { $this->object_type = "folder"; }
1804 1804
 
1805 1805
 		# set subject
1806 1806
 		$subject = "";
1807
-		if($this->object_action == "add") 		{ $subject = ucwords($this->object_type)." create notification"; }
1808
-		elseif($this->object_action == "edit") 	{ $subject = ucwords($this->object_type)." change notification"; }
1809
-		elseif($this->object_action == "delete"){ $subject = ucwords($this->object_type)." delete notification"; }
1807
+		if ($this->object_action == "add") { $subject = ucwords($this->object_type)." create notification"; }
1808
+		elseif ($this->object_action == "edit") { $subject = ucwords($this->object_type)." change notification"; }
1809
+		elseif ($this->object_action == "delete") { $subject = ucwords($this->object_type)." delete notification"; }
1810 1810
 
1811 1811
 		// if address we need subnet details !
1812 1812
 		$address_subnet = array();
1813
-		if ($this->object_type=="address")		{ $address_subnet = (array) $this->Tools->fetch_object("subnets", "id", $obj_details['subnetId']); }
1813
+		if ($this->object_type == "address") { $address_subnet = (array) $this->Tools->fetch_object("subnets", "id", $obj_details['subnetId']); }
1814 1814
 
1815 1815
 		# set object details
1816 1816
 		$details = "";
1817
-		if ($this->object_type=="section") 		{ $details = "<a style='font-family:Helvetica, Verdana, Arial, sans-serif; font-size:12px;color:#a0ce4e;' href='".$this->createURL().create_link("subnets",$obj_details['id'])."'>".$obj_details['name'] . "(".$obj_details['description'].") - id ".$obj_details['id']."</a>"; }
1818
-		elseif ($this->object_type=="subnet")	{ $details = "<a style='font-family:Helvetica, Verdana, Arial, sans-serif; font-size:12px;color:#a0ce4e;' href='".$this->createURL().create_link("subnets",$this->object_orig['sectionId'],$obj_details['id'])."'>".$this->Subnets->transform_address ($obj_details['subnet'], "dotted")."/".$obj_details['mask']." (".$obj_details['description'].") - id ".$obj_details['id']."</a>"; }
1819
-		elseif ($this->object_type=="folder")	{ $details = "<a style='font-family:Helvetica, Verdana, Arial, sans-serif; font-size:12px;color:#a0ce4e;' href='".$this->createURL().create_link("folder",$this->object_orig['sectionId'],$obj_details['id'])."'>".$obj_details['description']." - id ".$obj_details['id']."</a>"; }
1820
-		elseif ($this->object_type=="address")	{ $details = "<a style='font-family:Helvetica, Verdana, Arial, sans-serif; font-size:12px;color:#a0ce4e;' href='".$this->createURL().create_link("subnets",$this->object_orig['section'],$this->object_orig['subnetId'],"address-details",$this->object_orig['id'])."'>".$this->Subnets->transform_address ($obj_details['ip_addr'], "dotted")." ( hostname ".$obj_details['hostname'].", subnet: ".$this->Subnets->transform_address ($address_subnet['subnet'], "dotted")."/".$address_subnet['mask'].")- id ".$obj_details['id']."</a>"; }
1821
-		elseif ($this->object_type=="address range")	{ $details = $changelog; }
1817
+		if ($this->object_type == "section") { $details = "<a style='font-family:Helvetica, Verdana, Arial, sans-serif; font-size:12px;color:#a0ce4e;' href='".$this->createURL().create_link("subnets", $obj_details['id'])."'>".$obj_details['name']."(".$obj_details['description'].") - id ".$obj_details['id']."</a>"; }
1818
+		elseif ($this->object_type == "subnet") { $details = "<a style='font-family:Helvetica, Verdana, Arial, sans-serif; font-size:12px;color:#a0ce4e;' href='".$this->createURL().create_link("subnets", $this->object_orig['sectionId'], $obj_details['id'])."'>".$this->Subnets->transform_address($obj_details['subnet'], "dotted")."/".$obj_details['mask']." (".$obj_details['description'].") - id ".$obj_details['id']."</a>"; }
1819
+		elseif ($this->object_type == "folder") { $details = "<a style='font-family:Helvetica, Verdana, Arial, sans-serif; font-size:12px;color:#a0ce4e;' href='".$this->createURL().create_link("folder", $this->object_orig['sectionId'], $obj_details['id'])."'>".$obj_details['description']." - id ".$obj_details['id']."</a>"; }
1820
+		elseif ($this->object_type == "address") { $details = "<a style='font-family:Helvetica, Verdana, Arial, sans-serif; font-size:12px;color:#a0ce4e;' href='".$this->createURL().create_link("subnets", $this->object_orig['section'], $this->object_orig['subnetId'], "address-details", $this->object_orig['id'])."'>".$this->Subnets->transform_address($obj_details['ip_addr'], "dotted")." ( hostname ".$obj_details['hostname'].", subnet: ".$this->Subnets->transform_address($address_subnet['subnet'], "dotted")."/".$address_subnet['mask'].")- id ".$obj_details['id']."</a>"; }
1821
+		elseif ($this->object_type == "address range") { $details = $changelog; }
1822 1822
 
1823 1823
 		# remove subnet sectionId
1824
-		if($this->object_type=="subnet" && $this->object_action == "edit") {
1824
+		if ($this->object_type == "subnet" && $this->object_action == "edit") {
1825 1825
 			unset($obj_details['sectionId']);
1826 1826
 		}
1827 1827
 
@@ -1840,7 +1840,7 @@  discard block
 block discarded – undo
1840 1840
 		$content[] = "<tr><td style='vertical-align:top;'>$this->mail_font_style Changes:</td>";
1841 1841
 		$content[] = "<td>";
1842 1842
 		// add changelog
1843
-		$changelog = str_replace("\r\n", "<br>",$changelog);
1843
+		$changelog = str_replace("\r\n", "<br>", $changelog);
1844 1844
 		$changelog = array_filter(explode("<br>", $changelog));
1845 1845
 		$content[] = "<table>";
1846 1846
 
@@ -1850,11 +1850,11 @@  discard block
 block discarded – undo
1850 1850
     	    $value = explode("=>", $field[1]);
1851 1851
 
1852 1852
     	    // format field
1853
-    	    $field = trim(str_replace(array("[","]"), "", $field[0]));
1853
+    	    $field = trim(str_replace(array("[", "]"), "", $field[0]));
1854 1854
 
1855 1855
     	    // no isFolder
1856
-    	    if($field!=="isFolder") {
1857
-	    	    if(is_array($this->changelog_keys[$this->object_type])) {
1856
+    	    if ($field !== "isFolder") {
1857
+	    	    if (is_array($this->changelog_keys[$this->object_type])) {
1858 1858
 	        	    if (array_key_exists($field, $this->changelog_keys[$this->object_type])) {
1859 1859
 	            	    $field = $this->changelog_keys[$this->object_type][$field];
1860 1860
 	        	    }
@@ -1863,7 +1863,7 @@  discard block
 block discarded – undo
1863 1863
 	    		$content[] = "<tr>";
1864 1864
 	    		$content[] = "  <td>$this->mail_font_style<strong> $field</strong>: </font></td>";
1865 1865
 	    		$content[] = "  <td>$this->mail_font_style ".trim($value[0])." </font></td>";
1866
-	    		if($this->object_action=="edit") {
1866
+	    		if ($this->object_action == "edit") {
1867 1867
 	    		$content[] = "  <td>$this->mail_font_style => </font></td>";
1868 1868
 	    		$content[] = "  <td>$this->mail_font_style ".trim($value[1])." </font></td>";
1869 1869
 	    		}
@@ -1889,18 +1889,18 @@  discard block
 block discarded – undo
1889 1889
 
1890 1890
 		# get all admins and check who to end mail to
1891 1891
 		//subnets, addresses - send mail to normal users also
1892
-		if ($this->object_type=="subnet" || $this->object_type=="address") {
1893
-    		if($this->object_type=="subnet") {
1894
-        		$recipients = $this->changelog_mail_get_recipients ($obj_details['id']);
1892
+		if ($this->object_type == "subnet" || $this->object_type == "address") {
1893
+    		if ($this->object_type == "subnet") {
1894
+        		$recipients = $this->changelog_mail_get_recipients($obj_details['id']);
1895 1895
     		}
1896 1896
     		else {
1897
-        		$recipients = $this->changelog_mail_get_recipients ($obj_details['subnetId']);
1897
+        		$recipients = $this->changelog_mail_get_recipients($obj_details['subnetId']);
1898 1898
     		}
1899 1899
 		}
1900 1900
 		else {
1901
-    		$recipients = $this->changelog_mail_get_recipients (false);
1901
+    		$recipients = $this->changelog_mail_get_recipients(false);
1902 1902
 		}
1903
-		if($recipients ===false) {
1903
+		if ($recipients === false) {
1904 1904
     		return true;
1905 1905
         }
1906 1906
 
@@ -1913,11 +1913,11 @@  discard block
 block discarded – undo
1913 1913
 			$phpipam_mail = new phpipam_mail($this->settings, $mail_settings);
1914 1914
 
1915 1915
 			// set content
1916
-			$content 		= $phpipam_mail->generate_message (implode("\r\n", $content));
1917
-			$content_plain = implode("\r\n",$content_plain);
1916
+			$content = $phpipam_mail->generate_message(implode("\r\n", $content));
1917
+			$content_plain = implode("\r\n", $content_plain);
1918 1918
 
1919 1919
 			$phpipam_mail->Php_mailer->setFrom($mail_settings->mAdminMail, $mail_settings->mAdminName);
1920
-			foreach($recipients as $r) {
1920
+			foreach ($recipients as $r) {
1921 1921
 			$phpipam_mail->Php_mailer->addAddress(addslashes(trim($r->email)));
1922 1922
 			}
1923 1923
 			$phpipam_mail->Php_mailer->Subject = $subject;
Please login to merge, or discard this patch.
functions/classes/class.Tools.php 2 patches
Indentation   +2970 added lines, -2970 removed lines patch added patch discarded remove patch
@@ -6,1692 +6,1692 @@  discard block
 block discarded – undo
6 6
 
7 7
 class Tools extends Common_functions {
8 8
 
9
-	/**
10
-	 * settings
11
-	 *
12
-	 * (default value: null)
13
-	 *
14
-	 * @var object
15
-	 * @access public
16
-	 */
17
-	public $settings = null;
18
-
19
-	/**
20
-	 * (array) IP address types from Addresses object
21
-	 *
22
-	 * (default value: null)
23
-	 *
24
-	 * @var mixed
25
-	 * @access public
26
-	 */
27
-	public $address_types = null;
28
-
29
-	/**
30
-	 * CSV delimiter
31
-	 *
32
-	 * @var string
33
-	 */
34
-	public $csv_delimiter = ",";
35
-
36
-	/**
37
-	 * PEAR NET IPv4 object
38
-	 *
39
-	 * @var mixed
40
-	 * @access protected
41
-	 */
42
-	protected $Net_IPv4;
43
-
44
-	/**
45
-	 * PEAR NET IPv6 object
46
-	 *
47
-	 * @var mixed
48
-	 * @access protected
49
-	 */
50
-	protected $Net_IPv6;
51
-
52
-	/**
53
-	 * Addresses object
54
-	 *
55
-	 * (default value: false)
56
-	 *
57
-	 * @var bool|object
58
-	 * @access protected
59
-	 */
60
-	protected $Addresses = false;
61
-
62
-	/**
63
-	 * for Result printing
64
-	 *
65
-	 * @var object
66
-	 * @access public
67
-	 */
68
-	public $Result;
69
-
70
-	/**
71
-	 * debugging flag
72
-	 *
73
-	 * (default value: false)
74
-	 *
75
-	 * @var bool
76
-	 * @access protected
77
-	 */
78
-	protected $debugging = false;
79
-
80
-	/**
81
-	 * Database connection
82
-	 *
83
-	 * @var object
84
-	 * @access protected
85
-	 */
86
-	protected $Database;
87
-
88
-
89
-
90
-
91
-
92
-	/**
93
-	 * __construct method
94
-	 *
95
-	 * @access public
96
-	 */
97
-	public function __construct (Database_PDO $database) {
98
-		# set database object
99
-		$this->Database = $database;
100
-		# initialize Result
101
-		$this->Result = new Result ();
102
-		# set debugging
103
-		$this->set_debugging ();
104
-	}
105
-
106
-
107
-
108
-
109
-
110
-
111
-
112
-
113
-
114
-
115
-
116
-	/**
117
-	 *	@VLAN specific methods
118
-	 *	--------------------------------
119
-	 */
120
-
121
-	/**
122
-	 * Fetch vlans and subnets for tools vlan display. Joined query
123
-	 *
124
-	 * @access public
125
-	 * @param int $domainId (default: 1)
126
-	 * @return array|bool
127
-	 */
128
-	public function fetch_vlans_and_subnets ($domainId=1) {
129
-	    # custom fields
130
-	    $custom_fields = $this->fetch_custom_fields("vlans");
131
-		# if set add to query
132
-		$custom_fields_query = "";
133
-	    if(sizeof($custom_fields)>0) {
134
-			foreach($custom_fields as $myField) {
135
-				$custom_fields_query  .= ',`vlans`.`'.$myField['name'].'`';
136
-			}
137
-		}
138
-	    # set query
139
-	    $query = 'SELECT vlans.vlanId,vlans.number,vlans.name,vlans.description,vlans.customer_id,subnets.subnet,subnets.mask,subnets.id AS subnetId,subnets.sectionId'.@$custom_fields_query.' FROM vlans LEFT JOIN subnets ON subnets.vlanId = vlans.vlanId where vlans.`domainId` = ? ORDER BY vlans.number ASC;';
140
-		# fetch
141
-		try { $vlans = $this->Database->getObjectsQuery($query, array($domainId)); }
142
-		catch (Exception $e) {
143
-			$this->Result->show("danger", _("Error: ").$e->getMessage());
144
-			return false;
145
-		}
146
-
147
-		# reorder
148
-		$out = array();
149
-		foreach ($vlans as $vlan) {
150
-			$out[$vlan->vlanId][] = $vlan;
151
-		}
152
-		# result
153
-		return is_array($out) ? array_values($out) : false;
154
-	}
155
-
156
-	/**
157
-	 * Validates VLAN
158
-	 *
159
-	 *	not 1
160
-	 *	integer
161
-	 *	not higher that maxVLAN from settings
162
-	 *
163
-	 * @access public
164
-	 * @param int $number
165
-	 * @return mixed|bool
166
-	 */
167
-	public function validate_vlan ($number) {
168
-		# fetch highest vlan id
169
-		$settings = $this->get_settings();
170
-
171
-		if(empty($number)) 							{ return true; }
172
-		elseif(!is_numeric($number)) 				{ return _('VLAN must be numeric value!'); }
173
-		elseif ($number > $settings['vlanMax']) 	{ return _('Vlan number can be max '.$settings['vlanMax']); }
174
-		else 										{ return true; }
175
-	}
176
-
177
-
178
-
179
-
180
-
181
-
182
-
183
-	/**
184
-	 *	@search methods
185
-	 *	--------------------------------
186
-	 */
187
-
188
-
189
-	/**
190
-	 * Search database for addresses
191
-	 *
192
-	 * @access public
193
-	 * @param mixed $search_term
194
-	 * @param string $high (default: "")
195
-	 * @param string $low (default: "")
196
-	 * @param array $custom_fields (default: array())
197
-	 * @return array
198
-	 */
199
-	public function search_addresses($search_term, $high = "", $low = "", $custom_fields = array()) {
200
-
201
-    	$tags = $this->fetch_all_objects ("ipTags", "id");
202
-    	foreach ($tags as $t) {
203
-        	if(strtolower($t->type)==strtolower($search_term)) {
204
-            	$tags = $t->id;
205
-            	break;
206
-        	}
207
-        	$tags = false;
208
-    	}
209
-
210
-		# set search query
211
-		$query[] = "select * from `ipaddresses` ";
212
-		$query[] = "where `ip_addr` between :low and :high ";	//ip range
213
-		$query[] = "or `hostname` like :search_term ";			//hostname
214
-		$query[] = "or `owner` like :search_term ";				//owner
215
-		# custom fields
216
-		if(sizeof($custom_fields) > 0) {
217
-			foreach($custom_fields as $myField) {
218
-				$myField['name'] = $this->Database->escape($myField['name']);
219
-				$query[] = "or `$myField[name]` like :search_term ";
220
-			}
221
-		}
222
-		$query[] = "or `switch` like :search_term ";
223
-		$query[] = "or `port` like :search_term ";				//port search
224
-		$query[] = "or `description` like :search_term ";		//descriptions
225
-		$query[] = "or `note` like :search_term ";				//note
226
-		$query[] = "or `mac` like :search_term ";				//mac
227
-		//tag
228
-		if($tags!==false)
229
-		$query[] = "or `state` like :tags ";				//tag
230
-		$query[] = "order by `ip_addr` asc;";
231
-
232
-		# join query
233
-		$query = implode("\n", $query);
234
-
235
-		# fetch
236
-		try { $result = $this->Database->getObjectsQuery($query, array("low"=>$low, "high"=>$high, "search_term"=>"%$search_term%", "tags"=>$tags)); }
237
-		catch (Exception $e) {
238
-			$this->Result->show("danger", _("Error: ").$e->getMessage());
239
-			return false;
240
-		}
241
-		# result
242
-		return $result;
243
-	}
244
-
245
-	/**
246
-	 * Search subnets for provided range
247
-	 *
248
-	 *	First search range
249
-	 *	If host provided search also inside subnet ranges
250
-	 *
251
-	 * @access public
252
-	 * @param mixed $search_term
253
-	 * @param string $high (default: "")
254
-	 * @param string $low (default: "")
255
-	 * @param mixed $search_req
256
-	 * @param mixed $custom_fields (default: array())
257
-	 * @return array
258
-	 */
259
-	public function search_subnets($search_term, $high = "", $low = "", $search_req, $custom_fields = array()) {
260
-		# first search if range provided
261
-		$result1 = $this->search_subnets_range  ($search_term, $high, $low, $custom_fields);
262
-		# search inside subnets even if IP does not exist!
263
-		$result2 = $this->search_subnets_inside ($high, $low);
264
-		# search inside subnets even if IP does not exist - IPv6
265
-		$result3 = $this->search_subnets_inside_v6 ($high, $low, $search_req);
266
-		# merge arrays
267
-		$result = array_merge($result1, $result2, $result3);
268
-	    # result
269
-	    return array_filter($result);
270
-	}
271
-
272
-	/**
273
-	 * Search for subnets inside range
274
-	 *
275
-	 * @access private
276
-	 * @param mixed $search_term
277
-	 * @param string $high
278
-	 * @param string $low
279
-	 * @param mixed $custom_fields (default: array())
280
-	 * @return array
281
-	 */
282
-	private function search_subnets_range ($search_term, $high, $low, $custom_fields = array()) {
283
-		# reformat low/high
284
-		if($high==0 && $low==0)	{ $high = "1"; $low="1"; }
285
-
286
-		# set search query
287
-		$query[] = "select * from `subnets` where `description` like :search_term ";
288
-		$query[] = "or `subnet` between :low and :high ";
289
-		# custom
290
-	    if(sizeof($custom_fields) > 0) {
291
-			foreach($custom_fields as $myField) {
292
-				$myField['name'] = $this->Database->escape($myField['name']);
293
-				$query[] = " or `$myField[name]` like :search_term ";
294
-			}
295
-		}
296
-		$query[] = "order by `subnet` asc, `mask` asc;";
297
-
298
-		# join query
299
-		$query = implode("\n", $query);
300
-
301
-		# fetch
302
-		try { $result = $this->Database->getObjectsQuery($query, array("low"=>$low, "high"=>$high, "search_term"=>"%$search_term%")); }
303
-		catch (Exception $e) {
304
-			$this->Result->show("danger", _("Error: ").$e->getMessage());
305
-			return false;
306
-		}
307
-		# result
308
-		return $result;
309
-	}
310
-
311
-	/**
312
-	 * Search inside subnets if host address is provided!
313
-	 *
314
-	 * @access private
315
-	 * @param string $high
316
-	 * @param string $low
317
-	 * @return array
318
-	 */
319
-	private function search_subnets_inside ($high, $low) {
320
-		if($low==$high) {
321
-			# subnets class
322
-			$Subnets = new Subnets ($this->Database);
323
-			# fetch all subnets
324
-			$subnets = $Subnets->fetch_all_subnets_search();
325
-			# loop and search
326
-			$ids = array();
327
-			foreach($subnets as $s) {
328
-				# cast
329
-				$s = (array) $s;
330
-
331
-				//first verify address type
332
-				$type = $this->identify_address($s['subnet']);
333
-
334
-				if($type == "IPv4") {
335
-					# Initialize PEAR NET object
336
-					$this->initialize_pear_net_IPv4 ();
337
-					# parse address
338
-					$net = $this->Net_IPv4->parseAddress($this->transform_address($s['subnet']).'/'.$s['mask'], "dotted");
339
-
340
-					if($low>$this->transform_to_decimal(@$net->network) && $low<$this->transform_address($net->broadcast, "decimal")) {
341
-						$ids[] = $s['id'];
342
-					}
343
-				}
344
-			}
345
-			# filter
346
-			$ids = sizeof(@$ids)>0 ? array_filter($ids) : array();
347
-
348
-			$result = array();
349
-
350
-			# search
351
-			if(sizeof($ids)>0) {
352
-				foreach($ids as $id) {
353
-					$result[] = $Subnets->fetch_subnet(null, $id);
354
-				}
355
-			}
356
-			# return
357
-			return sizeof(@$result)>0 ? array_filter($result) : array();
358
-		}
359
-		else {
360
-			return array();
361
-		}
362
-	}
363
-
364
-
365
-	/**
366
-	 * Search inside subnets if host address is provided! ipv6
367
-	 *
368
-	 * @access private
369
-	 * @param string $high
370
-	 * @param string $low
371
-	 * @return array
372
-	 */
373
-	private function search_subnets_inside_v6 ($high, $low, $search_req) {
374
-		// same
375
-		if($low==$high) {
376
-			# Initialize PEAR NET object
377
-			$this->initialize_pear_net_IPv6 ();
378
-
379
-			// validate
380
-			if ($this->Net_IPv6->checkIPv6($search_req)) {
381
-				# subnets class
382
-				$Subnets = new Subnets ($this->Database);
383
-				# fetch all subnets
384
-				$subnets = $Subnets->fetch_all_subnets_search("IPv6");
385
-				# loop and search
386
-				$ids = array();
387
-				foreach($subnets as $s) {
388
-					# cast
389
-					$s = (array) $s;
390
-					# parse address
391
-					$net = $this->Net_IPv6->parseAddress($this->transform_address($s['subnet'], "dotted").'/'.$s['mask']);
392
-
393
-					if(gmp_cmp($low, $this->transform_address(@$net['start'], "decimal")) == 1 && gmp_cmp($low, $this->transform_address(@$net['end'], "decimal")) == -1) {
394
-						$ids[] = $s['id'];
395
-
396
-					}
397
-				}
398
-				# filter
399
-				$ids = sizeof(@$ids)>0 ? array_filter($ids) : array();
400
-				# search
401
-				$result = array();
402
-				if(sizeof($ids)>0) {
403
-					foreach($ids as $id) {
404
-						$result[] = $Subnets->fetch_subnet(null, $id);
405
-					}
406
-				}
407
-				# return
408
-				return sizeof(@$result)>0 ? array_filter($result) : array();
409
-			}
410
-			// empty
411
-			else {
412
-				return array();
413
-			}
414
-		}
415
-		else {
416
-			return array();
417
-		}
418
-	}
419
-
420
-	/**
421
-	 * Function to search vlans
422
-	 *
423
-	 * @access public
424
-	 * @param mixed $search_term
425
-	 * @param array $custom_fields (default: array())
426
-	 * @return array
427
-	 */
428
-	public function search_vlans($search_term, $custom_fields = array()) {
429
-		# query
430
-		$query[] = "select * from `vlans` where `name` like :search_term or `description` like :search_term or `number` like :search_term ";
431
-		# custom
432
-	    if(sizeof($custom_fields) > 0) {
433
-			foreach($custom_fields as $myField) {
434
-				$myField['name'] = $this->Database->escape($myField['name']);
435
-				$query[] = " or `$myField[name]` like :search_term ";
436
-			}
437
-		}
438
-		$query[] = ";";
439
-		# join query
440
-		$query = implode("\n", $query);
441
-
442
-		# fetch
443
-		try { $search = $this->Database->getObjectsQuery($query, array("search_term"=>"%$search_term%")); }
444
-		catch (Exception $e) {
445
-			$this->Result->show("danger", _("Error: ").$e->getMessage());
446
-			return false;
447
-		}
448
-
449
-	    # return result
450
-	    return $search;
451
-	}
452
-
453
-
454
-	/**
455
-	 * Function to search vrf
456
-	 *
457
-	 * @access public
458
-	 * @param mixed $search_term
459
-	 * @param array $custom_fields (default: array())
460
-	 * @return array
461
-	 */
462
-	public function search_vrfs ($search_term, $custom_fields = array()) {
463
-		# query
464
-		$query[] = "select * from `vrf` where `name` like :search_term or `description` like :search_term or `rd` like :search_term ";
465
-		# custom
466
-	    if(sizeof($custom_fields) > 0) {
467
-			foreach($custom_fields as $myField) {
468
-				$myField['name'] = $this->Database->escape($myField['name']);
469
-				$query[] = " or `$myField[name]` like :search_term ";
470
-			}
471
-		}
472
-		$query[] = ";";
473
-		# join query
474
-		$query = implode("\n", $query);
475
-
476
-		# fetch
477
-		try { $search = $this->Database->getObjectsQuery($query, array("search_term"=>"%$search_term%")); }
478
-		catch (Exception $e) {
479
-			$this->Result->show("danger", _("Error: ").$e->getMessage());
480
-			return false;
481
-		}
482
-
483
-	    # return result
484
-	    return $search;
485
-	}
486
-
487
-	/**
488
-	 * Search for PSTN prefixes.
489
-	 *
490
-	 * @access public
491
-	 * @param mixed $search_term
492
-	 * @param array $custom_prefix_fields (default: array())
493
-	 * @return array
494
-	 */
495
-	public function search_pstn_refixes ($search_term, $custom_prefix_fields = array()) {
496
-		# query
497
-		$query[] = "select *,concat(prefix,start) as raw from `pstnPrefixes` where `prefix` like :search_term or `name` like :search_term or `description` like :search_term ";
498
-		# custom
499
-	    if(sizeof($custom_prefix_fields) > 0) {
500
-			foreach($custom_prefix_fields as $myField) {
501
-				$myField['name'] = $this->Database->escape($myField['name']);
502
-				$query[] = " or `$myField[name]` like :search_term ";
503
-			}
504
-		}
505
-		$query[] = "order by  raw asc;";
506
-		# join query
507
-		$query = implode("\n", $query);
508
-
509
-		# fetch
510
-		try { $search = $this->Database->getObjectsQuery($query, array("search_term"=>"%$search_term%")); }
511
-		catch (Exception $e) {
512
-			$this->Result->show("danger", _("Error: ").$e->getMessage());
513
-			return false;
514
-		}
515
-
516
-	    # return result
517
-	    return $search;
518
-	}
519
-
520
-	/**
521
-	 * Search for PSTN numbers.
522
-	 *
523
-	 * @access public
524
-	 * @param mixed $search_term
525
-	 * @param array $custom_prefix_fields (default: array())
526
-	 * @return array
527
-	 */
528
-	public function search_pstn_numbers ($search_term, $custom_prefix_fields = array()) {
529
-		# query
530
-		$query[] = "select * from `pstnNumbers` where `number` like :search_term or `name` like :search_term or `description` like :search_term or `owner` like :search_term ";
531
-		# custom
532
-	    if(sizeof($custom_prefix_fields) > 0) {
533
-			foreach($custom_prefix_fields as $myField) {
534
-				$myField['name'] = $this->Database->escape($myField['name']);
535
-				$query[] = " or `$myField[name]` like :search_term ";
536
-			}
537
-		}
538
-		$query[] = "order by number asc;";
539
-		# join query
540
-		$query = implode("\n", $query);
541
-
542
-		# fetch
543
-		try { $search = $this->Database->getObjectsQuery($query, array("search_term"=>"%$search_term%")); }
544
-		catch (Exception $e) {
545
-			$this->Result->show("danger", _("Error: ").$e->getMessage());
546
-			return false;
547
-		}
548
-
549
-	    # return result
550
-	    return $search;
551
-	}
552
-
553
-	/**
554
-	 * Search for circuits.
555
-	 *
556
-	 * @access public
557
-	 * @param mixed $search_term
558
-	 * @param array $custom_circuit_fields (default: array())
559
-	 * @return array
560
-	 */
561
-	public function search_circuits ($search_term, $custom_circuit_fields = array()) {
562
-		# query
563
-		$query[] = "select c.id,c.cid,c.type,c.device1,c.location1,c.device2,c.location2,p.name,p.description,p.contact,c.capacity,p.id as pid,c.status ";
564
-		$query[] = "from circuits as c, circuitProviders as p ";
565
-		$query[] = "where c.provider = p.id";
566
-		$query[] = "and (`cid` like :search_term or `type` like :search_term or `capacity` like :search_term or `comment` like :search_term or `name` like :search_term)";
567
-		# custom
568
-	    if(sizeof($custom_circuit_fields) > 0) {
569
-			foreach($custom_circuit_fields as $myField) {
570
-				$myField['name'] = $this->Database->escape($myField['name']);
571
-				$query[] = " or `$myField[name]` like :search_term ";
572
-			}
573
-		}
574
-
575
-		$query[] = "order by c.cid asc;";
576
-		# join query
577
-		$query = implode("\n", $query);
578
-
579
-		# fetch
580
-		try { $search = $this->Database->getObjectsQuery($query, array("search_term"=>"%$search_term%")); }
581
-		catch (Exception $e) {
582
-			$this->Result->show("danger", _("Error: ").$e->getMessage());
583
-			return false;
584
-		}
585
-
586
-	    # return result
587
-	    return $search;
588
-	}
589
-
590
-
591
-	/**
592
-	 * Search for circuit providers
593
-	 *
594
-	 * @access public
595
-	 * @param mixed $search_term
596
-	 * @param array $custom_circuit_fields (default: array())
597
-	 * @return array
598
-	 */
599
-	public function search_circuit_providers ($search_term, $custom_circuit_fields = array()) {
600
-		# query
601
-		$query[] = "select * from `circuitProviders` where `name` like :search_term or `description` like :search_term or `contact` like :search_term ";
602
-		# custom
603
-	    if(sizeof($custom_circuit_fields) > 0) {
604
-			foreach($custom_circuit_fields as $myField) {
605
-				$myField['name'] = $this->Database->escape($myField['name']);
606
-				$query[] = " or `$myField[name]` like :search_term ";
607
-			}
608
-		}
609
-		$query[] = "order by name asc;";
610
-		# join query
611
-		$query = implode("\n", $query);
612
-
613
-		# fetch
614
-		try { $search = $this->Database->getObjectsQuery($query, array("search_term"=>"%$search_term%")); }
615
-		catch (Exception $e) {
616
-			$this->Result->show("danger", _("Error: ").$e->getMessage());
617
-			return false;
618
-		}
619
-
620
-	    # return result
621
-	    return $search;
622
-	}
623
-
624
-	/**
625
-	 * Reformat possible nun-full IPv4 address for search
626
-	 *
627
-	 *	e.g. 10.10.10 -> 10.10.10.0 - 10.10.10.255
628
-	 *
629
-	 * @access public
630
-	 * @param mixed $address
631
-	 * @return array high/low decimal address
632
-	 */
633
-	public function reformat_IPv4_for_search ($address) {
634
-		# remove % sign if present
635
-		$address = str_replace("%", "", $address);
636
-		# we need Addresses class
637
-		$Addresses = new Addresses ($this->Database);
638
-
639
-		# if subnet is provided we have all data
640
-		if(strpos($address, "/")>0) {
641
-			# Initialize PEAR NET object
642
-			$this->initialize_pear_net_IPv4 ();
643
-			$net = $this->Net_IPv4->parseAddress($address);
644
-
645
-			$result['low']   = $Addresses->transform_to_decimal($net->network);
646
-			$result['high']	 = $Addresses->transform_to_decimal($net->broadcast);
647
-		}
648
-		# else calculate options
649
-		else {
650
-			# if subnet is not provided maybe wildcard is, so explode it to array
651
-			$address = explode(".", $address);
9
+    /**
10
+     * settings
11
+     *
12
+     * (default value: null)
13
+     *
14
+     * @var object
15
+     * @access public
16
+     */
17
+    public $settings = null;
18
+
19
+    /**
20
+     * (array) IP address types from Addresses object
21
+     *
22
+     * (default value: null)
23
+     *
24
+     * @var mixed
25
+     * @access public
26
+     */
27
+    public $address_types = null;
28
+
29
+    /**
30
+     * CSV delimiter
31
+     *
32
+     * @var string
33
+     */
34
+    public $csv_delimiter = ",";
35
+
36
+    /**
37
+     * PEAR NET IPv4 object
38
+     *
39
+     * @var mixed
40
+     * @access protected
41
+     */
42
+    protected $Net_IPv4;
43
+
44
+    /**
45
+     * PEAR NET IPv6 object
46
+     *
47
+     * @var mixed
48
+     * @access protected
49
+     */
50
+    protected $Net_IPv6;
51
+
52
+    /**
53
+     * Addresses object
54
+     *
55
+     * (default value: false)
56
+     *
57
+     * @var bool|object
58
+     * @access protected
59
+     */
60
+    protected $Addresses = false;
61
+
62
+    /**
63
+     * for Result printing
64
+     *
65
+     * @var object
66
+     * @access public
67
+     */
68
+    public $Result;
69
+
70
+    /**
71
+     * debugging flag
72
+     *
73
+     * (default value: false)
74
+     *
75
+     * @var bool
76
+     * @access protected
77
+     */
78
+    protected $debugging = false;
79
+
80
+    /**
81
+     * Database connection
82
+     *
83
+     * @var object
84
+     * @access protected
85
+     */
86
+    protected $Database;
87
+
88
+
89
+
90
+
91
+
92
+    /**
93
+     * __construct method
94
+     *
95
+     * @access public
96
+     */
97
+    public function __construct (Database_PDO $database) {
98
+        # set database object
99
+        $this->Database = $database;
100
+        # initialize Result
101
+        $this->Result = new Result ();
102
+        # set debugging
103
+        $this->set_debugging ();
104
+    }
105
+
106
+
107
+
108
+
109
+
110
+
111
+
112
+
113
+
114
+
115
+
116
+    /**
117
+     *	@VLAN specific methods
118
+     *	--------------------------------
119
+     */
120
+
121
+    /**
122
+     * Fetch vlans and subnets for tools vlan display. Joined query
123
+     *
124
+     * @access public
125
+     * @param int $domainId (default: 1)
126
+     * @return array|bool
127
+     */
128
+    public function fetch_vlans_and_subnets ($domainId=1) {
129
+        # custom fields
130
+        $custom_fields = $this->fetch_custom_fields("vlans");
131
+        # if set add to query
132
+        $custom_fields_query = "";
133
+        if(sizeof($custom_fields)>0) {
134
+            foreach($custom_fields as $myField) {
135
+                $custom_fields_query  .= ',`vlans`.`'.$myField['name'].'`';
136
+            }
137
+        }
138
+        # set query
139
+        $query = 'SELECT vlans.vlanId,vlans.number,vlans.name,vlans.description,vlans.customer_id,subnets.subnet,subnets.mask,subnets.id AS subnetId,subnets.sectionId'.@$custom_fields_query.' FROM vlans LEFT JOIN subnets ON subnets.vlanId = vlans.vlanId where vlans.`domainId` = ? ORDER BY vlans.number ASC;';
140
+        # fetch
141
+        try { $vlans = $this->Database->getObjectsQuery($query, array($domainId)); }
142
+        catch (Exception $e) {
143
+            $this->Result->show("danger", _("Error: ").$e->getMessage());
144
+            return false;
145
+        }
146
+
147
+        # reorder
148
+        $out = array();
149
+        foreach ($vlans as $vlan) {
150
+            $out[$vlan->vlanId][] = $vlan;
151
+        }
152
+        # result
153
+        return is_array($out) ? array_values($out) : false;
154
+    }
155
+
156
+    /**
157
+     * Validates VLAN
158
+     *
159
+     *	not 1
160
+     *	integer
161
+     *	not higher that maxVLAN from settings
162
+     *
163
+     * @access public
164
+     * @param int $number
165
+     * @return mixed|bool
166
+     */
167
+    public function validate_vlan ($number) {
168
+        # fetch highest vlan id
169
+        $settings = $this->get_settings();
170
+
171
+        if(empty($number)) 							{ return true; }
172
+        elseif(!is_numeric($number)) 				{ return _('VLAN must be numeric value!'); }
173
+        elseif ($number > $settings['vlanMax']) 	{ return _('Vlan number can be max '.$settings['vlanMax']); }
174
+        else 										{ return true; }
175
+    }
176
+
177
+
178
+
179
+
180
+
181
+
182
+
183
+    /**
184
+     *	@search methods
185
+     *	--------------------------------
186
+     */
187
+
188
+
189
+    /**
190
+     * Search database for addresses
191
+     *
192
+     * @access public
193
+     * @param mixed $search_term
194
+     * @param string $high (default: "")
195
+     * @param string $low (default: "")
196
+     * @param array $custom_fields (default: array())
197
+     * @return array
198
+     */
199
+    public function search_addresses($search_term, $high = "", $low = "", $custom_fields = array()) {
200
+
201
+        $tags = $this->fetch_all_objects ("ipTags", "id");
202
+        foreach ($tags as $t) {
203
+            if(strtolower($t->type)==strtolower($search_term)) {
204
+                $tags = $t->id;
205
+                break;
206
+            }
207
+            $tags = false;
208
+        }
209
+
210
+        # set search query
211
+        $query[] = "select * from `ipaddresses` ";
212
+        $query[] = "where `ip_addr` between :low and :high ";	//ip range
213
+        $query[] = "or `hostname` like :search_term ";			//hostname
214
+        $query[] = "or `owner` like :search_term ";				//owner
215
+        # custom fields
216
+        if(sizeof($custom_fields) > 0) {
217
+            foreach($custom_fields as $myField) {
218
+                $myField['name'] = $this->Database->escape($myField['name']);
219
+                $query[] = "or `$myField[name]` like :search_term ";
220
+            }
221
+        }
222
+        $query[] = "or `switch` like :search_term ";
223
+        $query[] = "or `port` like :search_term ";				//port search
224
+        $query[] = "or `description` like :search_term ";		//descriptions
225
+        $query[] = "or `note` like :search_term ";				//note
226
+        $query[] = "or `mac` like :search_term ";				//mac
227
+        //tag
228
+        if($tags!==false)
229
+        $query[] = "or `state` like :tags ";				//tag
230
+        $query[] = "order by `ip_addr` asc;";
231
+
232
+        # join query
233
+        $query = implode("\n", $query);
234
+
235
+        # fetch
236
+        try { $result = $this->Database->getObjectsQuery($query, array("low"=>$low, "high"=>$high, "search_term"=>"%$search_term%", "tags"=>$tags)); }
237
+        catch (Exception $e) {
238
+            $this->Result->show("danger", _("Error: ").$e->getMessage());
239
+            return false;
240
+        }
241
+        # result
242
+        return $result;
243
+    }
244
+
245
+    /**
246
+     * Search subnets for provided range
247
+     *
248
+     *	First search range
249
+     *	If host provided search also inside subnet ranges
250
+     *
251
+     * @access public
252
+     * @param mixed $search_term
253
+     * @param string $high (default: "")
254
+     * @param string $low (default: "")
255
+     * @param mixed $search_req
256
+     * @param mixed $custom_fields (default: array())
257
+     * @return array
258
+     */
259
+    public function search_subnets($search_term, $high = "", $low = "", $search_req, $custom_fields = array()) {
260
+        # first search if range provided
261
+        $result1 = $this->search_subnets_range  ($search_term, $high, $low, $custom_fields);
262
+        # search inside subnets even if IP does not exist!
263
+        $result2 = $this->search_subnets_inside ($high, $low);
264
+        # search inside subnets even if IP does not exist - IPv6
265
+        $result3 = $this->search_subnets_inside_v6 ($high, $low, $search_req);
266
+        # merge arrays
267
+        $result = array_merge($result1, $result2, $result3);
268
+        # result
269
+        return array_filter($result);
270
+    }
271
+
272
+    /**
273
+     * Search for subnets inside range
274
+     *
275
+     * @access private
276
+     * @param mixed $search_term
277
+     * @param string $high
278
+     * @param string $low
279
+     * @param mixed $custom_fields (default: array())
280
+     * @return array
281
+     */
282
+    private function search_subnets_range ($search_term, $high, $low, $custom_fields = array()) {
283
+        # reformat low/high
284
+        if($high==0 && $low==0)	{ $high = "1"; $low="1"; }
285
+
286
+        # set search query
287
+        $query[] = "select * from `subnets` where `description` like :search_term ";
288
+        $query[] = "or `subnet` between :low and :high ";
289
+        # custom
290
+        if(sizeof($custom_fields) > 0) {
291
+            foreach($custom_fields as $myField) {
292
+                $myField['name'] = $this->Database->escape($myField['name']);
293
+                $query[] = " or `$myField[name]` like :search_term ";
294
+            }
295
+        }
296
+        $query[] = "order by `subnet` asc, `mask` asc;";
297
+
298
+        # join query
299
+        $query = implode("\n", $query);
300
+
301
+        # fetch
302
+        try { $result = $this->Database->getObjectsQuery($query, array("low"=>$low, "high"=>$high, "search_term"=>"%$search_term%")); }
303
+        catch (Exception $e) {
304
+            $this->Result->show("danger", _("Error: ").$e->getMessage());
305
+            return false;
306
+        }
307
+        # result
308
+        return $result;
309
+    }
310
+
311
+    /**
312
+     * Search inside subnets if host address is provided!
313
+     *
314
+     * @access private
315
+     * @param string $high
316
+     * @param string $low
317
+     * @return array
318
+     */
319
+    private function search_subnets_inside ($high, $low) {
320
+        if($low==$high) {
321
+            # subnets class
322
+            $Subnets = new Subnets ($this->Database);
323
+            # fetch all subnets
324
+            $subnets = $Subnets->fetch_all_subnets_search();
325
+            # loop and search
326
+            $ids = array();
327
+            foreach($subnets as $s) {
328
+                # cast
329
+                $s = (array) $s;
330
+
331
+                //first verify address type
332
+                $type = $this->identify_address($s['subnet']);
333
+
334
+                if($type == "IPv4") {
335
+                    # Initialize PEAR NET object
336
+                    $this->initialize_pear_net_IPv4 ();
337
+                    # parse address
338
+                    $net = $this->Net_IPv4->parseAddress($this->transform_address($s['subnet']).'/'.$s['mask'], "dotted");
339
+
340
+                    if($low>$this->transform_to_decimal(@$net->network) && $low<$this->transform_address($net->broadcast, "decimal")) {
341
+                        $ids[] = $s['id'];
342
+                    }
343
+                }
344
+            }
345
+            # filter
346
+            $ids = sizeof(@$ids)>0 ? array_filter($ids) : array();
347
+
348
+            $result = array();
349
+
350
+            # search
351
+            if(sizeof($ids)>0) {
352
+                foreach($ids as $id) {
353
+                    $result[] = $Subnets->fetch_subnet(null, $id);
354
+                }
355
+            }
356
+            # return
357
+            return sizeof(@$result)>0 ? array_filter($result) : array();
358
+        }
359
+        else {
360
+            return array();
361
+        }
362
+    }
363
+
364
+
365
+    /**
366
+     * Search inside subnets if host address is provided! ipv6
367
+     *
368
+     * @access private
369
+     * @param string $high
370
+     * @param string $low
371
+     * @return array
372
+     */
373
+    private function search_subnets_inside_v6 ($high, $low, $search_req) {
374
+        // same
375
+        if($low==$high) {
376
+            # Initialize PEAR NET object
377
+            $this->initialize_pear_net_IPv6 ();
378
+
379
+            // validate
380
+            if ($this->Net_IPv6->checkIPv6($search_req)) {
381
+                # subnets class
382
+                $Subnets = new Subnets ($this->Database);
383
+                # fetch all subnets
384
+                $subnets = $Subnets->fetch_all_subnets_search("IPv6");
385
+                # loop and search
386
+                $ids = array();
387
+                foreach($subnets as $s) {
388
+                    # cast
389
+                    $s = (array) $s;
390
+                    # parse address
391
+                    $net = $this->Net_IPv6->parseAddress($this->transform_address($s['subnet'], "dotted").'/'.$s['mask']);
392
+
393
+                    if(gmp_cmp($low, $this->transform_address(@$net['start'], "decimal")) == 1 && gmp_cmp($low, $this->transform_address(@$net['end'], "decimal")) == -1) {
394
+                        $ids[] = $s['id'];
395
+
396
+                    }
397
+                }
398
+                # filter
399
+                $ids = sizeof(@$ids)>0 ? array_filter($ids) : array();
400
+                # search
401
+                $result = array();
402
+                if(sizeof($ids)>0) {
403
+                    foreach($ids as $id) {
404
+                        $result[] = $Subnets->fetch_subnet(null, $id);
405
+                    }
406
+                }
407
+                # return
408
+                return sizeof(@$result)>0 ? array_filter($result) : array();
409
+            }
410
+            // empty
411
+            else {
412
+                return array();
413
+            }
414
+        }
415
+        else {
416
+            return array();
417
+        }
418
+    }
419
+
420
+    /**
421
+     * Function to search vlans
422
+     *
423
+     * @access public
424
+     * @param mixed $search_term
425
+     * @param array $custom_fields (default: array())
426
+     * @return array
427
+     */
428
+    public function search_vlans($search_term, $custom_fields = array()) {
429
+        # query
430
+        $query[] = "select * from `vlans` where `name` like :search_term or `description` like :search_term or `number` like :search_term ";
431
+        # custom
432
+        if(sizeof($custom_fields) > 0) {
433
+            foreach($custom_fields as $myField) {
434
+                $myField['name'] = $this->Database->escape($myField['name']);
435
+                $query[] = " or `$myField[name]` like :search_term ";
436
+            }
437
+        }
438
+        $query[] = ";";
439
+        # join query
440
+        $query = implode("\n", $query);
441
+
442
+        # fetch
443
+        try { $search = $this->Database->getObjectsQuery($query, array("search_term"=>"%$search_term%")); }
444
+        catch (Exception $e) {
445
+            $this->Result->show("danger", _("Error: ").$e->getMessage());
446
+            return false;
447
+        }
448
+
449
+        # return result
450
+        return $search;
451
+    }
452
+
453
+
454
+    /**
455
+     * Function to search vrf
456
+     *
457
+     * @access public
458
+     * @param mixed $search_term
459
+     * @param array $custom_fields (default: array())
460
+     * @return array
461
+     */
462
+    public function search_vrfs ($search_term, $custom_fields = array()) {
463
+        # query
464
+        $query[] = "select * from `vrf` where `name` like :search_term or `description` like :search_term or `rd` like :search_term ";
465
+        # custom
466
+        if(sizeof($custom_fields) > 0) {
467
+            foreach($custom_fields as $myField) {
468
+                $myField['name'] = $this->Database->escape($myField['name']);
469
+                $query[] = " or `$myField[name]` like :search_term ";
470
+            }
471
+        }
472
+        $query[] = ";";
473
+        # join query
474
+        $query = implode("\n", $query);
475
+
476
+        # fetch
477
+        try { $search = $this->Database->getObjectsQuery($query, array("search_term"=>"%$search_term%")); }
478
+        catch (Exception $e) {
479
+            $this->Result->show("danger", _("Error: ").$e->getMessage());
480
+            return false;
481
+        }
482
+
483
+        # return result
484
+        return $search;
485
+    }
486
+
487
+    /**
488
+     * Search for PSTN prefixes.
489
+     *
490
+     * @access public
491
+     * @param mixed $search_term
492
+     * @param array $custom_prefix_fields (default: array())
493
+     * @return array
494
+     */
495
+    public function search_pstn_refixes ($search_term, $custom_prefix_fields = array()) {
496
+        # query
497
+        $query[] = "select *,concat(prefix,start) as raw from `pstnPrefixes` where `prefix` like :search_term or `name` like :search_term or `description` like :search_term ";
498
+        # custom
499
+        if(sizeof($custom_prefix_fields) > 0) {
500
+            foreach($custom_prefix_fields as $myField) {
501
+                $myField['name'] = $this->Database->escape($myField['name']);
502
+                $query[] = " or `$myField[name]` like :search_term ";
503
+            }
504
+        }
505
+        $query[] = "order by  raw asc;";
506
+        # join query
507
+        $query = implode("\n", $query);
508
+
509
+        # fetch
510
+        try { $search = $this->Database->getObjectsQuery($query, array("search_term"=>"%$search_term%")); }
511
+        catch (Exception $e) {
512
+            $this->Result->show("danger", _("Error: ").$e->getMessage());
513
+            return false;
514
+        }
515
+
516
+        # return result
517
+        return $search;
518
+    }
519
+
520
+    /**
521
+     * Search for PSTN numbers.
522
+     *
523
+     * @access public
524
+     * @param mixed $search_term
525
+     * @param array $custom_prefix_fields (default: array())
526
+     * @return array
527
+     */
528
+    public function search_pstn_numbers ($search_term, $custom_prefix_fields = array()) {
529
+        # query
530
+        $query[] = "select * from `pstnNumbers` where `number` like :search_term or `name` like :search_term or `description` like :search_term or `owner` like :search_term ";
531
+        # custom
532
+        if(sizeof($custom_prefix_fields) > 0) {
533
+            foreach($custom_prefix_fields as $myField) {
534
+                $myField['name'] = $this->Database->escape($myField['name']);
535
+                $query[] = " or `$myField[name]` like :search_term ";
536
+            }
537
+        }
538
+        $query[] = "order by number asc;";
539
+        # join query
540
+        $query = implode("\n", $query);
541
+
542
+        # fetch
543
+        try { $search = $this->Database->getObjectsQuery($query, array("search_term"=>"%$search_term%")); }
544
+        catch (Exception $e) {
545
+            $this->Result->show("danger", _("Error: ").$e->getMessage());
546
+            return false;
547
+        }
548
+
549
+        # return result
550
+        return $search;
551
+    }
552
+
553
+    /**
554
+     * Search for circuits.
555
+     *
556
+     * @access public
557
+     * @param mixed $search_term
558
+     * @param array $custom_circuit_fields (default: array())
559
+     * @return array
560
+     */
561
+    public function search_circuits ($search_term, $custom_circuit_fields = array()) {
562
+        # query
563
+        $query[] = "select c.id,c.cid,c.type,c.device1,c.location1,c.device2,c.location2,p.name,p.description,p.contact,c.capacity,p.id as pid,c.status ";
564
+        $query[] = "from circuits as c, circuitProviders as p ";
565
+        $query[] = "where c.provider = p.id";
566
+        $query[] = "and (`cid` like :search_term or `type` like :search_term or `capacity` like :search_term or `comment` like :search_term or `name` like :search_term)";
567
+        # custom
568
+        if(sizeof($custom_circuit_fields) > 0) {
569
+            foreach($custom_circuit_fields as $myField) {
570
+                $myField['name'] = $this->Database->escape($myField['name']);
571
+                $query[] = " or `$myField[name]` like :search_term ";
572
+            }
573
+        }
574
+
575
+        $query[] = "order by c.cid asc;";
576
+        # join query
577
+        $query = implode("\n", $query);
578
+
579
+        # fetch
580
+        try { $search = $this->Database->getObjectsQuery($query, array("search_term"=>"%$search_term%")); }
581
+        catch (Exception $e) {
582
+            $this->Result->show("danger", _("Error: ").$e->getMessage());
583
+            return false;
584
+        }
585
+
586
+        # return result
587
+        return $search;
588
+    }
589
+
590
+
591
+    /**
592
+     * Search for circuit providers
593
+     *
594
+     * @access public
595
+     * @param mixed $search_term
596
+     * @param array $custom_circuit_fields (default: array())
597
+     * @return array
598
+     */
599
+    public function search_circuit_providers ($search_term, $custom_circuit_fields = array()) {
600
+        # query
601
+        $query[] = "select * from `circuitProviders` where `name` like :search_term or `description` like :search_term or `contact` like :search_term ";
602
+        # custom
603
+        if(sizeof($custom_circuit_fields) > 0) {
604
+            foreach($custom_circuit_fields as $myField) {
605
+                $myField['name'] = $this->Database->escape($myField['name']);
606
+                $query[] = " or `$myField[name]` like :search_term ";
607
+            }
608
+        }
609
+        $query[] = "order by name asc;";
610
+        # join query
611
+        $query = implode("\n", $query);
612
+
613
+        # fetch
614
+        try { $search = $this->Database->getObjectsQuery($query, array("search_term"=>"%$search_term%")); }
615
+        catch (Exception $e) {
616
+            $this->Result->show("danger", _("Error: ").$e->getMessage());
617
+            return false;
618
+        }
619
+
620
+        # return result
621
+        return $search;
622
+    }
623
+
624
+    /**
625
+     * Reformat possible nun-full IPv4 address for search
626
+     *
627
+     *	e.g. 10.10.10 -> 10.10.10.0 - 10.10.10.255
628
+     *
629
+     * @access public
630
+     * @param mixed $address
631
+     * @return array high/low decimal address
632
+     */
633
+    public function reformat_IPv4_for_search ($address) {
634
+        # remove % sign if present
635
+        $address = str_replace("%", "", $address);
636
+        # we need Addresses class
637
+        $Addresses = new Addresses ($this->Database);
638
+
639
+        # if subnet is provided we have all data
640
+        if(strpos($address, "/")>0) {
641
+            # Initialize PEAR NET object
642
+            $this->initialize_pear_net_IPv4 ();
643
+            $net = $this->Net_IPv4->parseAddress($address);
644
+
645
+            $result['low']   = $Addresses->transform_to_decimal($net->network);
646
+            $result['high']	 = $Addresses->transform_to_decimal($net->broadcast);
647
+        }
648
+        # else calculate options
649
+        else {
650
+            # if subnet is not provided maybe wildcard is, so explode it to array
651
+            $address = explode(".", $address);
652 652
             # remove empty
653 653
             foreach($address as $k=>$a) {
654 654
                 if (strlen($a)==0)  unset($address[$k]);
655 655
             }
656
-
657
-			# 4 pieces is ok, host
658
-			if (sizeof($address) == 4) {
659
-				$result['low'] = $result['high'] = $Addresses->transform_to_decimal(implode(".", $address));
660
-			}
661
-			# 3 pieces, we need to modify > check whole subnet
662
-			elseif (sizeof($address) == 3) {
663
-				$result['low']  = $Addresses->transform_to_decimal(implode(".", array_merge($address, array(0))));
664
-				$result['high'] = $Addresses->transform_to_decimal(implode(".", array_merge($address, array(255))));
665
-			}
666
-			# 2 pieces also
667
-			elseif (sizeof($address) == 2) {
668
-				$result['low']  = $Addresses->transform_to_decimal(implode(".", array_merge($address, array(0,0))));
669
-				$result['high'] = $Addresses->transform_to_decimal(implode(".", array_merge($address, array(255,255))));
670
-			}
671
-			# 1 piece also
672
-			elseif (sizeof($address) == 1) {
673
-				$result['low']  = $Addresses->transform_to_decimal(implode(".", array_merge($address, array(0,0,0))));
674
-				$result['high'] = $Addresses->transform_to_decimal(implode(".", array_merge($address, array(255,255,255))));
675
-			}
676
-			# else return same value
677
-			else {
678
-				$result['low']  = implode(".", $address);
679
-				$result['high'] = implode(".", $address);
680
-			}
681
-		}
682
-		# return result array low/high
683
-		return $result;
684
-	}
685
-
686
-	/**
687
-	 * Reformat possible non-full IPv6 address for search - set lowest and highest IPs
688
-	 *
689
-	 *	we can have
690
-	 *		a:a:a:a:a:a:a
691
-	 *		a:a:a::a
692
-	 *		a:a:a:a:a:a:a:a/mask
693
-	 *
694
-	 * @access public
695
-	 * @param mixed $address
696
-	 * @return array
697
-	 */
698
-	public function reformat_IPv6_for_search ($address) {
699
-		# parse address
700
-		$this->initialize_pear_net_IPv6 ();
701
-
702
-		$return = array();
703
-
704
-		# validate
705
-		if ($this->Net_IPv6->checkIPv6($address)==false) {
706
-			// return 0
707
-			return array("high"=>0, "low"=>0);
708
-		}
709
-		else {
710
-			# fake mask
711
-			if (strpos($address, "/")==0)	{ $address .= "/128"; }
712
-
713
-			# parse address
714
-			$parsed = $this->Net_IPv6->parseAddress($address);
715
-
716
-			# result
717
-			$return['low']  = gmp_strval($this->transform_address($parsed['start'], "decimal"));
718
-			$return['high'] = gmp_strval($this->transform_address($parsed['end'], "decimal"));
719
-
720
-			# return result array low/high
721
-			return $return;
722
-		}
723
-	}
724
-
725
-
726
-
727
-
728
-
729
-
730
-
731
-
732
-
733
-
734
-
735
-
736
-
737
-	/**
738
-	 *	@custom fields methods
739
-	 *	--------------------------------
740
-	 */
741
-
742
-	/**
743
-	 * Fetches all custom fields
744
-	 *
745
-	 * @access public
746
-	 * @param mixed $table
747
-	 * @return array
748
-	 */
749
-	public function fetch_custom_fields ($table) {
750
-    	# fetch columns
751
-		$fields = $this->fetch_columns ($table);
752
-
753
-		$res = array();
754
-
755
-		# save Field values only
756
-		foreach($fields as $field) {
757
-			# cast
758
-			$field = (array) $field;
759
-
760
-			$res[$field['Field']]['name'] 	 = $field['Field'];
761
-			$res[$field['Field']]['type'] 	 = $field['Type'];
762
-			$res[$field['Field']]['Comment'] = $field['Comment'];
763
-			$res[$field['Field']]['Null'] 	 = $field['Null'];
764
-			$res[$field['Field']]['Default'] = $field['Default'];
765
-		}
766
-
767
-		# fetch standard fields
768
-		$standard = $this->fetch_standard_fields ($table);
769
-
770
-		# remove them
771
-		foreach($standard as $st) {
772
-			unset($res[$st]);
773
-		}
774
-		# return array
775
-		return sizeof($res)==0 ? array() : $res;
776
-	}
777
-
778
-	/**
779
-	 * Fetches all custom fields and reorders them into numeric array
780
-	 *
781
-	 * @access public
782
-	 * @param mixed $table
783
-	 * @return array
784
-	 */
785
-	public function fetch_custom_fields_numeric ($table) {
786
-		# fetch all custom fields
787
-		$custom_fields = $this->fetch_custom_fields ($table);
788
-		# make numberic array
789
-		if(sizeof($custom_fields)>0) {
790
-			foreach($custom_fields as $f) {
791
-				$out[] = $f;
792
-			}
793
-			# result
794
-			return isset($out) ? $out : array();
795
-		}
796
-		else {
797
-			return array();
798
-		}
799
-	}
800
-
801
-	/**
802
-	 * Fetch all fields configured in table - standard + custom
803
-	 *
804
-	 * @access private
805
-	 * @param mixed $table
806
-	 * @return array
807
-	 */
808
-	private function fetch_columns ($table) {
809
-		# escape method/table
810
-		$table = $this->Database->escape($table);
811
-    	# fetch columns
812
-		$query    = "show full columns from `$table`;";
813
-		# fetch
814
-	    try { $fields = $this->Database->getObjectsQuery($query); }
815
-		catch (Exception $e) { $this->Result->show("danger", $e->getMessage(), false);	return false; }
816
-
817
-		return (array) $fields;
818
-	}
819
-
820
-	/**
821
-	 * Read the SCHEMA.sql file and enforce UNIX LF
822
-	 *
823
-	 * @access private
824
-	 * @return array
825
-	 */
826
-	private function read_db_schema() {
827
-		$fh = fopen(dirname(__FILE__) . '/../../db/SCHEMA.sql', 'r');
828
-		$schema = str_replace("\r\n", "\n", fread($fh, 100000));
829
-		return $schema;
830
-	}
831
-
832
-	/**
833
-	 * Fetches standard database fields from SCHEMA.sql file
834
-	 *
835
-	 * @access public
836
-	 * @param mixed $table
837
-	 * @return array
838
-	 */
839
-	public function fetch_standard_fields ($table) {
840
-		# get SCHEMA.SQL file
841
-		$schema = $this->read_db_schema();
842
-
843
-		# get definition
844
-		$definition = strstr($schema, "CREATE TABLE `$table` (");
845
-		$definition = trim(strstr($definition, ";" . "\n", true));
846
-
847
-		# get each line to array
848
-		$definition = explode("\n", $definition);
849
-
850
-		# go through,if it begins with ` use it !
851
-		$out = array();
852
-		foreach($definition as $d) {
853
-			$d = trim($d);
854
-			if(strpos(trim($d), "`")==0) {
855
-				$d = strstr(trim($d, "`"), "`", true);
856
-				$out[] = substr($d, strpos($d, "`"));
857
-			}
858
-		}
859
-		# return array of fields
860
-		return is_array($out) ? array_filter($out) : array();
861
-	}
862
-
863
-	/**
864
-	 * Fetches standard tables from SCHEMA.sql file
865
-	 *
866
-	 * @return array
867
-	 */
868
-	public function fetch_standard_tables () {
869
-		# get SCHEMA.SQL file
870
-		$schema = $this->read_db_schema();
871
-
872
-		# get definitions to array, explode with CREATE TABLE `
873
-		$creates = explode("CREATE TABLE `", $schema);
874
-		# fill tables array
875
-		$tables = array();
876
-		foreach($creates as $k=>$c) {
877
-			if($k>0)	{ $tables[] = strstr($c, "`", true); }	//we exclude first !
878
-		}
879
-
880
-		# return array of tables
881
-		return $tables;
882
-	}
883
-
884
-	/**
885
-	 * This functions fetches all columns for specified Field
886
-	 *
887
-	 * Array (Field, Type, Collation, Null, Comment)
888
-	 *
889
-	 * @access public
890
-	 * @param mixed $table
891
-	 * @param mixed $field
892
-	 * @return array
893
-	 */
894
-	public function fetch_full_field_definition ($table, $field) {
895
-		# escape field
896
-		$table = $this->Database->escape($table);
897
-		# fetch
898
-	    try { $field_data = $this->Database->getObjectQuery("show full columns from `$table` where `Field` = ?;", array($field)); }
899
-		catch (Exception $e) { $this->Result->show("danger", $e->getMessage(), false);	return false; }
900
-		# result
901
-	    return($field_data);
902
-	}
903
-
904
-
905
-
906
-
907
-
908
-
909
-
910
-
911
-
912
-
913
-
914
-
915
-	/**
916
-	 *	@widget methods
917
-	 *	--------------------------------
918
-	 */
919
-
920
-	/**
921
-	 * Fetches all widgets
922
-	 *
923
-	 * @access public
924
-	 * @param bool $admin (default: false)
925
-	 * @param bool $inactive (default: false)
926
-	 * @return array
927
-	 */
928
-	public function fetch_widgets ($admin = false, $inactive = false) {
929
-
930
-		# inactive also - only for administration
931
-		if($inactive) 			{ $query = "select * from `widgets`; "; }
932
-		else {
933
-			# admin?
934
-			if($admin) 			{ $query = "select * from `widgets` where `wactive` = 'yes'; "; }
935
-			else				{ $query = "select * from `widgets` where `wadminonly` = 'no' and `wactive` = 'yes'; "; }
936
-		}
937
-	    # fetch
938
-	    try { $widgets = $this->Database->getObjectsQuery($query); }
939
-		catch (Exception $e) { $this->Result->show("danger", $e->getMessage(), false);	return false; }
940
-
941
-	    # reindex
942
-	    $wout = array();
943
-	    foreach($widgets as $w) {
944
-			$wout[$w->wfile] = $w;
945
-	    }
946
-
947
-	    # return results
948
-	    return $wout;
949
-	}
950
-
951
-	/**
952
-	 * Verify that widget file exists
953
-	 *
954
-	 * @access public
955
-	 * @return bool
956
-	 */
957
-	public function verify_widget ($file) {
958
-		return file_exists(dirname(__FILE__)."/../../app/dashboard/widgets/$file.php")||file_exists(dirname(__FILE__)."/../../app/dashboard/widgets/custom/$file.php") ? true : false;
959
-	}
960
-
961
-
962
-
963
-
964
-
965
-
966
-
967
-
968
-
969
-
970
-	/**
971
-	 *	@request methods (for IP request)
972
-	 *	--------------------------------
973
-	 */
974
-
975
-	/**
976
-	 * fetches all IP requests and saves them to $requests
977
-	 *
978
-	 * @access public
979
-	 * @return int|array
980
-	 */
981
-	public function requests_fetch ($num = true) {
982
-		return $num ? $this->requests_fetch_num () : $this->requests_fetch_objects ();
983
-	}
984
-
985
-	/**
986
-	 * Fetches number of active IP requests
987
-	 *
988
-	 * @access private
989
-	 * @return int
990
-	 */
991
-	private function requests_fetch_num () {
992
-    	return $this->count_database_objects ("requests", "processed", 0);
993
-	}
994
-
995
-	/**
996
-	 * Fetches all requests and saves them to $requests
997
-	 *
998
-	 * @access private
999
-	 * @return array
1000
-	 */
1001
-	private function requests_fetch_objects () {
1002
-    	return $this->fetch_multiple_objects ("requests", "processed", 0);
1003
-	}
1004
-
1005
-	/**
1006
-	 * Fetches all subnets that are set to allow requests
1007
-	 *
1008
-	 * @access public
1009
-	 * @return array|null
1010
-	 */
1011
-	public function requests_fetch_available_subnets () {
1012
-		try { $subnets = $this->Database->getObjectsQuery("SELECT * FROM `subnets` where `allowRequests`=1 and `isFull` != 1 ORDER BY `subnet`;"); }
1013
-		catch (Exception $e) { $this->Result->show("danger", $e->getMessage(), false);	return false; }
1014
-
1015
-		# save
1016
-		return sizeof($subnets)>0 ? (array) $subnets : NULL;
1017
-	}
1018
-
1019
-	/**
1020
-	 * Sends mail for IP request
1021
-	 *
1022
-	 * @access public
1023
-	 * @param string $action (default: "new")
1024
-	 * @param mixed $values
1025
-	 * @return bool
1026
-	 */
1027
-	public function ip_request_send_mail ($action="new", $values) {
1028
-
1029
-		$this->get_settings ();
1030
-
1031
-		# try to send
1032
-		try {
1033
-			# fetch mailer settings
1034
-			$mail_settings = $this->fetch_object("settingsMail", "id", 1);
1035
-
1036
-			# initialize mailer
1037
-			$phpipam_mail = new phpipam_mail($this->settings, $mail_settings);
1038
-
1039
-			# get all users and check who to end mail to
1040
-			$recipients = $this->ip_request_get_mail_recipients ($values['subnetId']);
1041
-
1042
-			# add requester to cc
1043
-			$recipients_requester = $values['requester'];
1044
-
1045
-			# reformat key / vaues
1046
-			$values = $this->ip_request_reformat_mail_values ($values);
1047
-			#reformat empty
1048
-			$values = $this->reformat_empty_array_fields ($values, "/");
1049
-
1050
-			# generate content
1051
-			if ($action=="new")			{ $subject	= "New IP address request"; }
1052
-			elseif ($action=="accept")	{ $subject	= "IP address request accepted"; }
1053
-			elseif ($action=="reject")	{ $subject	= "IP address request rejected"; }
1054
-			else						{ $this->Result->show("danger", _("Invalid request action"), true); }
1055
-
1056
-			// set html content
1057
-			$content[] = "<table style='margin-left:10px;margin-top:20px;width:auto;padding:0px;border-collapse:collapse;'>";
1058
-			$content[] = "<tr><td colspan='2' style='margin:0px;>$this->mail_font_style <strong>$subject</strong></font></td></tr>";
1059
-			foreach($values as $k=>$v) {
1060
-			// title search
1061
-			if (preg_match("/s_title_/", $k)) {
1062
-			$content[] = "<tr><td colspan='2' style='margin:0px;border-bottom:1px solid #eeeeee;'>$this->mail_font_style<strong>$v</strong></font></td></tr>";
1063
-			}
1064
-			else {
1065
-			//content
1066
-			$content[] = "<tr>";
1067
-			$content[] = "<td style='padding-left:15px;margin:0px;'>$this->mail_font_style $k</font></td>";
1068
-			$content[] = "<td style='padding-left:15px;margin:0px;'>$this->mail_font_style $v</font></td>";
1069
-			$content[] = "</tr>";
1070
-			}
1071
-			}
1072
-			$content[] = "<tr><td style='padding-top:15px;padding-bottom:3px;text-align:right;color:#ccc;'>$this->mail_font_style Sent at ".date('Y/m/d H:i')."</font></td></tr>";
1073
-			//set alt content
1074
-			$content_plain[] = "$subject"."\r\n------------------------------\r\n";
1075
-			foreach($values as $k=>$v) {
1076
-			$content_plain[] = $k." => ".$v;
1077
-			}
1078
-			$content_plain[] = "\r\n\r\nSent at ".date('Y/m/d H:i');
1079
-			$content[] = "</table>";
1080
-
1081
-			// set content
1082
-			$content 		= $phpipam_mail->generate_message (implode("\r\n", $content));
1083
-			$content_plain 	= implode("\r\n",$content_plain);
1084
-
1085
-			$phpipam_mail->Php_mailer->setFrom($mail_settings->mAdminMail, $mail_settings->mAdminName);
1086
-			if ($recipients!==false) {
1087
-			foreach($recipients as $r) {
1088
-			$phpipam_mail->Php_mailer->addAddress(addslashes(trim($r->email)));
1089
-			}
1090
-			$phpipam_mail->Php_mailer->AddCC(addslashes(trim($recipients_requester)));
1091
-			}
1092
-			else {
1093
-			$phpipam_mail->Php_mailer->addAddress(addslashes(trim($recipients_requester)));
1094
-			}
1095
-			$phpipam_mail->Php_mailer->Subject = $subject;
1096
-			$phpipam_mail->Php_mailer->msgHTML($content);
1097
-			$phpipam_mail->Php_mailer->AltBody = $content_plain;
1098
-			//send
1099
-			$phpipam_mail->Php_mailer->send();
1100
-		} catch (phpmailerException $e) {
1101
-			$this->Result->show("danger", "Mailer Error: ".$e->errorMessage(), true);
1102
-		} catch (Exception $e) {
1103
-			$this->Result->show("danger", "Mailer Error: ".$e->getMessage(), true);
1104
-		}
1105
-
1106
-		# ok
1107
-		return true;
1108
-
1109
-	}
1110
-
1111
-	/**
1112
-	 * Returns list of recipients to get new
1113
-	 *
1114
-	 * @access private
1115
-	 * @param bool|mixed $subnetId
1116
-	 * @return array|bool
1117
-	 */
1118
-	private function ip_request_get_mail_recipients ($subnetId = false) {
1119
-    	// fetch all users with mailNotify
1120
-        $notification_users = $this->fetch_multiple_objects ("users", "mailNotify", "Yes", "id", true);
1121
-        // recipients array
1122
-        $recipients = array();
1123
-        // any ?
1124
-        if ($notification_users!==false) {
1125
-         	// if subnetId is set check who has permissions
1126
-        	if (isset($subnetId)) {
1127
-             	foreach ($notification_users as $u) {
1128
-                	// inti object
1129
-                	$Subnets = new Subnets ($this->Database);
1130
-                	//check permissions
1131
-                	$subnet_permission = $Subnets->check_permission($u, $subnetId);
1132
-                	// if 3 than add
1133
-                	if ($subnet_permission==3) {
1134
-                    	$recipients[] = $u;
1135
-                	}
1136
-            	}
1137
-        	}
1138
-        	else {
1139
-            	foreach ($notification_users as $u) {
1140
-                	if($u->role=="Administrator") {
1141
-                    	$recipients[] = $u;
1142
-                	}
1143
-            	}
1144
-        	}
1145
-        	return sizeof($recipients)>0 ? $recipients : false;
656
+
657
+            # 4 pieces is ok, host
658
+            if (sizeof($address) == 4) {
659
+                $result['low'] = $result['high'] = $Addresses->transform_to_decimal(implode(".", $address));
660
+            }
661
+            # 3 pieces, we need to modify > check whole subnet
662
+            elseif (sizeof($address) == 3) {
663
+                $result['low']  = $Addresses->transform_to_decimal(implode(".", array_merge($address, array(0))));
664
+                $result['high'] = $Addresses->transform_to_decimal(implode(".", array_merge($address, array(255))));
665
+            }
666
+            # 2 pieces also
667
+            elseif (sizeof($address) == 2) {
668
+                $result['low']  = $Addresses->transform_to_decimal(implode(".", array_merge($address, array(0,0))));
669
+                $result['high'] = $Addresses->transform_to_decimal(implode(".", array_merge($address, array(255,255))));
670
+            }
671
+            # 1 piece also
672
+            elseif (sizeof($address) == 1) {
673
+                $result['low']  = $Addresses->transform_to_decimal(implode(".", array_merge($address, array(0,0,0))));
674
+                $result['high'] = $Addresses->transform_to_decimal(implode(".", array_merge($address, array(255,255,255))));
675
+            }
676
+            # else return same value
677
+            else {
678
+                $result['low']  = implode(".", $address);
679
+                $result['high'] = implode(".", $address);
680
+            }
681
+        }
682
+        # return result array low/high
683
+        return $result;
684
+    }
685
+
686
+    /**
687
+     * Reformat possible non-full IPv6 address for search - set lowest and highest IPs
688
+     *
689
+     *	we can have
690
+     *		a:a:a:a:a:a:a
691
+     *		a:a:a::a
692
+     *		a:a:a:a:a:a:a:a/mask
693
+     *
694
+     * @access public
695
+     * @param mixed $address
696
+     * @return array
697
+     */
698
+    public function reformat_IPv6_for_search ($address) {
699
+        # parse address
700
+        $this->initialize_pear_net_IPv6 ();
701
+
702
+        $return = array();
703
+
704
+        # validate
705
+        if ($this->Net_IPv6->checkIPv6($address)==false) {
706
+            // return 0
707
+            return array("high"=>0, "low"=>0);
708
+        }
709
+        else {
710
+            # fake mask
711
+            if (strpos($address, "/")==0)	{ $address .= "/128"; }
712
+
713
+            # parse address
714
+            $parsed = $this->Net_IPv6->parseAddress($address);
715
+
716
+            # result
717
+            $return['low']  = gmp_strval($this->transform_address($parsed['start'], "decimal"));
718
+            $return['high'] = gmp_strval($this->transform_address($parsed['end'], "decimal"));
719
+
720
+            # return result array low/high
721
+            return $return;
722
+        }
723
+    }
724
+
725
+
726
+
727
+
728
+
729
+
730
+
731
+
732
+
733
+
734
+
735
+
736
+
737
+    /**
738
+     *	@custom fields methods
739
+     *	--------------------------------
740
+     */
741
+
742
+    /**
743
+     * Fetches all custom fields
744
+     *
745
+     * @access public
746
+     * @param mixed $table
747
+     * @return array
748
+     */
749
+    public function fetch_custom_fields ($table) {
750
+        # fetch columns
751
+        $fields = $this->fetch_columns ($table);
752
+
753
+        $res = array();
754
+
755
+        # save Field values only
756
+        foreach($fields as $field) {
757
+            # cast
758
+            $field = (array) $field;
759
+
760
+            $res[$field['Field']]['name'] 	 = $field['Field'];
761
+            $res[$field['Field']]['type'] 	 = $field['Type'];
762
+            $res[$field['Field']]['Comment'] = $field['Comment'];
763
+            $res[$field['Field']]['Null'] 	 = $field['Null'];
764
+            $res[$field['Field']]['Default'] = $field['Default'];
765
+        }
766
+
767
+        # fetch standard fields
768
+        $standard = $this->fetch_standard_fields ($table);
769
+
770
+        # remove them
771
+        foreach($standard as $st) {
772
+            unset($res[$st]);
773
+        }
774
+        # return array
775
+        return sizeof($res)==0 ? array() : $res;
776
+    }
777
+
778
+    /**
779
+     * Fetches all custom fields and reorders them into numeric array
780
+     *
781
+     * @access public
782
+     * @param mixed $table
783
+     * @return array
784
+     */
785
+    public function fetch_custom_fields_numeric ($table) {
786
+        # fetch all custom fields
787
+        $custom_fields = $this->fetch_custom_fields ($table);
788
+        # make numberic array
789
+        if(sizeof($custom_fields)>0) {
790
+            foreach($custom_fields as $f) {
791
+                $out[] = $f;
792
+            }
793
+            # result
794
+            return isset($out) ? $out : array();
795
+        }
796
+        else {
797
+            return array();
798
+        }
799
+    }
800
+
801
+    /**
802
+     * Fetch all fields configured in table - standard + custom
803
+     *
804
+     * @access private
805
+     * @param mixed $table
806
+     * @return array
807
+     */
808
+    private function fetch_columns ($table) {
809
+        # escape method/table
810
+        $table = $this->Database->escape($table);
811
+        # fetch columns
812
+        $query    = "show full columns from `$table`;";
813
+        # fetch
814
+        try { $fields = $this->Database->getObjectsQuery($query); }
815
+        catch (Exception $e) { $this->Result->show("danger", $e->getMessage(), false);	return false; }
816
+
817
+        return (array) $fields;
818
+    }
819
+
820
+    /**
821
+     * Read the SCHEMA.sql file and enforce UNIX LF
822
+     *
823
+     * @access private
824
+     * @return array
825
+     */
826
+    private function read_db_schema() {
827
+        $fh = fopen(dirname(__FILE__) . '/../../db/SCHEMA.sql', 'r');
828
+        $schema = str_replace("\r\n", "\n", fread($fh, 100000));
829
+        return $schema;
830
+    }
831
+
832
+    /**
833
+     * Fetches standard database fields from SCHEMA.sql file
834
+     *
835
+     * @access public
836
+     * @param mixed $table
837
+     * @return array
838
+     */
839
+    public function fetch_standard_fields ($table) {
840
+        # get SCHEMA.SQL file
841
+        $schema = $this->read_db_schema();
842
+
843
+        # get definition
844
+        $definition = strstr($schema, "CREATE TABLE `$table` (");
845
+        $definition = trim(strstr($definition, ";" . "\n", true));
846
+
847
+        # get each line to array
848
+        $definition = explode("\n", $definition);
849
+
850
+        # go through,if it begins with ` use it !
851
+        $out = array();
852
+        foreach($definition as $d) {
853
+            $d = trim($d);
854
+            if(strpos(trim($d), "`")==0) {
855
+                $d = strstr(trim($d, "`"), "`", true);
856
+                $out[] = substr($d, strpos($d, "`"));
857
+            }
858
+        }
859
+        # return array of fields
860
+        return is_array($out) ? array_filter($out) : array();
861
+    }
862
+
863
+    /**
864
+     * Fetches standard tables from SCHEMA.sql file
865
+     *
866
+     * @return array
867
+     */
868
+    public function fetch_standard_tables () {
869
+        # get SCHEMA.SQL file
870
+        $schema = $this->read_db_schema();
871
+
872
+        # get definitions to array, explode with CREATE TABLE `
873
+        $creates = explode("CREATE TABLE `", $schema);
874
+        # fill tables array
875
+        $tables = array();
876
+        foreach($creates as $k=>$c) {
877
+            if($k>0)	{ $tables[] = strstr($c, "`", true); }	//we exclude first !
878
+        }
879
+
880
+        # return array of tables
881
+        return $tables;
882
+    }
883
+
884
+    /**
885
+     * This functions fetches all columns for specified Field
886
+     *
887
+     * Array (Field, Type, Collation, Null, Comment)
888
+     *
889
+     * @access public
890
+     * @param mixed $table
891
+     * @param mixed $field
892
+     * @return array
893
+     */
894
+    public function fetch_full_field_definition ($table, $field) {
895
+        # escape field
896
+        $table = $this->Database->escape($table);
897
+        # fetch
898
+        try { $field_data = $this->Database->getObjectQuery("show full columns from `$table` where `Field` = ?;", array($field)); }
899
+        catch (Exception $e) { $this->Result->show("danger", $e->getMessage(), false);	return false; }
900
+        # result
901
+        return($field_data);
902
+    }
903
+
904
+
905
+
906
+
907
+
908
+
909
+
910
+
911
+
912
+
913
+
914
+
915
+    /**
916
+     *	@widget methods
917
+     *	--------------------------------
918
+     */
919
+
920
+    /**
921
+     * Fetches all widgets
922
+     *
923
+     * @access public
924
+     * @param bool $admin (default: false)
925
+     * @param bool $inactive (default: false)
926
+     * @return array
927
+     */
928
+    public function fetch_widgets ($admin = false, $inactive = false) {
929
+
930
+        # inactive also - only for administration
931
+        if($inactive) 			{ $query = "select * from `widgets`; "; }
932
+        else {
933
+            # admin?
934
+            if($admin) 			{ $query = "select * from `widgets` where `wactive` = 'yes'; "; }
935
+            else				{ $query = "select * from `widgets` where `wadminonly` = 'no' and `wactive` = 'yes'; "; }
936
+        }
937
+        # fetch
938
+        try { $widgets = $this->Database->getObjectsQuery($query); }
939
+        catch (Exception $e) { $this->Result->show("danger", $e->getMessage(), false);	return false; }
940
+
941
+        # reindex
942
+        $wout = array();
943
+        foreach($widgets as $w) {
944
+            $wout[$w->wfile] = $w;
945
+        }
946
+
947
+        # return results
948
+        return $wout;
949
+    }
950
+
951
+    /**
952
+     * Verify that widget file exists
953
+     *
954
+     * @access public
955
+     * @return bool
956
+     */
957
+    public function verify_widget ($file) {
958
+        return file_exists(dirname(__FILE__)."/../../app/dashboard/widgets/$file.php")||file_exists(dirname(__FILE__)."/../../app/dashboard/widgets/custom/$file.php") ? true : false;
959
+    }
960
+
961
+
962
+
963
+
964
+
965
+
966
+
967
+
968
+
969
+
970
+    /**
971
+     *	@request methods (for IP request)
972
+     *	--------------------------------
973
+     */
974
+
975
+    /**
976
+     * fetches all IP requests and saves them to $requests
977
+     *
978
+     * @access public
979
+     * @return int|array
980
+     */
981
+    public function requests_fetch ($num = true) {
982
+        return $num ? $this->requests_fetch_num () : $this->requests_fetch_objects ();
983
+    }
984
+
985
+    /**
986
+     * Fetches number of active IP requests
987
+     *
988
+     * @access private
989
+     * @return int
990
+     */
991
+    private function requests_fetch_num () {
992
+        return $this->count_database_objects ("requests", "processed", 0);
993
+    }
994
+
995
+    /**
996
+     * Fetches all requests and saves them to $requests
997
+     *
998
+     * @access private
999
+     * @return array
1000
+     */
1001
+    private function requests_fetch_objects () {
1002
+        return $this->fetch_multiple_objects ("requests", "processed", 0);
1003
+    }
1004
+
1005
+    /**
1006
+     * Fetches all subnets that are set to allow requests
1007
+     *
1008
+     * @access public
1009
+     * @return array|null
1010
+     */
1011
+    public function requests_fetch_available_subnets () {
1012
+        try { $subnets = $this->Database->getObjectsQuery("SELECT * FROM `subnets` where `allowRequests`=1 and `isFull` != 1 ORDER BY `subnet`;"); }
1013
+        catch (Exception $e) { $this->Result->show("danger", $e->getMessage(), false);	return false; }
1014
+
1015
+        # save
1016
+        return sizeof($subnets)>0 ? (array) $subnets : NULL;
1017
+    }
1018
+
1019
+    /**
1020
+     * Sends mail for IP request
1021
+     *
1022
+     * @access public
1023
+     * @param string $action (default: "new")
1024
+     * @param mixed $values
1025
+     * @return bool
1026
+     */
1027
+    public function ip_request_send_mail ($action="new", $values) {
1028
+
1029
+        $this->get_settings ();
1030
+
1031
+        # try to send
1032
+        try {
1033
+            # fetch mailer settings
1034
+            $mail_settings = $this->fetch_object("settingsMail", "id", 1);
1035
+
1036
+            # initialize mailer
1037
+            $phpipam_mail = new phpipam_mail($this->settings, $mail_settings);
1038
+
1039
+            # get all users and check who to end mail to
1040
+            $recipients = $this->ip_request_get_mail_recipients ($values['subnetId']);
1041
+
1042
+            # add requester to cc
1043
+            $recipients_requester = $values['requester'];
1044
+
1045
+            # reformat key / vaues
1046
+            $values = $this->ip_request_reformat_mail_values ($values);
1047
+            #reformat empty
1048
+            $values = $this->reformat_empty_array_fields ($values, "/");
1049
+
1050
+            # generate content
1051
+            if ($action=="new")			{ $subject	= "New IP address request"; }
1052
+            elseif ($action=="accept")	{ $subject	= "IP address request accepted"; }
1053
+            elseif ($action=="reject")	{ $subject	= "IP address request rejected"; }
1054
+            else						{ $this->Result->show("danger", _("Invalid request action"), true); }
1055
+
1056
+            // set html content
1057
+            $content[] = "<table style='margin-left:10px;margin-top:20px;width:auto;padding:0px;border-collapse:collapse;'>";
1058
+            $content[] = "<tr><td colspan='2' style='margin:0px;>$this->mail_font_style <strong>$subject</strong></font></td></tr>";
1059
+            foreach($values as $k=>$v) {
1060
+            // title search
1061
+            if (preg_match("/s_title_/", $k)) {
1062
+            $content[] = "<tr><td colspan='2' style='margin:0px;border-bottom:1px solid #eeeeee;'>$this->mail_font_style<strong>$v</strong></font></td></tr>";
1063
+            }
1064
+            else {
1065
+            //content
1066
+            $content[] = "<tr>";
1067
+            $content[] = "<td style='padding-left:15px;margin:0px;'>$this->mail_font_style $k</font></td>";
1068
+            $content[] = "<td style='padding-left:15px;margin:0px;'>$this->mail_font_style $v</font></td>";
1069
+            $content[] = "</tr>";
1070
+            }
1071
+            }
1072
+            $content[] = "<tr><td style='padding-top:15px;padding-bottom:3px;text-align:right;color:#ccc;'>$this->mail_font_style Sent at ".date('Y/m/d H:i')."</font></td></tr>";
1073
+            //set alt content
1074
+            $content_plain[] = "$subject"."\r\n------------------------------\r\n";
1075
+            foreach($values as $k=>$v) {
1076
+            $content_plain[] = $k." => ".$v;
1077
+            }
1078
+            $content_plain[] = "\r\n\r\nSent at ".date('Y/m/d H:i');
1079
+            $content[] = "</table>";
1080
+
1081
+            // set content
1082
+            $content 		= $phpipam_mail->generate_message (implode("\r\n", $content));
1083
+            $content_plain 	= implode("\r\n",$content_plain);
1084
+
1085
+            $phpipam_mail->Php_mailer->setFrom($mail_settings->mAdminMail, $mail_settings->mAdminName);
1086
+            if ($recipients!==false) {
1087
+            foreach($recipients as $r) {
1088
+            $phpipam_mail->Php_mailer->addAddress(addslashes(trim($r->email)));
1089
+            }
1090
+            $phpipam_mail->Php_mailer->AddCC(addslashes(trim($recipients_requester)));
1091
+            }
1092
+            else {
1093
+            $phpipam_mail->Php_mailer->addAddress(addslashes(trim($recipients_requester)));
1094
+            }
1095
+            $phpipam_mail->Php_mailer->Subject = $subject;
1096
+            $phpipam_mail->Php_mailer->msgHTML($content);
1097
+            $phpipam_mail->Php_mailer->AltBody = $content_plain;
1098
+            //send
1099
+            $phpipam_mail->Php_mailer->send();
1100
+        } catch (phpmailerException $e) {
1101
+            $this->Result->show("danger", "Mailer Error: ".$e->errorMessage(), true);
1102
+        } catch (Exception $e) {
1103
+            $this->Result->show("danger", "Mailer Error: ".$e->getMessage(), true);
1104
+        }
1105
+
1106
+        # ok
1107
+        return true;
1108
+
1109
+    }
1110
+
1111
+    /**
1112
+     * Returns list of recipients to get new
1113
+     *
1114
+     * @access private
1115
+     * @param bool|mixed $subnetId
1116
+     * @return array|bool
1117
+     */
1118
+    private function ip_request_get_mail_recipients ($subnetId = false) {
1119
+        // fetch all users with mailNotify
1120
+        $notification_users = $this->fetch_multiple_objects ("users", "mailNotify", "Yes", "id", true);
1121
+        // recipients array
1122
+        $recipients = array();
1123
+        // any ?
1124
+        if ($notification_users!==false) {
1125
+                // if subnetId is set check who has permissions
1126
+            if (isset($subnetId)) {
1127
+                    foreach ($notification_users as $u) {
1128
+                    // inti object
1129
+                    $Subnets = new Subnets ($this->Database);
1130
+                    //check permissions
1131
+                    $subnet_permission = $Subnets->check_permission($u, $subnetId);
1132
+                    // if 3 than add
1133
+                    if ($subnet_permission==3) {
1134
+                        $recipients[] = $u;
1135
+                    }
1136
+                }
1137
+            }
1138
+            else {
1139
+                foreach ($notification_users as $u) {
1140
+                    if($u->role=="Administrator") {
1141
+                        $recipients[] = $u;
1142
+                    }
1143
+                }
1144
+            }
1145
+            return sizeof($recipients)>0 ? $recipients : false;
1146
+        }
1147
+        else {
1148
+            return false;
1149
+        }
1150
+    }
1151
+
1152
+    /**
1153
+     * Reformats request value/key pairs for request mailing
1154
+     *
1155
+     * @access private
1156
+     * @param mixed $values
1157
+     * @return array
1158
+     */
1159
+    private function ip_request_reformat_mail_values ($values) {
1160
+        // no array
1161
+        if (!is_array($values)) { return $values; }
1162
+
1163
+        // addresses
1164
+        $this->Addresses = new Addresses ($this->Database);
1165
+
1166
+        $mail = array();
1167
+
1168
+        // change fields for mailings
1169
+        foreach ($values as $k=>$v) {
1170
+            // subnetId
1171
+            if ($k=="subnetId")	{
1172
+                // add title
1173
+                $mail["s_title_1"] = "<br>Subnet details";
1174
+
1175
+                $subnet = $this->fetch_object("subnets", "id", $v);
1176
+                $mail["Subnet"]  = $this->transform_address ($subnet->subnet, "dotted")."/".$subnet->mask;
1177
+                $mail["Subnet"] .= strlen($subnet->description)>0 ? " - ".$subnet->description : "";
1178
+            }
1179
+            // ip_addr
1180
+            elseif ($k=="ip_addr") {
1181
+                // add title
1182
+                $mail["s_title_2"] = "<br>Address details";
1183
+
1184
+                if (strlen($v)>0) {
1185
+                    $mail['IP address'] = $this->transform_address($v, "dotted");
1186
+                } else {
1187
+                    $mail['IP address'] = "Automatic";
1188
+                }
1189
+            }
1190
+            // state
1191
+            elseif ($k=="state") {
1192
+                $mail['State'] = $this->Addresses-> address_type_index_to_type ($v);
1193
+            }
1194
+            // description
1195
+            elseif ($k=="descriotion") {
1196
+                $mail['Description'] = $v;
1197
+            }
1198
+            // hostname
1199
+            elseif ($k=="hostname") {
1200
+                $mail['Hostname'] = $v;
1201
+            }
1202
+            // owner
1203
+            elseif ($k=="owner") {
1204
+                $mail['Address owner'] = $v;
1205
+            }
1206
+            // requester
1207
+            elseif ($k=="requester") {
1208
+                $mail['Requested by'] = $v;
1209
+            }
1210
+            // comment
1211
+            elseif ($k=="comment") {
1212
+                $mail['Request comment'] = $v;
1213
+            }
1214
+            // admin comment
1215
+            elseif ($k=="adminComment") {
1216
+                // add title
1217
+                $mail["s_title_3"] = "<br>Admin comment";
1218
+
1219
+                $mail['Admin comment'] = $v;
1220
+            }
1221
+            // admin comment
1222
+            elseif ($k=="gateway") {
1223
+                $mail['Gateway'] = $v;
1224
+            }
1225
+            // nameservers
1226
+            elseif ($k=="dns") {
1227
+                if (strlen($v)>0) {
1228
+                $mail['DNS servers'] = $v;
1229
+                }
1230
+            }
1231
+            // vlans
1232
+            elseif ($k=="vlan") {
1233
+                if (strlen($v)>0) {
1234
+                $mail['VLAN'] = $v;
1235
+                }
1236
+            }
1237
+        }
1238
+        // response
1239
+        return $mail;
1240
+    }
1241
+
1242
+
1243
+
1244
+
1245
+
1246
+
1247
+
1248
+
1249
+
1250
+
1251
+
1252
+
1253
+    /**
1254
+     *	@database verification methods
1255
+     *	------------------------------
1256
+     */
1257
+
1258
+    /**
1259
+     * Checks if all database fields are installed ok
1260
+     *
1261
+     * @access public
1262
+     * @return array
1263
+     */
1264
+    public function verify_database () {
1265
+
1266
+        # required tables from SCHEMA.sql
1267
+        $tables = $this->fetch_standard_tables();
1268
+
1269
+        # fetch required fields
1270
+        foreach($tables as $t) {
1271
+            $fields[$t] = $this->fetch_standard_fields ($t);
1272
+        }
1273
+
1274
+        /**
1275
+         * check that each database exist - if it does check also fields
1276
+         *		2 errors -> $tableError, $fieldError[table] = field
1277
+         ****************************************************************/
1278
+        foreach($tables as $table) {
1279
+
1280
+            //check if table exists
1281
+            if(!$this->table_exists($table)) {
1282
+                $error['tableError'][] = $table;
1283
+            }
1284
+            //check for each field
1285
+            else {
1286
+                foreach($fields[$table] as $field) {
1287
+                    //if it doesnt exist store error
1288
+                    if(!$this->field_exists($table, $field)) {
1289
+                        $error['fieldError'][$table][] = $field;
1290
+                    }
1291
+                }
1292
+            }
1293
+        }
1294
+
1295
+        # return array
1296
+        if(isset($error)) {
1297
+            return $error;
1298
+        } else 	{
1299
+            # update check field
1300
+            $this->update_db_verify_field ();
1301
+            # return empty array
1302
+            return array();
1303
+        }
1304
+    }
1305
+
1306
+    /**
1307
+     * Checks if specified table exists in database
1308
+     *
1309
+     *	true = exists
1310
+     *	false = doesnt exist
1311
+     *
1312
+     * @access public
1313
+     * @param mixed $tablename
1314
+     * @param bool $quit
1315
+     * @return bool
1316
+     */
1317
+    public function table_exists ($tablename, $quit = false) {
1318
+        # query
1319
+        $query = 'SELECT COUNT(*) AS count FROM information_schema.tables WHERE table_schema = "'.$this->Database->dbname.'" AND table_name = ?;';
1320
+        try { $count = $this->Database->getObjectQuery($query, array($tablename)); }
1321
+        catch (Exception $e) { !$quit ? : $this->Result->show("danger", $e->getMessage(), true);	return false; }
1322
+        # return
1323
+        return $count->count ==1 ? true : false;
1324
+    }
1325
+
1326
+    /**
1327
+     * Checks if specified field exists in table
1328
+     *
1329
+     *	true = exists
1330
+     *	false = doesnt exist
1331
+     *
1332
+     * @access public
1333
+     * @param mixed $fieldname
1334
+     * @return bool
1335
+     */
1336
+    public function field_exists ($tablename, $fieldname) {
1337
+        # escape
1338
+        $tablename = $this->Database->escape($tablename);
1339
+        # check
1340
+        $query = "DESCRIBE `$tablename` `$fieldname`;";
1341
+        try { $count = $this->Database->getObjectQuery($query); }
1342
+        catch (Exception $e) { $this->Result->show("danger", $e->getMessage(), true);	return false; }
1343
+        # return true if it exists
1344
+        return $count!== null ? true : false;
1345
+    }
1346
+
1347
+    /**
1348
+     * Updates DB check flag in database
1349
+     *
1350
+     * @access private
1351
+     */
1352
+    private function update_db_verify_field () {
1353
+        # query
1354
+        $query = "update `settings` set `dbverified`=1 where `id` = 1; ";
1355
+        try { $this->Database->runQuery($query); }
1356
+        catch (Exception $e) { !$this->debugging ? : $this->Result->show("danger", $e->getMessage(), false); }
1357
+    }
1358
+
1359
+    /**
1360
+     * Get fix for missing table.
1361
+     *
1362
+     * @access public
1363
+     * @param mixed $table
1364
+     * @return false|string
1365
+     */
1366
+    public function get_table_fix ($table) {
1367
+        $file = $this->read_db_schema();
1368
+
1369
+        //go from delimiter on
1370
+        $file = strstr($file, "DROP TABLE IF EXISTS `$table`;");
1371
+        $file = trim(strstr($file, "# Dump of table", true));
1372
+
1373
+        # check
1374
+        if(strpos($file, "DROP TABLE IF EXISTS `$table`;") > 0 )	return false;
1375
+        else														return $file;
1376
+    }
1377
+
1378
+    /**
1379
+     * Get fix for missing field.
1380
+     *
1381
+     * @access public
1382
+     * @param mixed $table
1383
+     * @param mixed $field
1384
+     * @return string|false
1385
+     */
1386
+    public function get_field_fix ($table, $field) {
1387
+        $file = $this->read_db_schema();
1388
+
1389
+        //go from delimiter on
1390
+        $file = strstr($file, "DROP TABLE IF EXISTS `$table`;");
1391
+        $file = trim(strstr($file, "# Dump of table", true));
1392
+
1393
+        //get proper line
1394
+        $file = explode("\n", $file);
1395
+        foreach($file as $k=>$l) {
1396
+            if(strpos(trim($l), "$field`")==1) {
1397
+                $res = trim($l, ",");
1398
+                $res .= ";";
1399
+
1400
+                return $res;
1401
+            }
1402
+        }
1403
+        return false;
1404
+    }
1405
+
1406
+    /**
1407
+     * Fix missing table - create
1408
+     *
1409
+     * @access public
1410
+     * @param mixed $table
1411
+     * @return bool
1412
+     */
1413
+    public function fix_table ($table) {
1414
+        # first fetch fix query
1415
+        $query = $this->get_table_fix($table);
1416
+        # fix
1417
+        try { $this->Database->runQuery($query); }
1418
+        catch (Exception $e) {
1419
+            $this->Result->show("danger", _("Update: ").$e->getMessage()."<br>query: ".$query, true);
1420
+            return false;
1421
+        }
1422
+        return true;
1423
+    }
1424
+
1425
+    /**
1426
+     * Fix missing field in table
1427
+     *
1428
+     * @access public
1429
+     * @param mixed $table
1430
+     * @param mixed $field
1431
+     * @return bool
1432
+     */
1433
+    public function fix_field ($table, $field) {
1434
+        # set fix query
1435
+        $query  = "alter table `$table` add ";
1436
+        $query .= trim($this->get_field_fix ($table, $field), ",");
1437
+        $query .= ";";
1438
+
1439
+        # fix
1440
+        try { $this->Database->runQuery($query); }
1441
+        catch (Exception $e) {
1442
+            $this->Result->show("danger", _("Update: ").$e->getMessage()."<br>query: ".$query, true);
1443
+            return false;
1444
+        }
1445
+        return true;
1446
+    }
1447
+
1448
+    /**
1449
+     * Verify that all required indexes are present in database
1450
+     *
1451
+     * @method verify_database_indexes
1452
+     * @return bool
1453
+     */
1454
+    public function verify_database_indexes () {
1455
+        // get indexes from schema
1456
+        $schema_indexes = $this->get_schema_indexes();
1457
+        // get existing indexes
1458
+        $missing = $this->get_missing_database_indexes($schema_indexes);
1459
+
1460
+        // if false all indexes are ok, otherwise fix
1461
+        if ($missing===false) {
1462
+            return true;
1463
+        }
1464
+        else {
1465
+            foreach ($missing as $table=>$index_id) {
1466
+                foreach ($index_id as $index_name) {
1467
+                    $this->fix_missing_index ($table, $index_name);
1468
+                }
1469
+            }
1470
+        }
1471
+        return false;
1472
+    }
1473
+
1474
+    /**
1475
+     * Get all indexes required for phpipam
1476
+     *
1477
+     * ignoring primary keys
1478
+     *
1479
+     * @method get_schema_indexes
1480
+     * @return array
1481
+     */
1482
+    private function get_schema_indexes () {
1483
+        // Discover indexes required for phpipam
1484
+        $schema = $this->read_db_schema();
1485
+
1486
+        # get definitions to array, explode with CREATE TABLE `
1487
+        $creates = explode("CREATE TABLE `", $schema);
1488
+
1489
+        $indexes = array ();
1490
+        foreach($creates as $k=>$c) {
1491
+            if($k == 0) continue;
1492
+            $c = trim(strstr($c, ";" . "\n", true));
1493
+
1494
+            $table = strstr($c, "`", true);
1495
+
1496
+            $definitions = explode("\n", $c);
1497
+            foreach($definitions as $definition) {
1498
+                if (preg_match('/(KEY|UNIQUE KEY) +`(.*)` +\(/', $definition, $matches)) {
1499
+                    $indexes[$table][] = $matches[2];
1500
+                }
1501
+            }
1502
+        }
1503
+        return $indexes;
1504
+    }
1505
+
1506
+    /**
1507
+     * Using required database indexes remove all that are existing and return array of missing indexes
1508
+     *
1509
+     * @method get_missing_database_indexes
1510
+     * @param array $schema_indexes
1511
+     * @return array|null
1512
+     */
1513
+    private function get_missing_database_indexes ($schema_indexes) {
1514
+        // loop
1515
+        foreach ($schema_indexes as $table=>$index) {
1516
+            try { $indexes = $this->Database->getObjectsQuery("SHOW INDEX from `$table` where `Key_name` != 'PRIMARY';"); }
1517
+            catch (Exception $e) {
1518
+                $this->Result->show("danger", _("Invalid query for `$table` database index check : ").$e->getMessage(), true);
1519
+            }
1520
+            // remove existing
1521
+            if ($indexes!==false) {
1522
+                foreach ($indexes as $i) {
1523
+                    // remove indexes
1524
+                    if(($key = array_search($i->Key_name, $schema_indexes[$table])) !== false) {
1525
+                        unset($schema_indexes[$table][$key]);
1526
+                    }
1527
+                }
1528
+            }
1529
+            // remove also empty table
1530
+            if(sizeof($schema_indexes[$table])==0) {
1531
+                unset($schema_indexes[$table]);
1532
+            }
1533
+        }
1534
+        // return diff
1535
+        return sizeof($schema_indexes)==0 ? false : $schema_indexes;
1536
+    }
1537
+
1538
+    /**
1539
+     * Fix missing indexes
1540
+     *
1541
+     * @method fix_missing_index
1542
+     * @param  string $table
1543
+     * @param  string $index_name
1544
+     * @return void
1545
+     */
1546
+    private function fix_missing_index ($table, $index_name) {
1547
+        // get definition
1548
+        $file = $this->read_db_schema();
1549
+
1550
+        //go from delimiter on
1551
+        $file = strstr($file, "DROP TABLE IF EXISTS `$table`;");
1552
+        $file = trim(strstr($file, "# Dump of table", true));
1553
+
1554
+        //get proper line
1555
+        $file = explode("\n", $file);
1556
+
1557
+        $line = false;
1558
+        foreach($file as $k=>$l) {
1559
+            // trim
1560
+            $l = trim($l);
1561
+            if(strpos($l, "KEY `".$index_name."`")!==false) {
1562
+                // remove last ,
1563
+                if(substr($l, -1)==",") {
1564
+                    $l = substr($l, 0, -1);
1565
+                }
1566
+                // set query and run
1567
+                $query = "ALTER TABLE `$table` ADD ".$l;
1568
+
1569
+                try { $this->Database->runQuery($query); }
1570
+                catch (Exception $e) {
1571
+                    $this->Result->show("danger", _("Creating index failed: ").$e->getMessage()."<br><pre>".$query."</pre>", true);
1572
+                    return false;
1573
+                }
1574
+                // add warning that index was created
1575
+                $this->Result->show("warning", _("Created index for table `$table` named `$index_name`."), false);
1576
+            }
1577
+        }
1578
+    }
1579
+
1580
+
1581
+
1582
+
1583
+
1584
+
1585
+
1586
+
1587
+
1588
+
1589
+
1590
+    /**
1591
+     *	@version check methods
1592
+     *	------------------------------
1593
+     */
1594
+
1595
+    /**
1596
+     * Check for latest version on gitHub
1597
+     *
1598
+     * @access public
1599
+     * @param bool $print_error (default: false)
1600
+     * @return string|bool
1601
+     */
1602
+    public function check_latest_phpipam_version ($print_error = false) {
1603
+        # fetch settings
1604
+        $this->get_settings ();
1605
+        # check for release
1606
+        # try to fetch
1607
+        $release_gh = @file('https://github.com/phpipam/phpipam/releases.atom');
1608
+        # check
1609
+        if ($release_gh===false) {
1610
+            if($print_error) {
1611
+                $this->Result->show("danger", "Cannot fetch https://github.com/phpipam/phpipam/releases.atom", false);
1612
+            }
1613
+            return false;
1614
+        }
1615
+        # set releases href
1616
+        $feed = implode($release_gh);
1617
+        // fetch
1618
+        $xml = simplexml_load_string($feed);
1619
+
1620
+        // if ok
1621
+        if ($xml!==false) {
1622
+            // encode to json
1623
+            $json = json_decode(json_encode($xml));
1624
+            // save all releases
1625
+            $this->phpipam_releases = $json->entry;
1626
+            // check for latest release
1627
+            foreach ($json->entry as $e) {
1628
+                // releases will be named with numberic values
1629
+                if (is_numeric(str_replace(array("Version", "."), "", $e->title))) {
1630
+                    // save
1631
+                    $this->phpipam_latest_release = $e;
1632
+                    // return
1633
+                    return str_replace("Version", "", $e->title);
1634
+                }
1635
+            }
1636
+            // none
1637
+            return false;
1146 1638
         }
1147 1639
         else {
1148 1640
             return false;
1149 1641
         }
1150
-	}
1151
-
1152
-	/**
1153
-	 * Reformats request value/key pairs for request mailing
1154
-	 *
1155
-	 * @access private
1156
-	 * @param mixed $values
1157
-	 * @return array
1158
-	 */
1159
-	private function ip_request_reformat_mail_values ($values) {
1160
-		// no array
1161
-		if (!is_array($values)) { return $values; }
1162
-
1163
-		// addresses
1164
-		$this->Addresses = new Addresses ($this->Database);
1165
-
1166
-		$mail = array();
1167
-
1168
-		// change fields for mailings
1169
-		foreach ($values as $k=>$v) {
1170
-			// subnetId
1171
-			if ($k=="subnetId")	{
1172
-				// add title
1173
-				$mail["s_title_1"] = "<br>Subnet details";
1174
-
1175
-				$subnet = $this->fetch_object("subnets", "id", $v);
1176
-				$mail["Subnet"]  = $this->transform_address ($subnet->subnet, "dotted")."/".$subnet->mask;
1177
-				$mail["Subnet"] .= strlen($subnet->description)>0 ? " - ".$subnet->description : "";
1178
-			}
1179
-			// ip_addr
1180
-			elseif ($k=="ip_addr") {
1181
-				// add title
1182
-				$mail["s_title_2"] = "<br>Address details";
1183
-
1184
-				if (strlen($v)>0) {
1185
-					$mail['IP address'] = $this->transform_address($v, "dotted");
1186
-				} else {
1187
-					$mail['IP address'] = "Automatic";
1188
-				}
1189
-			}
1190
-			// state
1191
-			elseif ($k=="state") {
1192
-				$mail['State'] = $this->Addresses-> address_type_index_to_type ($v);
1193
-			}
1194
-			// description
1195
-			elseif ($k=="descriotion") {
1196
-				$mail['Description'] = $v;
1197
-			}
1198
-			// hostname
1199
-			elseif ($k=="hostname") {
1200
-				$mail['Hostname'] = $v;
1201
-			}
1202
-			// owner
1203
-			elseif ($k=="owner") {
1204
-				$mail['Address owner'] = $v;
1205
-			}
1206
-			// requester
1207
-			elseif ($k=="requester") {
1208
-				$mail['Requested by'] = $v;
1209
-			}
1210
-			// comment
1211
-			elseif ($k=="comment") {
1212
-				$mail['Request comment'] = $v;
1213
-			}
1214
-			// admin comment
1215
-			elseif ($k=="adminComment") {
1216
-				// add title
1217
-				$mail["s_title_3"] = "<br>Admin comment";
1218
-
1219
-				$mail['Admin comment'] = $v;
1220
-			}
1221
-			// admin comment
1222
-			elseif ($k=="gateway") {
1223
-				$mail['Gateway'] = $v;
1224
-			}
1225
-			// nameservers
1226
-			elseif ($k=="dns") {
1227
-				if (strlen($v)>0) {
1228
-				$mail['DNS servers'] = $v;
1229
-				}
1230
-			}
1231
-			// vlans
1232
-			elseif ($k=="vlan") {
1233
-				if (strlen($v)>0) {
1234
-				$mail['VLAN'] = $v;
1235
-				}
1236
-			}
1237
-		}
1238
-		// response
1239
-		return $mail;
1240
-	}
1241
-
1242
-
1243
-
1244
-
1245
-
1246
-
1247
-
1248
-
1249
-
1250
-
1251
-
1252
-
1253
-	/**
1254
-	 *	@database verification methods
1255
-	 *	------------------------------
1256
-	 */
1257
-
1258
-	/**
1259
-	 * Checks if all database fields are installed ok
1260
-	 *
1261
-	 * @access public
1262
-	 * @return array
1263
-	 */
1264
-	public function verify_database () {
1265
-
1266
-		# required tables from SCHEMA.sql
1267
-		$tables = $this->fetch_standard_tables();
1268
-
1269
-		# fetch required fields
1270
-		foreach($tables as $t) {
1271
-			$fields[$t] = $this->fetch_standard_fields ($t);
1272
-		}
1273
-
1274
-		/**
1275
-		 * check that each database exist - if it does check also fields
1276
-		 *		2 errors -> $tableError, $fieldError[table] = field
1277
-		 ****************************************************************/
1278
-		foreach($tables as $table) {
1279
-
1280
-			//check if table exists
1281
-			if(!$this->table_exists($table)) {
1282
-				$error['tableError'][] = $table;
1283
-			}
1284
-			//check for each field
1285
-			else {
1286
-				foreach($fields[$table] as $field) {
1287
-					//if it doesnt exist store error
1288
-					if(!$this->field_exists($table, $field)) {
1289
-						$error['fieldError'][$table][] = $field;
1290
-					}
1291
-				}
1292
-			}
1293
-		}
1294
-
1295
-		# return array
1296
-		if(isset($error)) {
1297
-			return $error;
1298
-		} else 	{
1299
-			# update check field
1300
-			$this->update_db_verify_field ();
1301
-			# return empty array
1302
-			return array();
1303
-		}
1304
-	}
1305
-
1306
-	/**
1307
-	 * Checks if specified table exists in database
1308
-	 *
1309
-	 *	true = exists
1310
-	 *	false = doesnt exist
1311
-	 *
1312
-	 * @access public
1313
-	 * @param mixed $tablename
1314
-	 * @param bool $quit
1315
-	 * @return bool
1316
-	 */
1317
-	public function table_exists ($tablename, $quit = false) {
1318
-	    # query
1319
-	    $query = 'SELECT COUNT(*) AS count FROM information_schema.tables WHERE table_schema = "'.$this->Database->dbname.'" AND table_name = ?;';
1320
-		try { $count = $this->Database->getObjectQuery($query, array($tablename)); }
1321
-		catch (Exception $e) { !$quit ? : $this->Result->show("danger", $e->getMessage(), true);	return false; }
1322
-		# return
1323
-		return $count->count ==1 ? true : false;
1324
-	}
1325
-
1326
-	/**
1327
-	 * Checks if specified field exists in table
1328
-	 *
1329
-	 *	true = exists
1330
-	 *	false = doesnt exist
1331
-	 *
1332
-	 * @access public
1333
-	 * @param mixed $fieldname
1334
-	 * @return bool
1335
-	 */
1336
-	public function field_exists ($tablename, $fieldname) {
1337
-	    # escape
1338
-	    $tablename = $this->Database->escape($tablename);
1339
-		# check
1340
-	    $query = "DESCRIBE `$tablename` `$fieldname`;";
1341
-		try { $count = $this->Database->getObjectQuery($query); }
1342
-		catch (Exception $e) { $this->Result->show("danger", $e->getMessage(), true);	return false; }
1343
-		# return true if it exists
1344
-		return $count!== null ? true : false;
1345
-	}
1346
-
1347
-	/**
1348
-	 * Updates DB check flag in database
1349
-	 *
1350
-	 * @access private
1351
-	 */
1352
-	private function update_db_verify_field () {
1353
-		# query
1354
-		$query = "update `settings` set `dbverified`=1 where `id` = 1; ";
1355
-		try { $this->Database->runQuery($query); }
1356
-		catch (Exception $e) { !$this->debugging ? : $this->Result->show("danger", $e->getMessage(), false); }
1357
-	}
1358
-
1359
-	/**
1360
-	 * Get fix for missing table.
1361
-	 *
1362
-	 * @access public
1363
-	 * @param mixed $table
1364
-	 * @return false|string
1365
-	 */
1366
-	public function get_table_fix ($table) {
1367
-		$file = $this->read_db_schema();
1368
-
1369
-		//go from delimiter on
1370
-		$file = strstr($file, "DROP TABLE IF EXISTS `$table`;");
1371
-		$file = trim(strstr($file, "# Dump of table", true));
1372
-
1373
-		# check
1374
-		if(strpos($file, "DROP TABLE IF EXISTS `$table`;") > 0 )	return false;
1375
-		else														return $file;
1376
-	}
1377
-
1378
-	/**
1379
-	 * Get fix for missing field.
1380
-	 *
1381
-	 * @access public
1382
-	 * @param mixed $table
1383
-	 * @param mixed $field
1384
-	 * @return string|false
1385
-	 */
1386
-	public function get_field_fix ($table, $field) {
1387
-		$file = $this->read_db_schema();
1388
-
1389
-		//go from delimiter on
1390
-		$file = strstr($file, "DROP TABLE IF EXISTS `$table`;");
1391
-		$file = trim(strstr($file, "# Dump of table", true));
1392
-
1393
-		//get proper line
1394
-		$file = explode("\n", $file);
1395
-		foreach($file as $k=>$l) {
1396
-			if(strpos(trim($l), "$field`")==1) {
1397
-				$res = trim($l, ",");
1398
-				$res .= ";";
1399
-
1400
-				return $res;
1401
-			}
1402
-		}
1403
-		return false;
1404
-	}
1405
-
1406
-	/**
1407
-	 * Fix missing table - create
1408
-	 *
1409
-	 * @access public
1410
-	 * @param mixed $table
1411
-	 * @return bool
1412
-	 */
1413
-	public function fix_table ($table) {
1414
-		# first fetch fix query
1415
-		$query = $this->get_table_fix($table);
1416
-		# fix
1417
-		try { $this->Database->runQuery($query); }
1418
-		catch (Exception $e) {
1419
-			$this->Result->show("danger", _("Update: ").$e->getMessage()."<br>query: ".$query, true);
1420
-			return false;
1421
-		}
1422
-		return true;
1423
-	}
1424
-
1425
-	/**
1426
-	 * Fix missing field in table
1427
-	 *
1428
-	 * @access public
1429
-	 * @param mixed $table
1430
-	 * @param mixed $field
1431
-	 * @return bool
1432
-	 */
1433
-	public function fix_field ($table, $field) {
1434
-		# set fix query
1435
-		$query  = "alter table `$table` add ";
1436
-		$query .= trim($this->get_field_fix ($table, $field), ",");
1437
-		$query .= ";";
1438
-
1439
-		# fix
1440
-		try { $this->Database->runQuery($query); }
1441
-		catch (Exception $e) {
1442
-			$this->Result->show("danger", _("Update: ").$e->getMessage()."<br>query: ".$query, true);
1443
-			return false;
1444
-		}
1445
-		return true;
1446
-	}
1447
-
1448
-	/**
1449
-	 * Verify that all required indexes are present in database
1450
-	 *
1451
-	 * @method verify_database_indexes
1452
-	 * @return bool
1453
-	 */
1454
-	public function verify_database_indexes () {
1455
-		// get indexes from schema
1456
-		$schema_indexes = $this->get_schema_indexes();
1457
-		// get existing indexes
1458
-		$missing = $this->get_missing_database_indexes($schema_indexes);
1459
-
1460
-		// if false all indexes are ok, otherwise fix
1461
-		if ($missing===false) {
1462
-			return true;
1463
-		}
1464
-		else {
1465
-			foreach ($missing as $table=>$index_id) {
1466
-				foreach ($index_id as $index_name) {
1467
-					$this->fix_missing_index ($table, $index_name);
1468
-				}
1469
-			}
1470
-		}
1471
-		return false;
1472
-	}
1473
-
1474
-	/**
1475
-	 * Get all indexes required for phpipam
1476
-	 *
1477
-	 * ignoring primary keys
1478
-	 *
1479
-	 * @method get_schema_indexes
1480
-	 * @return array
1481
-	 */
1482
-	private function get_schema_indexes () {
1483
-		// Discover indexes required for phpipam
1484
-		$schema = $this->read_db_schema();
1485
-
1486
-		# get definitions to array, explode with CREATE TABLE `
1487
-		$creates = explode("CREATE TABLE `", $schema);
1488
-
1489
-		$indexes = array ();
1490
-		foreach($creates as $k=>$c) {
1491
-			if($k == 0) continue;
1492
-			$c = trim(strstr($c, ";" . "\n", true));
1493
-
1494
-			$table = strstr($c, "`", true);
1495
-
1496
-			$definitions = explode("\n", $c);
1497
-			foreach($definitions as $definition) {
1498
-				if (preg_match('/(KEY|UNIQUE KEY) +`(.*)` +\(/', $definition, $matches)) {
1499
-					$indexes[$table][] = $matches[2];
1500
-				}
1501
-			}
1502
-		}
1503
-		return $indexes;
1504
-	}
1505
-
1506
-	/**
1507
-	 * Using required database indexes remove all that are existing and return array of missing indexes
1508
-	 *
1509
-	 * @method get_missing_database_indexes
1510
-	 * @param array $schema_indexes
1511
-	 * @return array|null
1512
-	 */
1513
-	private function get_missing_database_indexes ($schema_indexes) {
1514
-		// loop
1515
-		foreach ($schema_indexes as $table=>$index) {
1516
-			try { $indexes = $this->Database->getObjectsQuery("SHOW INDEX from `$table` where `Key_name` != 'PRIMARY';"); }
1517
-			catch (Exception $e) {
1518
-				$this->Result->show("danger", _("Invalid query for `$table` database index check : ").$e->getMessage(), true);
1519
-			}
1520
-			// remove existing
1521
-			if ($indexes!==false) {
1522
-				foreach ($indexes as $i) {
1523
-					// remove indexes
1524
-					if(($key = array_search($i->Key_name, $schema_indexes[$table])) !== false) {
1525
-						unset($schema_indexes[$table][$key]);
1526
-					}
1527
-				}
1528
-			}
1529
-			// remove also empty table
1530
-			if(sizeof($schema_indexes[$table])==0) {
1531
-				unset($schema_indexes[$table]);
1532
-			}
1533
-		}
1534
-		// return diff
1535
-		return sizeof($schema_indexes)==0 ? false : $schema_indexes;
1536
-	}
1537
-
1538
-	/**
1539
-	 * Fix missing indexes
1540
-	 *
1541
-	 * @method fix_missing_index
1542
-	 * @param  string $table
1543
-	 * @param  string $index_name
1544
-	 * @return void
1545
-	 */
1546
-	private function fix_missing_index ($table, $index_name) {
1547
-		// get definition
1548
-		$file = $this->read_db_schema();
1549
-
1550
-		//go from delimiter on
1551
-		$file = strstr($file, "DROP TABLE IF EXISTS `$table`;");
1552
-		$file = trim(strstr($file, "# Dump of table", true));
1553
-
1554
-		//get proper line
1555
-		$file = explode("\n", $file);
1556
-
1557
-		$line = false;
1558
-		foreach($file as $k=>$l) {
1559
-			// trim
1560
-			$l = trim($l);
1561
-			if(strpos($l, "KEY `".$index_name."`")!==false) {
1562
-				// remove last ,
1563
-				if(substr($l, -1)==",") {
1564
-					$l = substr($l, 0, -1);
1565
-				}
1566
-				// set query and run
1567
-				$query = "ALTER TABLE `$table` ADD ".$l;
1568
-
1569
-				try { $this->Database->runQuery($query); }
1570
-				catch (Exception $e) {
1571
-					$this->Result->show("danger", _("Creating index failed: ").$e->getMessage()."<br><pre>".$query."</pre>", true);
1572
-					return false;
1573
-				}
1574
-				// add warning that index was created
1575
-				$this->Result->show("warning", _("Created index for table `$table` named `$index_name`."), false);
1576
-			}
1577
-		}
1578
-	}
1579
-
1580
-
1581
-
1582
-
1583
-
1584
-
1585
-
1586
-
1587
-
1588
-
1589
-
1590
-	/**
1591
-	 *	@version check methods
1592
-	 *	------------------------------
1593
-	 */
1594
-
1595
-	/**
1596
-	 * Check for latest version on gitHub
1597
-	 *
1598
-	 * @access public
1599
-	 * @param bool $print_error (default: false)
1600
-	 * @return string|bool
1601
-	 */
1602
-	public function check_latest_phpipam_version ($print_error = false) {
1603
-		# fetch settings
1604
-		$this->get_settings ();
1605
-		# check for release
1606
-    	# try to fetch
1607
-    	$release_gh = @file('https://github.com/phpipam/phpipam/releases.atom');
1608
-    	# check
1609
-    	if ($release_gh===false) {
1610
-        	if($print_error) {
1611
-            	$this->Result->show("danger", "Cannot fetch https://github.com/phpipam/phpipam/releases.atom", false);
1612
-            }
1613
-        	return false;
1614
-    	}
1615
-		# set releases href
1616
-		$feed = implode($release_gh);
1617
-		// fetch
1618
-		$xml = simplexml_load_string($feed);
1619
-
1620
-		// if ok
1621
-		if ($xml!==false) {
1622
-			// encode to json
1623
-			$json = json_decode(json_encode($xml));
1624
-			// save all releases
1625
-			$this->phpipam_releases = $json->entry;
1626
-			// check for latest release
1627
-			foreach ($json->entry as $e) {
1628
-				// releases will be named with numberic values
1629
-				if (is_numeric(str_replace(array("Version", "."), "", $e->title))) {
1630
-					// save
1631
-					$this->phpipam_latest_release = $e;
1632
-					// return
1633
-					return str_replace("Version", "", $e->title);
1634
-				}
1635
-			}
1636
-			// none
1637
-			return false;
1638
-		}
1639
-		else {
1640
-			return false;
1641
-		}
1642
-	}
1643
-
1644
-	/**
1645
-	 * Updates DB version check flag in database
1646
-	 *
1647
-	 * @access public
1648
-	 */
1649
-	public function update_phpipam_checktime () {
1650
-		# query
1651
-		$query = "update `settings` set `vcheckDate`='".date("Y-m-d H:i:s")."';";
1652
-		try { $this->Database->runQuery($query); }
1653
-		catch (Exception $e) { !$this->debugging ? : $this->Result->show("danger", $e->getMessage(), false); }
1654
-	}
1655
-
1656
-
1657
-
1658
-
1659
-
1660
-
1661
-
1662
-
1663
-
1664
-	/**
1665
-	 * @ipcalc @calculator methods
1666
-	 * ------------------------------
1667
-	 */
1668
-
1669
-	/**
1670
-	 * Calculates IP calculator result per IP type
1671
-	 *
1672
-	 * @access public
1673
-	 * @param mixed $cidr
1674
-	 * @return mixed
1675
-	 */
1676
-	public function calculate_ip_calc_results ($cidr) {
1677
-		# detect address and calculate
1678
-		return $this->identify_address($cidr)=="IPv6" ? $this->calculate_IPv6_calc_results($cidr) : $this->calculate_IPv4_calc_results($cidr);
1679
-	}
1680
-
1681
-	/**
1682
-	 * Calculates IPv4 results from provided CIDR address
1683
-	 *
1684
-	 * @access private
1685
-	 * @param mixed $cidr
1686
-	 * @return array
1687
-	 */
1688
-	private function calculate_IPv4_calc_results ($cidr) {
1689
-		# initialize subnets Class
1690
-		$Subnets = new Subnets($this->Database);
1691
-		# Initialize PEAR NET object
1692
-		$this->initialize_pear_net_IPv4 ();
1693
-
1694
-		# parse address
1642
+    }
1643
+
1644
+    /**
1645
+     * Updates DB version check flag in database
1646
+     *
1647
+     * @access public
1648
+     */
1649
+    public function update_phpipam_checktime () {
1650
+        # query
1651
+        $query = "update `settings` set `vcheckDate`='".date("Y-m-d H:i:s")."';";
1652
+        try { $this->Database->runQuery($query); }
1653
+        catch (Exception $e) { !$this->debugging ? : $this->Result->show("danger", $e->getMessage(), false); }
1654
+    }
1655
+
1656
+
1657
+
1658
+
1659
+
1660
+
1661
+
1662
+
1663
+
1664
+    /**
1665
+     * @ipcalc @calculator methods
1666
+     * ------------------------------
1667
+     */
1668
+
1669
+    /**
1670
+     * Calculates IP calculator result per IP type
1671
+     *
1672
+     * @access public
1673
+     * @param mixed $cidr
1674
+     * @return mixed
1675
+     */
1676
+    public function calculate_ip_calc_results ($cidr) {
1677
+        # detect address and calculate
1678
+        return $this->identify_address($cidr)=="IPv6" ? $this->calculate_IPv6_calc_results($cidr) : $this->calculate_IPv4_calc_results($cidr);
1679
+    }
1680
+
1681
+    /**
1682
+     * Calculates IPv4 results from provided CIDR address
1683
+     *
1684
+     * @access private
1685
+     * @param mixed $cidr
1686
+     * @return array
1687
+     */
1688
+    private function calculate_IPv4_calc_results ($cidr) {
1689
+        # initialize subnets Class
1690
+        $Subnets = new Subnets($this->Database);
1691
+        # Initialize PEAR NET object
1692
+        $this->initialize_pear_net_IPv4 ();
1693
+
1694
+        # parse address
1695 1695
         $net = $this->Net_IPv4->parseAddress( $cidr );
1696 1696
 
1697 1697
         # set ip address type
@@ -1720,76 +1720,76 @@  discard block
 block discarded – undo
1720 1720
         }
1721 1721
         # /32 and /32 fixes
1722 1722
         if($net->bitmask==31 || $net->bitmask==32) {
1723
-			$out['Min host IP'] = $out['Network'];
1724
-			$out['Max host IP'] = $out['Broadcast'];
1725
-        }
1726
-		# result
1727
-		return $out;
1728
-	}
1729
-
1730
-	/**
1731
-	 * Returns IPv4 address type from cidr
1732
-	 *
1733
-	 * @access private
1734
-	 * @param $network
1735
-	 * @param $broadcast
1736
-	 * @return string|false
1737
-	 */
1738
-	private function get_ipv4_address_type ($network, $broadcast) {
1739
-		# get all possible classes
1740
-		$classes = $this->define_ipv4_address_types ();
1741
-		# Initialize PEAR NET object
1742
-		$this->initialize_pear_net_IPv4 ();
1743
-		# check for each if member
1744
-	    foreach( $classes as $key=>$class ) {
1745
-	        if ($this->Net_IPv4->ipInNetwork($network, $class)) {
1746
-	            if ($this->Net_IPv4->ipInNetwork($broadcast, $class)) {
1747
-	                return($key);
1748
-	            }
1749
-	        }
1750
-	    }
1751
-	    # no match
1752
-	    return false;
1753
-	}
1754
-
1755
-	/**
1756
-	 * Defines all possible IPv4 address types
1757
-	 *
1758
-	 * @access private
1759
-	 * @return array
1760
-	 */
1761
-	private function define_ipv4_address_types () {
1762
-	    # define classes
1763
-	    $classes = array();
1764
-	    $classes['private A']          = '10.0.0.0/8';
1765
-	    $classes['private B']          = '172.16.0.0/12';
1766
-	    $classes['private C']          = '192.168.0.0/16';
1767
-	    $classes['Loopback']           = '127.0.0.0/8';
1768
-	    $classes['Link-local']         = '169.254.0.0/16';
1769
-	    $classes['Reserved (IANA)']    = '192.0.0.0/24';
1770
-	    $classes['TEST-NET-1']         = '192.0.2.0/24';
1771
-	    $classes['IPv6 to IPv4 relay'] = '192.88.99.0/24';
1772
-	    $classes['Network benchmark']  = '198.18.0.0/15';
1773
-	    $classes['TEST-NET-2']         = '198.51.100.0/24';
1774
-	    $classes['TEST-NET-3']         = '203.0.113.0/24';
1775
-	    $classes['Multicast']          = '224.0.0.0/4';
1776
-	    $classes['Reserved']           = '240.0.0.0/4';
1777
-	    # result
1778
-	    return $classes;
1779
-	}
1780
-
1781
-	/**
1782
-	 * Calculates IPv6 from cidr
1783
-	 *
1784
-	 * @access private
1785
-	 * @param mixed $cidr
1786
-	 * @return array
1787
-	 */
1788
-	private function calculate_IPv6_calc_results ($cidr) {
1789
-		# initialize subnets Class
1790
-		$Subnets = new Subnets($this->Database);
1791
-		# Initialize PEAR NET object
1792
-		$this->initialize_pear_net_IPv6 ();
1723
+            $out['Min host IP'] = $out['Network'];
1724
+            $out['Max host IP'] = $out['Broadcast'];
1725
+        }
1726
+        # result
1727
+        return $out;
1728
+    }
1729
+
1730
+    /**
1731
+     * Returns IPv4 address type from cidr
1732
+     *
1733
+     * @access private
1734
+     * @param $network
1735
+     * @param $broadcast
1736
+     * @return string|false
1737
+     */
1738
+    private function get_ipv4_address_type ($network, $broadcast) {
1739
+        # get all possible classes
1740
+        $classes = $this->define_ipv4_address_types ();
1741
+        # Initialize PEAR NET object
1742
+        $this->initialize_pear_net_IPv4 ();
1743
+        # check for each if member
1744
+        foreach( $classes as $key=>$class ) {
1745
+            if ($this->Net_IPv4->ipInNetwork($network, $class)) {
1746
+                if ($this->Net_IPv4->ipInNetwork($broadcast, $class)) {
1747
+                    return($key);
1748
+                }
1749
+            }
1750
+        }
1751
+        # no match
1752
+        return false;
1753
+    }
1754
+
1755
+    /**
1756
+     * Defines all possible IPv4 address types
1757
+     *
1758
+     * @access private
1759
+     * @return array
1760
+     */
1761
+    private function define_ipv4_address_types () {
1762
+        # define classes
1763
+        $classes = array();
1764
+        $classes['private A']          = '10.0.0.0/8';
1765
+        $classes['private B']          = '172.16.0.0/12';
1766
+        $classes['private C']          = '192.168.0.0/16';
1767
+        $classes['Loopback']           = '127.0.0.0/8';
1768
+        $classes['Link-local']         = '169.254.0.0/16';
1769
+        $classes['Reserved (IANA)']    = '192.0.0.0/24';
1770
+        $classes['TEST-NET-1']         = '192.0.2.0/24';
1771
+        $classes['IPv6 to IPv4 relay'] = '192.88.99.0/24';
1772
+        $classes['Network benchmark']  = '198.18.0.0/15';
1773
+        $classes['TEST-NET-2']         = '198.51.100.0/24';
1774
+        $classes['TEST-NET-3']         = '203.0.113.0/24';
1775
+        $classes['Multicast']          = '224.0.0.0/4';
1776
+        $classes['Reserved']           = '240.0.0.0/4';
1777
+        # result
1778
+        return $classes;
1779
+    }
1780
+
1781
+    /**
1782
+     * Calculates IPv6 from cidr
1783
+     *
1784
+     * @access private
1785
+     * @param mixed $cidr
1786
+     * @return array
1787
+     */
1788
+    private function calculate_IPv6_calc_results ($cidr) {
1789
+        # initialize subnets Class
1790
+        $Subnets = new Subnets($this->Database);
1791
+        # Initialize PEAR NET object
1792
+        $this->initialize_pear_net_IPv6 ();
1793 1793
 
1794 1794
         # set ip address type
1795 1795
         $out = array();
@@ -1810,15 +1810,15 @@  discard block
 block discarded – undo
1810 1810
         $out['Subnet Reverse DNS'] = $this->reverse_IPv6($subnet, $mask);
1811 1811
 
1812 1812
         # if IP == subnet clear the Host fields and Host Reverse DNS
1813
-         if ($out['Host address'] == $out['Subnet prefix']) {
1814
-             $out['Host address']                = '/';
1815
-             $out['Host address (uncompressed)'] = '/';
1816
-             unset($out['Host Reverse DNS']);
1813
+            if ($out['Host address'] == $out['Subnet prefix']) {
1814
+                $out['Host address']                = '/';
1815
+                $out['Host address (uncompressed)'] = '/';
1816
+                unset($out['Host Reverse DNS']);
1817 1817
         }
1818 1818
 
1819 1819
         # /min / max hosts
1820 1820
         $maxIp = gmp_strval(gmp_add(gmp_pow(2, 128 - $mask),$this->ip2long6 ($subnet)));
1821
-		$maxIp = gmp_strval(gmp_sub($maxIp, 1));
1821
+        $maxIp = gmp_strval(gmp_sub($maxIp, 1));
1822 1822
 
1823 1823
         $out['Min host IP']               = $subnet;
1824 1824
         $out['Max host IP']               = $this->long2ip6 ($maxIp);
@@ -1826,63 +1826,63 @@  discard block
 block discarded – undo
1826 1826
 
1827 1827
         # set address type
1828 1828
         $out['Address type']              = $this->get_ipv6_address_type( $cidr );
1829
-		# result
1830
-		return $out;
1831
-	}
1832
-
1833
-	/**
1834
-	 * Calculate reverse DNS entry for IPv6 addresses
1835
-	 *
1836
-	 *	If a prefix length is given, generate only up to this length (ie. for zone definitions)
1837
-	 *
1838
-	 * @access public
1839
-	 * @param mixed $addresses
1840
-	 * @param int $pflen (default: 128)
1841
-	 * @return string
1842
-	 */
1843
-	public function reverse_IPv6 ($addresses, $pflen=128) {
1844
-		# Initialize PEAR NET object
1845
-		$this->initialize_pear_net_IPv6 ();
1846
-		//uncompress
1847
-	    $uncompressed = $this->Net_IPv6->removeNetmaskSpec($this->Net_IPv6->uncompress($addresses));
1848
-	    $len = $pflen / 4;
1849
-	    $parts = explode(':', $uncompressed);
1850
-	    $res = '';
1851
-	    foreach($parts as $part) {
1852
-	        $res .= str_pad($part, 4, '0', STR_PAD_LEFT);
1853
-	    }
1854
-	    $res = implode('.', str_split(strrev(substr($res, 0, $len)))) . '.ip6.arpa';
1855
-	    if ($pflen % 4 != 0) {
1856
-	        $res .= " "._("(closest parent)");
1857
-	    }
1858
-	    return $res;
1859
-	}
1860
-
1861
-	/**
1862
-	 * Returns IPv6 address type from cidr
1863
-	 *
1864
-	 * @access private
1865
-	 * @param CIDR $cidr
1866
-	 * @return string|false
1867
-	 */
1868
-	private function get_ipv6_address_type ($cidr) {
1869
-		# Initialize PEAR NET object
1870
-		$this->initialize_pear_net_IPv6 ();
1871
-		# get type in number
1872
-		$type = $this->Net_IPv6->getAddressType($cidr);
1873
-		# fetch types
1874
-		$all_types = $this->define_ipv6_address_types ();
1875
-		# translate
1876
-		return array_key_exists($type, $all_types) ? $all_types[$type] : false;
1877
-	}
1878
-
1879
-	/**
1880
-	 * Defines all IPv6 address types
1881
-	 *
1882
-	 * @access private
1883
-	 * @return string[]
1884
-	 */
1885
-	private function define_ipv6_address_types () {
1829
+        # result
1830
+        return $out;
1831
+    }
1832
+
1833
+    /**
1834
+     * Calculate reverse DNS entry for IPv6 addresses
1835
+     *
1836
+     *	If a prefix length is given, generate only up to this length (ie. for zone definitions)
1837
+     *
1838
+     * @access public
1839
+     * @param mixed $addresses
1840
+     * @param int $pflen (default: 128)
1841
+     * @return string
1842
+     */
1843
+    public function reverse_IPv6 ($addresses, $pflen=128) {
1844
+        # Initialize PEAR NET object
1845
+        $this->initialize_pear_net_IPv6 ();
1846
+        //uncompress
1847
+        $uncompressed = $this->Net_IPv6->removeNetmaskSpec($this->Net_IPv6->uncompress($addresses));
1848
+        $len = $pflen / 4;
1849
+        $parts = explode(':', $uncompressed);
1850
+        $res = '';
1851
+        foreach($parts as $part) {
1852
+            $res .= str_pad($part, 4, '0', STR_PAD_LEFT);
1853
+        }
1854
+        $res = implode('.', str_split(strrev(substr($res, 0, $len)))) . '.ip6.arpa';
1855
+        if ($pflen % 4 != 0) {
1856
+            $res .= " "._("(closest parent)");
1857
+        }
1858
+        return $res;
1859
+    }
1860
+
1861
+    /**
1862
+     * Returns IPv6 address type from cidr
1863
+     *
1864
+     * @access private
1865
+     * @param CIDR $cidr
1866
+     * @return string|false
1867
+     */
1868
+    private function get_ipv6_address_type ($cidr) {
1869
+        # Initialize PEAR NET object
1870
+        $this->initialize_pear_net_IPv6 ();
1871
+        # get type in number
1872
+        $type = $this->Net_IPv6->getAddressType($cidr);
1873
+        # fetch types
1874
+        $all_types = $this->define_ipv6_address_types ();
1875
+        # translate
1876
+        return array_key_exists($type, $all_types) ? $all_types[$type] : false;
1877
+    }
1878
+
1879
+    /**
1880
+     * Defines all IPv6 address types
1881
+     *
1882
+     * @access private
1883
+     * @return string[]
1884
+     */
1885
+    private function define_ipv6_address_types () {
1886 1886
         $all_types[10] = "NET_IPV6_NO_NETMASK";
1887 1887
         $all_types[1]  = "NET_IPV6";
1888 1888
         $all_types[11] = "NET_IPV6_RESERVED";
@@ -1897,9 +1897,9 @@  discard block
 block discarded – undo
1897 1897
         $all_types[51] = "NET_IPV6_UNSPECIFIED";
1898 1898
         $all_types[51] = "NET_IPV6_LOOPBACK";
1899 1899
         $all_types[51] = "NET_IPV6_UNKNOWN_TYPE";
1900
-		# response
1900
+        # response
1901 1901
         return $all_types;
1902
-	}
1902
+    }
1903 1903
 
1904 1904
 
1905 1905
 
@@ -1914,10 +1914,10 @@  discard block
 block discarded – undo
1914 1914
 
1915 1915
 
1916 1916
 
1917
-	/**
1918
-	 *	@nat methods
1919
-	 *	------------------------------
1920
-	 */
1917
+    /**
1918
+     *	@nat methods
1919
+     *	------------------------------
1920
+     */
1921 1921
 
1922 1922
     /**
1923 1923
      * Translates NAT objects to be shown on page
@@ -2155,12 +2155,12 @@  discard block
 block discarded – undo
2155 2155
 
2156 2156
 
2157 2157
 
2158
-	/**
2159
-	 *	@pstn methods
2160
-	 *	------------------------------
2161
-	 *
2162
-	 *  !pstn
2163
-	 */
2158
+    /**
2159
+     *	@pstn methods
2160
+     *	------------------------------
2161
+     *
2162
+     *  !pstn
2163
+     */
2164 2164
 
2165 2165
     /**
2166 2166
      * Returns all prefixes in correct order
@@ -2172,522 +2172,522 @@  discard block
 block discarded – undo
2172 2172
      * @return array|bool
2173 2173
      */
2174 2174
     public function fetch_all_prefixes ($master = false, $recursive = false) {
2175
-	    if($master && !$recursive) {
2176
-    	    $query = 'select *,concat(prefix,start) as raw from pstnPrefixes where master = ? order by raw asc;';
2177
-    	    $params = array($master);
2178
-	    }
2179
-	    else {
2180
-    	    $query = 'select *,concat(prefix,start) as raw from pstnPrefixes order by raw asc;';
2181
-    	    $params = array();
2182
-        }
2183
-		# fetch
2184
-		try { $prefixes = $this->Database->getObjectsQuery($query, $params); }
2185
-		catch (Exception $e) {
2186
-			$this->Result->show("danger", _("Error: ").$e->getMessage());
2187
-			return false;
2188
-		}
2175
+        if($master && !$recursive) {
2176
+            $query = 'select *,concat(prefix,start) as raw from pstnPrefixes where master = ? order by raw asc;';
2177
+            $params = array($master);
2178
+        }
2179
+        else {
2180
+            $query = 'select *,concat(prefix,start) as raw from pstnPrefixes order by raw asc;';
2181
+            $params = array();
2182
+        }
2183
+        # fetch
2184
+        try { $prefixes = $this->Database->getObjectsQuery($query, $params); }
2185
+        catch (Exception $e) {
2186
+            $this->Result->show("danger", _("Error: ").$e->getMessage());
2187
+            return false;
2188
+        }
2189 2189
         // for master + recursive we need to go from master id to next 0 (root
2190 2190
         if($master && $recursive && $prefixes) {
2191 2191
             $master_set = false;
2192 2192
             $out = array();
2193 2193
 
2194 2194
             foreach ($prefixes as $k=>$p) {
2195
-        	    if($p->id == $master) {
2196
-            	    $out[] = $p;
2197
-            	    $master_set = true;
2198
-        	    }
2199
-        	    elseif ($master_set && $p->master!=0) {
2200
-            	    $out[] = $p;
2201
-        	    }
2202
-        	    elseif ($master_set && $p->master!=0) {
2203
-            	    break;
2204
-        	    }
2195
+                if($p->id == $master) {
2196
+                    $out[] = $p;
2197
+                    $master_set = true;
2198
+                }
2199
+                elseif ($master_set && $p->master!=0) {
2200
+                    $out[] = $p;
2201
+                }
2202
+                elseif ($master_set && $p->master!=0) {
2203
+                    break;
2204
+                }
2205
+            }
2206
+            $prefixes = $out;
2207
+        }
2208
+        # result
2209
+        return sizeof($prefixes)>0 ? array_values($prefixes) : false;
2210
+    }
2211
+
2212
+    /**
2213
+     * Normalize prefix / number.
2214
+     *
2215
+     * @access public
2216
+     * @param mixed $number
2217
+     * @return mixed
2218
+     */
2219
+    public function prefix_normalize ($number) {
2220
+        return str_replace(array("+", " ", "-"), "", $number);
2221
+    }
2222
+
2223
+    /**
2224
+     * fetch whole tree path for prefix - from slave to parents
2225
+     *
2226
+     * @access public
2227
+     * @param mixed $id
2228
+     * @return array
2229
+     */
2230
+    public function fetch_prefix_parents_recursive ($id) {
2231
+        $parents = array();
2232
+        $root = false;
2233
+
2234
+        while($root === false) {
2235
+            $subd = $this->fetch_object("pstnPrefixes", "id", $id);		# get subnet details
2236
+
2237
+            if($subd!==false) {
2238
+                $subd = (array) $subd;
2239
+                # not root yet
2240
+                if(@$subd['master']!=0) {
2241
+                    array_unshift($parents, $subd['master']);
2242
+                    $id  = $subd['master'];
2243
+                }
2244
+                # root
2245
+                else {
2246
+                    array_unshift($parents, $subd['master']);
2247
+                    $root = true;
2248
+                }
2249
+            }
2250
+            else {
2251
+                $root = true;
2252
+            }
2253
+        }
2254
+        # remove 0
2255
+        unset($parents[0]);
2256
+        # return array
2257
+        return $parents;
2258
+    }
2259
+
2260
+    /**
2261
+     * Fetch parents recursive - generic function
2262
+     *
2263
+     * Fetches all parents for specific table in id / parent relations
2264
+     *
2265
+     * It will return array, keys will be id's and values as defined in return_field
2266
+     *
2267
+     * @param string $table
2268
+     * @param string $parent_field
2269
+     * @param string $return_field
2270
+     * @param int $false
2271
+     * @param bool $reverse (default: true)
2272
+     *
2273
+     * @return array
2274
+     */
2275
+    public function fetch_parents_recursive ($table, $parent_field, $return_field, $id, $reverse = false) {
2276
+        $parents = array();
2277
+        $root = false;
2278
+
2279
+        while($root === false) {
2280
+            $subd = $this->fetch_object($table, "id", $id);
2281
+
2282
+            if($subd!==false) {
2283
+                $subd = (array) $subd;
2284
+                # not root yet
2285
+                if(@$subd[$parent_field]!=0) {
2286
+                    // array_unshift($parents, $subd[$parent_field]);
2287
+                    $parents[$subd['id']] = $subd[$return_field];
2288
+                    $id  = $subd[$parent_field];
2289
+                }
2290
+                # root
2291
+                else {
2292
+                    $parents[$subd['id']] = $subd[$return_field];
2293
+                    $root = true;
2294
+                }
2295
+            }
2296
+            else {
2297
+                $root = true;
2298
+            }
2299
+        }
2300
+        # return array
2301
+        return $reverse ? array_reverse($parents, truetrue) :$parents;
2302
+    }
2303
+
2304
+    /**
2305
+     * Checks for duplicate number.
2306
+     *
2307
+     * @access public
2308
+     * @param bool $prefix (default: false)
2309
+     * @param bool $number (default: false)
2310
+     * @return null|boolean
2311
+     */
2312
+    public function check_number_duplicates ($prefix = false, $number = false) {
2313
+        if($prefix===false && $number===false) {
2314
+            $this->Result->show("danger", "Duplicate chck failed", true);
2315
+        }
2316
+        else {
2317
+            $query = "select count(*) as cnt from pstnNumbers where prefix = ? and number = ?;";
2318
+            # fetch
2319
+            try { $cnt = $this->Database->getObjectQuery($query, array($prefix, $number)); }
2320
+            catch (Exception $e) {
2321
+                $this->Result->show("danger", _("Error: ").$e->getMessage());
2322
+                return false;
2323
+            }
2324
+            # result
2325
+            return $cnt->cnt>0 ? true : false;
2326
+        }
2327
+    }
2328
+
2329
+    /**
2330
+     * Checks permission for specified prefix
2331
+     *
2332
+     *	we provide user details and subnetId
2333
+     *
2334
+     * @access public
2335
+     * @param object $user
2336
+     * @return int
2337
+     */
2338
+    public function check_prefix_permission ($user) {
2339
+        return $user->role=="Administrator" ? 3 : $user->pstn;
2340
+    }
2341
+
2342
+    /**
2343
+     * Prints structured menu of prefixes
2344
+     *
2345
+     * @access public
2346
+     * @param mixed $user
2347
+     * @param mixed $prefixes
2348
+     * @param mixed $custom_fields
2349
+     * @return mixed
2350
+     */
2351
+    public function print_menu_prefixes ( $user, $prefixes, $custom_fields ) {
2352
+
2353
+        # set hidden fields
2354
+        $this->get_settings ();
2355
+        $hidden_fields = json_decode($this->settings->hiddenCustomFields, true);
2356
+        $hidden_fields = is_array($hidden_fields['subnets']) ? $hidden_fields['subnets'] : array();
2357
+
2358
+        # set html array
2359
+        $html = array();
2360
+        # root is 0
2361
+        $rootId = 0;
2362
+
2363
+        # remove all not permitted!
2364
+        if(sizeof($prefixes)>0) {
2365
+        foreach($prefixes as $k=>$s) {
2366
+            $permission = $this->check_prefix_permission ($user);
2367
+            if($permission == 0) { unset($prefixes[$k]); }
2368
+        }
2369
+        }
2370
+
2371
+        # create loop array
2372
+        if(sizeof($prefixes) > 0) {
2373
+        $children_prefixes = array();
2374
+        foreach ( $prefixes as $item ) {
2375
+            $item = (array) $item;
2376
+            $children_prefixes[$item['master']][] = $item;
2377
+        }
2378
+        }
2379
+        else {
2380
+            return false;
2381
+        }
2382
+
2383
+        # loop will be false if the root has no children (i.e., an empty menu!)
2384
+        $loop = !empty( $children_prefixes[$rootId] );
2385
+
2386
+        # initializing $parent as the root
2387
+        $parent = $rootId;
2388
+        $parent_stack = array();
2389
+
2390
+        # old count
2391
+        $old_count = 0;
2392
+
2393
+        # return table content (tr and td's)
2394
+        reset( $children_prefixes[$parent] );
2395
+        while ( $loop && ( ( $option = current( $children_prefixes[$parent] ) ) || ( $parent > $rootId ) ) )
2396
+        {
2397
+            next( $children_prefixes[$parent] );
2398
+
2399
+            if(count($parent_stack) == 0) {
2400
+                $margin = "0px";
2401
+                $padding = "0px";
2402
+            }
2403
+            else {
2404
+                # padding
2405
+                $padding = "10px";
2406
+
2407
+                # margin
2408
+                $margin  = (count($parent_stack) * 10) -10;
2409
+                $margin  = $margin *1.5;
2410
+                $margin  = $margin."px";
2411
+            }
2412
+
2413
+            # count levels
2414
+            $count = count( $parent_stack ) + 1;
2415
+
2416
+            # description
2417
+            $name = strlen($option['name'])==0 ? "/" : $option['name'];
2418
+
2419
+            # print table line
2420
+            if(strlen($option['prefix']) > 0) {
2421
+                # count change?
2422
+                $html[] = "<tr class='level$count'>";
2423
+
2424
+                //which level?
2425
+                if($count==1) {
2426
+                    # last?
2427
+                    if(!empty( $children_prefixes[$option['id']])) {
2428
+                        $html[] = "	<td class='level$count'><span class='structure-last' style='padding-left:$padding; margin-left:$margin;'></span><i class='fa fa-gray fa-pad-right-3 fa-folder-open-o'></i><a href='".create_link($_GET['page'],"pstn-prefixes",$option['id'])."'>".$option['prefix']." </a></td>";
2429
+                        $html[] = "	<td class='level$count'><span class='structure-last' style='padding-left:$padding; margin-left:$margin;'></span><i class='fa fa-gray fa-pad-right-3 fa-folder-open-o'></i> <strong>$name</strong></td>";
2430
+                    } else {
2431
+                        $html[] = "	<td class='level$count'><span class='structure' style='padding-left:$padding; margin-left:$margin;'></span><i class='fa fa-gray fa-pad-right-3 fa-angle-right'></i><a href='".create_link($_GET['page'],"pstn-prefixes",$option['id'])."'>".$option['prefix']." </a></td>";
2432
+                        $html[] = "	<td class='level$count'><span class='structure' style='padding-left:$padding; margin-left:$margin;'></span><i class='fa fa-gray fa-pad-right-3 fa-angle-right'></i> <strong>$name</strong></td>";
2433
+                    }
2434
+                }
2435
+                else {
2436
+                    # last?
2437
+                    if(!empty( $children_prefixes[$option['id']])) {
2438
+                        $html[] = "	<td class='level$count'><span class='structure-last' style='padding-left:$padding; margin-left:$margin;'></span><i class='fa fa-gray fa-pad-right-3 fa-folder-open-o'></i> <a href='".create_link($_GET['page'],"pstn-prefixes",$option['id'])."'>  ".$option['prefix']."</a></td>";
2439
+                        $html[] = "	<td class='level$count'><span class='structure-last' style='padding-left:$padding; margin-left:$margin;'></span><i class='fa fa-gray fa-pad-right-3 fa-folder-open-o'></i> <strong>$name</strong></td>";
2440
+                    }
2441
+                    else {
2442
+                        $html[] = "	<td class='level$count'><span class='structure' style='padding-left:$padding; margin-left:$margin;'></span><i class='fa fa-gray fa-pad-right-3 fa-angle-right'></i> <a href='".create_link($_GET['page'],"pstn-prefixes",$option['id'])."'>  ".$option['prefix']."</a></td>";
2443
+                        $html[] = "	<td class='level$count'><span class='structure' style='padding-left:$padding; margin-left:$margin;'></span><i class='fa fa-gray fa-pad-right-3 fa-angle-right'></i> <strong>$name</strong></td>";
2444
+                    }
2445
+                }
2446
+
2447
+                // range
2448
+                $html[] = " <td class='level$count'><span class='structure-last' style='padding-left:$padding; margin-left:$margin;'></span><i class='fa fa-gray fa-pad-right-3 fa-angle-right'></i> ".$option['prefix'].$option['start']." ".$option['prefix'].$option['stop']."</td>";
2449
+
2450
+                //start/stop
2451
+                $html[] = "	<td>".$option['start']."</td>";
2452
+                $html[] = "	<td>".$option['stop']."</td>";
2453
+
2454
+                //count
2455
+                $cnt = $this->count_database_objects("pstnNumbers", "prefix", $option['id']);
2456
+
2457
+                $html[] = "	<td><span class='badge badge1 badge5'>".$cnt."</span></td>";
2458
+
2459
+                //device
2460
+                $device = ( $option['deviceId']==0 || empty($option['deviceId']) ) ? false : true;
2461
+
2462
+                if($device===false) { $html[] ='	<td>/</td>' . "\n"; }
2463
+                else {
2464
+                    $device = $this->fetch_object ("devices", "id", $option['deviceId']);
2465
+                    if ($device!==false) {
2466
+                        $html[] = "	<td><a href='".create_link("tools","devices",$device->id)."'>".$device->hostname .'</a></td>' . "\n";
2467
+                    }
2468
+                    else {
2469
+                        $html[] ='	<td>/</td>' . "\n";
2470
+                    }
2471
+                }
2472
+
2473
+                //custom
2474
+                if(sizeof($custom_fields) > 0) {
2475
+                        foreach($custom_fields as $field) {
2476
+                            # hidden?
2477
+                            if(!in_array($field['name'], $hidden_fields)) {
2478
+
2479
+                                $html[] =  "<td class='hidden-xs hidden-sm hidden-md'>";
2480
+
2481
+                                //booleans
2482
+                            if($field['type']=="tinyint(1)")	{
2483
+                                if($option[$field['name']] == "0")			{ $html[] = _("No"); }
2484
+                                elseif($option[$field['name']] == "1")		{ $html[] = _("Yes"); }
2485
+                            }
2486
+                            //text
2487
+                            elseif($field['type']=="text") {
2488
+                                if(strlen($option[$field['name']])>0)		{ $html[] = "<i class='fa fa-gray fa-comment' rel='tooltip' data-container='body' data-html='true' title='".str_replace("\n", "<br>", $option[$field['name']])."'>"; }
2489
+                                else												{ $html[] = ""; }
2490
+                            }
2491
+                            else {
2492
+                                $html[] = $option[$field['name']];
2493
+
2494
+                            }
2495
+
2496
+                                $html[] =  "</td>";
2497
+                            }
2498
+                    }
2499
+                }
2500
+
2501
+                # set permission
2502
+                $permission = $this->check_prefix_permission ($user);
2503
+
2504
+                $html[] = "	<td class='actions' style='padding:0px;'>";
2505
+                $html[] = "	<div class='btn-group'>";
2506
+
2507
+                if($permission>2) {
2508
+                    $html[] = "		<button class='btn btn-xs btn-default editPSTN' data-action='edit'   data-id='".$option['id']."'><i class='fa fa-pencil'></i></button>";
2509
+                    $html[] = "		<button class='btn btn-xs btn-default editPSTN' data-action='delete' data-id='".$option['id']."'><i class='fa fa-times'></i></button>";
2510
+                }
2511
+                else {
2512
+                    $html[] = "		<button class='btn btn-xs btn-default disabled'><i class='fa fa-gray fa-pencil'></i></button>";
2513
+                    $html[] = "		<button class='btn btn-xs btn-default disabled'><i class='fa fa-gray fa-times'></i></button>";
2514
+                }
2515
+                $html[] = "	</div>";
2516
+                $html[] = "	</td>";
2517
+
2518
+                $html[] = "</tr>";
2519
+
2520
+                # save old level count
2521
+                $old_count = $count;
2522
+            }
2523
+
2524
+            if ( $option === false ) { $parent = array_pop( $parent_stack ); }
2525
+            # Has slave subnets
2526
+            elseif ( !empty( $children_prefixes[$option['id']] ) ) {
2527
+                array_push( $parent_stack, $option['master'] );
2528
+                $parent = $option['id'];
2529
+            }
2530
+        }
2531
+        # print
2532
+        return $html;
2533
+    }
2534
+
2535
+
2536
+
2537
+
2538
+    /**
2539
+     * Prints dropdown menu for master prefix selection in prefix editing
2540
+     *
2541
+     * @access public
2542
+     * @param bool $prefixId (default: false)
2543
+     * @return mixed
2544
+     */
2545
+    public function print_masterprefix_dropdown_menu ($prefixId = false) {
2546
+
2547
+        # initialize vars
2548
+        $children_prefixes = array();
2549
+        $parent_stack_prefixes = array();
2550
+        $html = array();
2551
+        $rootId = 0;			// root is 0
2552
+        $parent = $rootId;      // initializing $parent as the root
2553
+
2554
+        # fetch all prefixes in section
2555
+        $all_prefixes = $this->fetch_all_prefixes ();
2556
+        if (!is_array($all_prefixes)) $all_prefixes = array();
2557
+        # folder or subnet?
2558
+        foreach($all_prefixes as $s) {
2559
+            $children_prefixes[$s->master][] = (array) $s;
2560
+        }
2561
+
2562
+        # loop will be false if the root has no children (i.e., an empty menu!)
2563
+        $loop  = !empty( $children_prefixes[$rootId] );
2564
+
2565
+        # structure
2566
+        $html[] = "<select name='master' class='form-control input-sm input-w-auto input-max-200'>";
2567
+
2568
+        # root subnet
2569
+        $html[] = "<option value='0'>"._("Root subnet")."</option>";
2570
+
2571
+        # return table content (tr and td's) - subnets
2572
+        if(sizeof($children_prefixes)>0) {
2573
+        reset( $children_prefixes[$parent] );
2574
+        while ( $loop && ( ( $option = current( $children_prefixes[$parent] ) ) || ( $parent > $rootId ) ) )
2575
+        {
2576
+            next( $children_prefixes[$parent] );
2577
+            # repeat
2578
+            $repeat  = str_repeat( " &nbsp;&nbsp; ", ( count($parent_stack_prefixes)) );
2579
+
2580
+            # selected
2581
+            $selected = $option['id'] == $prefixId ? "selected='selected'" : "";
2582
+            if($option['id'])
2583
+            $html[] = "<option value='".$option['id']."' $selected>$repeat ".$option['prefix']." (".$option['name'].")</option>";
2584
+
2585
+            if ( $option === false ) { $parent = array_pop( $parent_stack_prefixes ); }
2586
+            # Has slave subnets
2587
+            elseif ( !empty( $children_prefixes[$option['id']] ) ) {
2588
+                array_push( $parent_stack_prefixes, $option['master'] );
2589
+                $parent = $option['id'];
2590
+            }		}
2591
+        }
2592
+        $html[] = "</select>";
2593
+        # join and print
2594
+        print implode( "\n", $html );
2595
+    }
2596
+
2597
+
2598
+
2599
+
2600
+    /**
2601
+     * This function compresses all pstn
2602
+     *
2603
+     *	input is array of pstn ranges
2604
+     *	output compresses pstn range
2605
+     *
2606
+     * @access public
2607
+     * @param array $numbers
2608
+     * @return array
2609
+     */
2610
+    public function compress_pstn_ranges ($numbers, $state=4) {
2611
+        # set size
2612
+        $size = sizeof($numbers);
2613
+        // vars
2614
+        $numbers_formatted = array();
2615
+
2616
+        # loop through IP addresses
2617
+        for($c=0; $c<$size; $c++) {
2618
+            # ignore already comressed range
2619
+            if($numbers[$c]->class!="compressed-range") {
2620
+                # gap between this and previous
2621
+                if(gmp_strval( @gmp_sub($numbers[$c]->number, $numbers[$c-1]->number)) != 1) {
2622
+                    # remove index flag
2623
+                    unset($fIndex);
2624
+                    # save IP address
2625
+                    $numbers_formatted[$c] = $numbers[$c];
2626
+                    $numbers_formatted[$c]->class = "ip";
2627
+
2628
+                    # no gap this -> next
2629
+                    if(gmp_strval( @gmp_sub($numbers[$c]->number, $numbers[$c+1]->number)) == -1 && $numbers[$c]->state==$state) {
2630
+                        //is state the same?
2631
+                        if($numbers[$c]->state==$numbers[$c+1]->state) {
2632
+                            $fIndex = $c;
2633
+                            $numbers_formatted[$fIndex]->startIP = $numbers[$c]->number;
2634
+                            $numbers_formatted[$c]->class = "compressed-range";
2635
+                        }
2636
+                    }
2637
+                }
2638
+                # no gap between this and previous
2639
+                else {
2640
+                    # is state same as previous?
2641
+                    if($numbers[$c]->state==$numbers[$c-1]->state && $numbers[$c]->state==$state) {
2642
+                        $numbers_formatted[$fIndex]->stopIP = $numbers[$c]->number;	//adds dhcp state
2643
+                        $numbers_formatted[$fIndex]->numHosts = gmp_strval( gmp_add(@gmp_sub($numbers[$c]->number, $numbers_formatted[$fIndex]->number),1));	//add number of hosts
2644
+                    }
2645
+                    # different state
2646
+                    else {
2647
+                        # remove index flag
2648
+                        unset($fIndex);
2649
+                        # save IP address
2650
+                        $numbers_formatted[$c] = $numbers[$c];
2651
+                        $numbers_formatted[$c]->class = "ip";
2652
+                        # check if state is same as next to start range
2653
+                        if($numbers[$c]->state==@$numbers[$c+1]->state &&  gmp_strval( @gmp_sub($numbers[$c]->number, $numbers[$c+1]->number)) == -1 && $numbers[$c]->state==$state) {
2654
+                            $fIndex = $c;
2655
+                            $numbers_formatted[$fIndex]->startIP = $numbers[$c]->number;
2656
+                            $numbers_formatted[$c]->class = "compressed-range";
2657
+                        }
2658
+                    }
2659
+                }
2660
+            }
2661
+            else {
2662
+                # save already compressed
2663
+                $numbers_formatted[$c] = $numbers[$c];
2205 2664
             }
2206
-            $prefixes = $out;
2207 2665
         }
2208
-		# result
2209
-		return sizeof($prefixes)>0 ? array_values($prefixes) : false;
2666
+        # overrwrite ipaddresses and rekey
2667
+        $addresses = @array_values($numbers_formatted);
2668
+        # return
2669
+        return $addresses;
2210 2670
     }
2211 2671
 
2212 2672
     /**
2213
-     * Normalize prefix / number.
2673
+     * Calculates pstn usage - dhcp, active, ...
2214 2674
      *
2215 2675
      * @access public
2216
-     * @param mixed $number
2217
-     * @return mixed
2676
+     * @param obj $prefix        //subnet in decimal format
2677
+     * @param obj $numbers	     //netmask in decimal format
2678
+     * @return array
2218 2679
      */
2219
-    public function prefix_normalize ($number) {
2220
-        return str_replace(array("+", " ", "-"), "", $number);
2221
-    }
2222
-
2223
-	/**
2224
-	 * fetch whole tree path for prefix - from slave to parents
2225
-	 *
2226
-	 * @access public
2227
-	 * @param mixed $id
2228
-	 * @return array
2229
-	 */
2230
-	public function fetch_prefix_parents_recursive ($id) {
2231
-		$parents = array();
2232
-		$root = false;
2233
-
2234
-		while($root === false) {
2235
-			$subd = $this->fetch_object("pstnPrefixes", "id", $id);		# get subnet details
2236
-
2237
-			if($subd!==false) {
2238
-    			$subd = (array) $subd;
2239
-				# not root yet
2240
-				if(@$subd['master']!=0) {
2241
-					array_unshift($parents, $subd['master']);
2242
-					$id  = $subd['master'];
2243
-				}
2244
-				# root
2245
-				else {
2246
-					array_unshift($parents, $subd['master']);
2247
-					$root = true;
2248
-				}
2249
-			}
2250
-			else {
2251
-				$root = true;
2252
-			}
2253
-		}
2254
-		# remove 0
2255
-		unset($parents[0]);
2256
-		# return array
2257
-		return $parents;
2258
-	}
2259
-
2260
-	/**
2261
-	 * Fetch parents recursive - generic function
2262
-	 *
2263
-	 * Fetches all parents for specific table in id / parent relations
2264
-	 *
2265
-	 * It will return array, keys will be id's and values as defined in return_field
2266
-	 *
2267
-	 * @param string $table
2268
-	 * @param string $parent_field
2269
-	 * @param string $return_field
2270
-	 * @param int $false
2271
-	 * @param bool $reverse (default: true)
2272
-	 *
2273
-	 * @return array
2274
-	 */
2275
-	public function fetch_parents_recursive ($table, $parent_field, $return_field, $id, $reverse = false) {
2276
-		$parents = array();
2277
-		$root = false;
2278
-
2279
-		while($root === false) {
2280
-			$subd = $this->fetch_object($table, "id", $id);
2281
-
2282
-			if($subd!==false) {
2283
-    			$subd = (array) $subd;
2284
-				# not root yet
2285
-				if(@$subd[$parent_field]!=0) {
2286
-					// array_unshift($parents, $subd[$parent_field]);
2287
-					$parents[$subd['id']] = $subd[$return_field];
2288
-					$id  = $subd[$parent_field];
2289
-				}
2290
-				# root
2291
-				else {
2292
-					$parents[$subd['id']] = $subd[$return_field];
2293
-					$root = true;
2294
-				}
2295
-			}
2296
-			else {
2297
-				$root = true;
2298
-			}
2299
-		}
2300
-		# return array
2301
-		return $reverse ? array_reverse($parents, truetrue) :$parents;
2302
-	}
2303
-
2304
-	/**
2305
-	 * Checks for duplicate number.
2306
-	 *
2307
-	 * @access public
2308
-	 * @param bool $prefix (default: false)
2309
-	 * @param bool $number (default: false)
2310
-	 * @return null|boolean
2311
-	 */
2312
-	public function check_number_duplicates ($prefix = false, $number = false) {
2313
-    	if($prefix===false && $number===false) {
2314
-        	$this->Result->show("danger", "Duplicate chck failed", true);
2315
-    	}
2316
-    	else {
2317
-        	$query = "select count(*) as cnt from pstnNumbers where prefix = ? and number = ?;";
2318
-    		# fetch
2319
-    		try { $cnt = $this->Database->getObjectQuery($query, array($prefix, $number)); }
2320
-    		catch (Exception $e) {
2321
-    			$this->Result->show("danger", _("Error: ").$e->getMessage());
2322
-    			return false;
2323
-    		}
2324
-    		# result
2325
-    		return $cnt->cnt>0 ? true : false;
2326
-    	}
2327
-	}
2328
-
2329
-	/**
2330
-	 * Checks permission for specified prefix
2331
-	 *
2332
-	 *	we provide user details and subnetId
2333
-	 *
2334
-	 * @access public
2335
-	 * @param object $user
2336
-	 * @return int
2337
-	 */
2338
-	public function check_prefix_permission ($user) {
2339
-        return $user->role=="Administrator" ? 3 : $user->pstn;
2340
-	}
2341
-
2342
-	/**
2343
-	 * Prints structured menu of prefixes
2344
-	 *
2345
-	 * @access public
2346
-	 * @param mixed $user
2347
-	 * @param mixed $prefixes
2348
-	 * @param mixed $custom_fields
2349
-	 * @return mixed
2350
-	 */
2351
-	public function print_menu_prefixes ( $user, $prefixes, $custom_fields ) {
2352
-
2353
-		# set hidden fields
2354
-		$this->get_settings ();
2355
-		$hidden_fields = json_decode($this->settings->hiddenCustomFields, true);
2356
-		$hidden_fields = is_array($hidden_fields['subnets']) ? $hidden_fields['subnets'] : array();
2357
-
2358
-		# set html array
2359
-		$html = array();
2360
-		# root is 0
2361
-		$rootId = 0;
2362
-
2363
-		# remove all not permitted!
2364
-		if(sizeof($prefixes)>0) {
2365
-		foreach($prefixes as $k=>$s) {
2366
-			$permission = $this->check_prefix_permission ($user);
2367
-			if($permission == 0) { unset($prefixes[$k]); }
2368
-		}
2369
-		}
2370
-
2371
-		# create loop array
2372
-		if(sizeof($prefixes) > 0) {
2373
-        $children_prefixes = array();
2374
-		foreach ( $prefixes as $item ) {
2375
-			$item = (array) $item;
2376
-			$children_prefixes[$item['master']][] = $item;
2377
-		}
2378
-		}
2379
-		else {
2380
-			return false;
2381
-		}
2382
-
2383
-		# loop will be false if the root has no children (i.e., an empty menu!)
2384
-		$loop = !empty( $children_prefixes[$rootId] );
2385
-
2386
-		# initializing $parent as the root
2387
-		$parent = $rootId;
2388
-		$parent_stack = array();
2389
-
2390
-		# old count
2391
-		$old_count = 0;
2392
-
2393
-		# return table content (tr and td's)
2394
-		reset( $children_prefixes[$parent] );
2395
-		while ( $loop && ( ( $option = current( $children_prefixes[$parent] ) ) || ( $parent > $rootId ) ) )
2396
-		{
2397
-			next( $children_prefixes[$parent] );
2398
-
2399
-			if(count($parent_stack) == 0) {
2400
-				$margin = "0px";
2401
-				$padding = "0px";
2402
-			}
2403
-			else {
2404
-				# padding
2405
-				$padding = "10px";
2406
-
2407
-				# margin
2408
-				$margin  = (count($parent_stack) * 10) -10;
2409
-				$margin  = $margin *1.5;
2410
-				$margin  = $margin."px";
2411
-			}
2412
-
2413
-			# count levels
2414
-			$count = count( $parent_stack ) + 1;
2415
-
2416
-			# description
2417
-			$name = strlen($option['name'])==0 ? "/" : $option['name'];
2418
-
2419
-			# print table line
2420
-			if(strlen($option['prefix']) > 0) {
2421
-    			# count change?
2422
-				$html[] = "<tr class='level$count'>";
2423
-
2424
-				//which level?
2425
-				if($count==1) {
2426
-					# last?
2427
-					if(!empty( $children_prefixes[$option['id']])) {
2428
-						$html[] = "	<td class='level$count'><span class='structure-last' style='padding-left:$padding; margin-left:$margin;'></span><i class='fa fa-gray fa-pad-right-3 fa-folder-open-o'></i><a href='".create_link($_GET['page'],"pstn-prefixes",$option['id'])."'>".$option['prefix']." </a></td>";
2429
-						$html[] = "	<td class='level$count'><span class='structure-last' style='padding-left:$padding; margin-left:$margin;'></span><i class='fa fa-gray fa-pad-right-3 fa-folder-open-o'></i> <strong>$name</strong></td>";
2430
-					} else {
2431
-						$html[] = "	<td class='level$count'><span class='structure' style='padding-left:$padding; margin-left:$margin;'></span><i class='fa fa-gray fa-pad-right-3 fa-angle-right'></i><a href='".create_link($_GET['page'],"pstn-prefixes",$option['id'])."'>".$option['prefix']." </a></td>";
2432
-						$html[] = "	<td class='level$count'><span class='structure' style='padding-left:$padding; margin-left:$margin;'></span><i class='fa fa-gray fa-pad-right-3 fa-angle-right'></i> <strong>$name</strong></td>";
2433
-					}
2434
-				}
2435
-				else {
2436
-					# last?
2437
-					if(!empty( $children_prefixes[$option['id']])) {
2438
-						$html[] = "	<td class='level$count'><span class='structure-last' style='padding-left:$padding; margin-left:$margin;'></span><i class='fa fa-gray fa-pad-right-3 fa-folder-open-o'></i> <a href='".create_link($_GET['page'],"pstn-prefixes",$option['id'])."'>  ".$option['prefix']."</a></td>";
2439
-						$html[] = "	<td class='level$count'><span class='structure-last' style='padding-left:$padding; margin-left:$margin;'></span><i class='fa fa-gray fa-pad-right-3 fa-folder-open-o'></i> <strong>$name</strong></td>";
2440
-					}
2441
-					else {
2442
-						$html[] = "	<td class='level$count'><span class='structure' style='padding-left:$padding; margin-left:$margin;'></span><i class='fa fa-gray fa-pad-right-3 fa-angle-right'></i> <a href='".create_link($_GET['page'],"pstn-prefixes",$option['id'])."'>  ".$option['prefix']."</a></td>";
2443
-						$html[] = "	<td class='level$count'><span class='structure' style='padding-left:$padding; margin-left:$margin;'></span><i class='fa fa-gray fa-pad-right-3 fa-angle-right'></i> <strong>$name</strong></td>";
2444
-					}
2445
-				}
2446
-
2447
-				// range
2448
-				$html[] = " <td class='level$count'><span class='structure-last' style='padding-left:$padding; margin-left:$margin;'></span><i class='fa fa-gray fa-pad-right-3 fa-angle-right'></i> ".$option['prefix'].$option['start']." ".$option['prefix'].$option['stop']."</td>";
2449
-
2450
-				//start/stop
2451
-				$html[] = "	<td>".$option['start']."</td>";
2452
-				$html[] = "	<td>".$option['stop']."</td>";
2453
-
2454
-				//count
2455
-                $cnt = $this->count_database_objects("pstnNumbers", "prefix", $option['id']);
2456
-
2457
-                $html[] = "	<td><span class='badge badge1 badge5'>".$cnt."</span></td>";
2458
-
2459
-				//device
2460
-				$device = ( $option['deviceId']==0 || empty($option['deviceId']) ) ? false : true;
2461
-
2462
-				if($device===false) { $html[] ='	<td>/</td>' . "\n"; }
2463
-				else {
2464
-					$device = $this->fetch_object ("devices", "id", $option['deviceId']);
2465
-					if ($device!==false) {
2466
-						$html[] = "	<td><a href='".create_link("tools","devices",$device->id)."'>".$device->hostname .'</a></td>' . "\n";
2467
-					}
2468
-					else {
2469
-						$html[] ='	<td>/</td>' . "\n";
2470
-					}
2471
-				}
2472
-
2473
-				//custom
2474
-				if(sizeof($custom_fields) > 0) {
2475
-			   		foreach($custom_fields as $field) {
2476
-				   		# hidden?
2477
-				   		if(!in_array($field['name'], $hidden_fields)) {
2478
-
2479
-				   			$html[] =  "<td class='hidden-xs hidden-sm hidden-md'>";
2480
-
2481
-				   			//booleans
2482
-							if($field['type']=="tinyint(1)")	{
2483
-								if($option[$field['name']] == "0")			{ $html[] = _("No"); }
2484
-								elseif($option[$field['name']] == "1")		{ $html[] = _("Yes"); }
2485
-							}
2486
-							//text
2487
-							elseif($field['type']=="text") {
2488
-								if(strlen($option[$field['name']])>0)		{ $html[] = "<i class='fa fa-gray fa-comment' rel='tooltip' data-container='body' data-html='true' title='".str_replace("\n", "<br>", $option[$field['name']])."'>"; }
2489
-								else												{ $html[] = ""; }
2490
-							}
2491
-							else {
2492
-								$html[] = $option[$field['name']];
2493
-
2494
-							}
2495
-
2496
-				   			$html[] =  "</td>";
2497
-			   			}
2498
-			    	}
2499
-			    }
2500
-
2501
-				# set permission
2502
-				$permission = $this->check_prefix_permission ($user);
2503
-
2504
-				$html[] = "	<td class='actions' style='padding:0px;'>";
2505
-				$html[] = "	<div class='btn-group'>";
2506
-
2507
-				if($permission>2) {
2508
-					$html[] = "		<button class='btn btn-xs btn-default editPSTN' data-action='edit'   data-id='".$option['id']."'><i class='fa fa-pencil'></i></button>";
2509
-					$html[] = "		<button class='btn btn-xs btn-default editPSTN' data-action='delete' data-id='".$option['id']."'><i class='fa fa-times'></i></button>";
2510
-				}
2511
-				else {
2512
-					$html[] = "		<button class='btn btn-xs btn-default disabled'><i class='fa fa-gray fa-pencil'></i></button>";
2513
-					$html[] = "		<button class='btn btn-xs btn-default disabled'><i class='fa fa-gray fa-times'></i></button>";
2514
-				}
2515
-				$html[] = "	</div>";
2516
-				$html[] = "	</td>";
2517
-
2518
-				$html[] = "</tr>";
2519
-
2520
-                # save old level count
2521
-                $old_count = $count;
2522
-			}
2523
-
2524
-			if ( $option === false ) { $parent = array_pop( $parent_stack ); }
2525
-			# Has slave subnets
2526
-			elseif ( !empty( $children_prefixes[$option['id']] ) ) {
2527
-				array_push( $parent_stack, $option['master'] );
2528
-				$parent = $option['id'];
2529
-			}
2530
-		}
2531
-		# print
2532
-		return $html;
2533
-	}
2534
-
2535
-
2536
-
2537
-
2538
-	/**
2539
-	 * Prints dropdown menu for master prefix selection in prefix editing
2540
-	 *
2541
-	 * @access public
2542
-	 * @param bool $prefixId (default: false)
2543
-	 * @return mixed
2544
-	 */
2545
-	public function print_masterprefix_dropdown_menu ($prefixId = false) {
2546
-
2547
-		# initialize vars
2548
-		$children_prefixes = array();
2549
-		$parent_stack_prefixes = array();
2550
-		$html = array();
2551
-		$rootId = 0;			// root is 0
2552
-		$parent = $rootId;      // initializing $parent as the root
2553
-
2554
-		# fetch all prefixes in section
2555
-		$all_prefixes = $this->fetch_all_prefixes ();
2556
-		if (!is_array($all_prefixes)) $all_prefixes = array();
2557
-		# folder or subnet?
2558
-		foreach($all_prefixes as $s) {
2559
-			$children_prefixes[$s->master][] = (array) $s;
2560
-		}
2561
-
2562
-		# loop will be false if the root has no children (i.e., an empty menu!)
2563
-		$loop  = !empty( $children_prefixes[$rootId] );
2564
-
2565
-		# structure
2566
-		$html[] = "<select name='master' class='form-control input-sm input-w-auto input-max-200'>";
2567
-
2568
-		# root subnet
2569
-		$html[] = "<option value='0'>"._("Root subnet")."</option>";
2570
-
2571
-		# return table content (tr and td's) - subnets
2572
-		if(sizeof($children_prefixes)>0) {
2573
-		reset( $children_prefixes[$parent] );
2574
-		while ( $loop && ( ( $option = current( $children_prefixes[$parent] ) ) || ( $parent > $rootId ) ) )
2575
-		{
2576
-			next( $children_prefixes[$parent] );
2577
-			# repeat
2578
-			$repeat  = str_repeat( " &nbsp;&nbsp; ", ( count($parent_stack_prefixes)) );
2579
-
2580
-			# selected
2581
-			$selected = $option['id'] == $prefixId ? "selected='selected'" : "";
2582
-			if($option['id'])
2583
-            $html[] = "<option value='".$option['id']."' $selected>$repeat ".$option['prefix']." (".$option['name'].")</option>";
2584
-
2585
-			if ( $option === false ) { $parent = array_pop( $parent_stack_prefixes ); }
2586
-			# Has slave subnets
2587
-			elseif ( !empty( $children_prefixes[$option['id']] ) ) {
2588
-				array_push( $parent_stack_prefixes, $option['master'] );
2589
-				$parent = $option['id'];
2590
-			}		}
2591
-		}
2592
-		$html[] = "</select>";
2593
-		# join and print
2594
-		print implode( "\n", $html );
2595
-	}
2596
-
2597
-
2598
-
2599
-
2600
-	/**
2601
-	 * This function compresses all pstn
2602
-	 *
2603
-	 *	input is array of pstn ranges
2604
-	 *	output compresses pstn range
2605
-	 *
2606
-	 * @access public
2607
-	 * @param array $numbers
2608
-	 * @return array
2609
-	 */
2610
-	public function compress_pstn_ranges ($numbers, $state=4) {
2611
-    	# set size
2612
-    	$size = sizeof($numbers);
2613
-    	// vars
2614
-    	$numbers_formatted = array();
2615
-
2616
-		# loop through IP addresses
2617
-		for($c=0; $c<$size; $c++) {
2618
-			# ignore already comressed range
2619
-			if($numbers[$c]->class!="compressed-range") {
2620
-				# gap between this and previous
2621
-				if(gmp_strval( @gmp_sub($numbers[$c]->number, $numbers[$c-1]->number)) != 1) {
2622
-					# remove index flag
2623
-					unset($fIndex);
2624
-					# save IP address
2625
-					$numbers_formatted[$c] = $numbers[$c];
2626
-					$numbers_formatted[$c]->class = "ip";
2627
-
2628
-					# no gap this -> next
2629
-					if(gmp_strval( @gmp_sub($numbers[$c]->number, $numbers[$c+1]->number)) == -1 && $numbers[$c]->state==$state) {
2630
-						//is state the same?
2631
-						if($numbers[$c]->state==$numbers[$c+1]->state) {
2632
-							$fIndex = $c;
2633
-							$numbers_formatted[$fIndex]->startIP = $numbers[$c]->number;
2634
-							$numbers_formatted[$c]->class = "compressed-range";
2635
-						}
2636
-					}
2637
-				}
2638
-				# no gap between this and previous
2639
-				else {
2640
-					# is state same as previous?
2641
-					if($numbers[$c]->state==$numbers[$c-1]->state && $numbers[$c]->state==$state) {
2642
-						$numbers_formatted[$fIndex]->stopIP = $numbers[$c]->number;	//adds dhcp state
2643
-						$numbers_formatted[$fIndex]->numHosts = gmp_strval( gmp_add(@gmp_sub($numbers[$c]->number, $numbers_formatted[$fIndex]->number),1));	//add number of hosts
2644
-					}
2645
-					# different state
2646
-					else {
2647
-						# remove index flag
2648
-						unset($fIndex);
2649
-						# save IP address
2650
-						$numbers_formatted[$c] = $numbers[$c];
2651
-						$numbers_formatted[$c]->class = "ip";
2652
-						# check if state is same as next to start range
2653
-						if($numbers[$c]->state==@$numbers[$c+1]->state &&  gmp_strval( @gmp_sub($numbers[$c]->number, $numbers[$c+1]->number)) == -1 && $numbers[$c]->state==$state) {
2654
-							$fIndex = $c;
2655
-							$numbers_formatted[$fIndex]->startIP = $numbers[$c]->number;
2656
-							$numbers_formatted[$c]->class = "compressed-range";
2657
-						}
2658
-					}
2659
-				}
2660
-			}
2661
-			else {
2662
-				# save already compressed
2663
-				$numbers_formatted[$c] = $numbers[$c];
2664
-			}
2665
-		}
2666
-		# overrwrite ipaddresses and rekey
2667
-		$addresses = @array_values($numbers_formatted);
2668
-		# return
2669
-		return $addresses;
2670
-	}
2671
-
2672
-	/**
2673
-	 * Calculates pstn usage - dhcp, active, ...
2674
-	 *
2675
-	 * @access public
2676
-	 * @param obj $prefix        //subnet in decimal format
2677
-	 * @param obj $numbers	     //netmask in decimal format
2678
-	 * @return array
2679
-	 */
2680
-	public function calculate_prefix_usege ($prefix, $numbers) {
2681
-	    # calculate max number of hosts
2682
-	    $details = array();
2683
-	    $details['maxhosts'] = ($prefix->stop - $prefix->start + 1);
2684
-
2685
-		# get IP address count per address type
2686
-		if($numbers!==false) {
2687
-		    $details_p = $this->calculate_prefix_usage_sort_numbers ($numbers);
2688
-    	    foreach($this->address_types as $t) {
2689
-    		    $details[$t['type']."_percent"] = round( ( ($details_p[$t['type']] * 100) / $details['maxhosts']), 2 );
2690
-    	    }
2680
+    public function calculate_prefix_usege ($prefix, $numbers) {
2681
+        # calculate max number of hosts
2682
+        $details = array();
2683
+        $details['maxhosts'] = ($prefix->stop - $prefix->start + 1);
2684
+
2685
+        # get IP address count per address type
2686
+        if($numbers!==false) {
2687
+            $details_p = $this->calculate_prefix_usage_sort_numbers ($numbers);
2688
+            foreach($this->address_types as $t) {
2689
+                $details[$t['type']."_percent"] = round( ( ($details_p[$t['type']] * 100) / $details['maxhosts']), 2 );
2690
+            }
2691 2691
 
2692 2692
             # calculate free hosts
2693 2693
             $details['freehosts'] =  $details['maxhosts'] - sizeof($numbers);
@@ -2695,76 +2695,76 @@  discard block
 block discarded – undo
2695 2695
         else {
2696 2696
             $details['freehosts'] =  $details['maxhosts'];
2697 2697
         }
2698
-	    # calculate use percentage for each type
2699
-	    $details['freehosts_percent'] = round( ( ($details['freehosts'] * 100) / $details['maxhosts']), 2 );
2700
-
2701
-	    # result
2702
-	    return $details;
2703
-	}
2704
-
2705
-	/**
2706
-	 * Calculates number usage per host type
2707
-	 *
2708
-	 * @access public
2709
-	 * @param mixed $numbers
2710
-	 * @return array
2711
-	 */
2712
-	public function calculate_prefix_usage_sort_numbers ($numbers) {
2713
-		$count = array();
2714
-		$count['used'] = 0;				//initial sum count
2715
-		# fetch address types
2716
-		$this->get_addresses_types();
2717
-		# create array of keys with initial value of 0
2718
-		foreach($this->address_types as $a) {
2719
-			$count[$a['type']] = 0;
2720
-		}
2721
-		# count
2722
-		if($numbers!==false) {
2723
-			foreach($numbers as $n) {
2724
-				$count[$this->translate_address_type($n->state)]++;
2725
-				$count['used'] = gmp_strval(gmp_add($count['used'], 1));
2726
-			}
2727
-		}
2728
-		# result
2729
-		return $count;
2730
-	}
2731
-
2732
-	/**
2733
-	 * Returns array of address types
2734
-	 *
2735
-	 * @access public
2736
-	 */
2737
-	public function get_addresses_types () {
2738
-		# from cache
2739
-		if($this->address_types == null) {
2740
-        	# fetch
2741
-        	$types = $this->fetch_all_objects ("ipTags", "id");
2698
+        # calculate use percentage for each type
2699
+        $details['freehosts_percent'] = round( ( ($details['freehosts'] * 100) / $details['maxhosts']), 2 );
2700
+
2701
+        # result
2702
+        return $details;
2703
+    }
2704
+
2705
+    /**
2706
+     * Calculates number usage per host type
2707
+     *
2708
+     * @access public
2709
+     * @param mixed $numbers
2710
+     * @return array
2711
+     */
2712
+    public function calculate_prefix_usage_sort_numbers ($numbers) {
2713
+        $count = array();
2714
+        $count['used'] = 0;				//initial sum count
2715
+        # fetch address types
2716
+        $this->get_addresses_types();
2717
+        # create array of keys with initial value of 0
2718
+        foreach($this->address_types as $a) {
2719
+            $count[$a['type']] = 0;
2720
+        }
2721
+        # count
2722
+        if($numbers!==false) {
2723
+            foreach($numbers as $n) {
2724
+                $count[$this->translate_address_type($n->state)]++;
2725
+                $count['used'] = gmp_strval(gmp_add($count['used'], 1));
2726
+            }
2727
+        }
2728
+        # result
2729
+        return $count;
2730
+    }
2731
+
2732
+    /**
2733
+     * Returns array of address types
2734
+     *
2735
+     * @access public
2736
+     */
2737
+    public function get_addresses_types () {
2738
+        # from cache
2739
+        if($this->address_types == null) {
2740
+            # fetch
2741
+            $types = $this->fetch_all_objects ("ipTags", "id");
2742 2742
 
2743 2743
             # save to array
2744
-			$types_out = array();
2745
-			foreach($types as $t) {
2746
-				$types_out[$t->id] = (array) $t;
2747
-			}
2748
-			# save to cache
2749
-			$this->address_types = $types_out;
2750
-		}
2751
-	}
2744
+            $types_out = array();
2745
+            foreach($types as $t) {
2746
+                $types_out[$t->id] = (array) $t;
2747
+            }
2748
+            # save to cache
2749
+            $this->address_types = $types_out;
2750
+        }
2751
+    }
2752 2752
 
2753
-	/**
2754
-	 * Translates address type from index (int) to type
2755
-	 *
2756
-	 *	e.g.: 0 > offline
2757
-	 *
2758
-	 * @access public
2759
-	 * @param mixed $index
2760
-	 * @return array
2761
-	 */
2762
-	public function translate_address_type ($index) {
2763
-		# fetch
2764
-		$this->get_addresses_types();
2765
-		# return
2766
-		return $this->address_types[$index]["type"];
2767
-	}
2753
+    /**
2754
+     * Translates address type from index (int) to type
2755
+     *
2756
+     *	e.g.: 0 > offline
2757
+     *
2758
+     * @access public
2759
+     * @param mixed $index
2760
+     * @return array
2761
+     */
2762
+    public function translate_address_type ($index) {
2763
+        # fetch
2764
+        $this->get_addresses_types();
2765
+        # return
2766
+        return $this->address_types[$index]["type"];
2767
+    }
2768 2768
 
2769 2769
 
2770 2770
 
@@ -2776,12 +2776,12 @@  discard block
 block discarded – undo
2776 2776
 
2777 2777
 
2778 2778
 
2779
-	/**
2780
-	 *	@location methods
2781
-	 *	------------------------------
2782
-	 *
2783
-	 *  !location
2784
-	 */
2779
+    /**
2780
+     *	@location methods
2781
+     *	------------------------------
2782
+     *
2783
+     *  !location
2784
+     */
2785 2785
 
2786 2786
     /**
2787 2787
      * Fetches all location objects.
@@ -2843,12 +2843,12 @@  discard block
 block discarded – undo
2843 2843
                         )
2844 2844
                         as linked;";
2845 2845
 
2846
-     		// fetch
2847
-    		try { $objects = $this->Database->getObjectsQuery($query); }
2848
-    		catch (Exception $e) { $this->Result->show("danger", $e->getMessage(), true); }
2846
+                // fetch
2847
+            try { $objects = $this->Database->getObjectsQuery($query); }
2848
+            catch (Exception $e) { $this->Result->show("danger", $e->getMessage(), true); }
2849 2849
 
2850
-    		// return
2851
-    		return sizeof($objects)>0 ? $objects : false;
2850
+            // return
2851
+            return sizeof($objects)>0 ? $objects : false;
2852 2852
         }
2853 2853
         else {
2854 2854
             return false;
@@ -2857,340 +2857,340 @@  discard block
 block discarded – undo
2857 2857
 
2858 2858
 
2859 2859
 
2860
-	/**
2861
-	 *	@misc methods
2862
-	 *	------------------------------
2863
-	 */
2864
-
2865
-	/**
2866
-	 * Fetches all circuits from database
2867
-	 *
2868
-	 * @method fetch_all_circuits
2869
-	 *
2870
-	 * @param  array $custom_circuit_fields
2871
-	 *
2872
-	 * @return false|array
2873
-	 */
2874
-	public function fetch_all_circuits ($custom_circuit_fields = array ()) {
2875
-		// set query
2876
-		$query[] = "select";
2877
-		$query[] = "c.id,c.cid,c.type,c.device1,c.location1,c.device2,c.location2,c.customer_id,p.name,p.description,p.contact,c.capacity,p.id as pid,c.status";
2878
-		// custom fields
2879
-		if(is_array($custom_circuit_fields)) {
2880
-			if(sizeof($custom_circuit_fields)>0) {
2881
-				foreach ($custom_circuit_fields as $f) {
2882
-					$query[] = ",c.`".$f['name']."`";
2883
-				}
2884
-			}
2885
-		}
2886
-		$query[] = "from circuits as c, circuitProviders as p where c.provider = p.id";
2887
-		$query[] = "order by c.cid asc;";
2888
-		// fetch
2889
-		try { $circuits = $this->Database->getObjectsQuery(implode("\n", $query), array()); }
2890
-		catch (Exception $e) {
2891
-			$this->Result->show("danger", $e->getMessage(), true);
2892
-		}
2893
-		// return
2894
-		return sizeof($circuits)>0 ? $circuits : false;
2895
-	}
2896
-
2897
-	/**
2898
-	 * Fetches all logical circuits belonging to circuit
2899
-	 *
2900
-	 * @method fetch_all_logical_circuits_using_circuit
2901
-	 * @param  int $circuit_id
2902
-	 * @return array|false
2903
-	 */
2904
-	public function fetch_all_logical_circuits_using_circuit ($circuit_id) {
2905
-		// set query
2906
-		$query[] = "select";
2907
-		$query[] = "lc.*";
2908
-		$query[] = "from circuitsLogical as lc";
2909
-		$query[] = "join `circuitsLogicalMapping` mapping on mapping.logicalCircuit_id=lc.id";
2910
-		$query[] = "WHERE mapping.circuit_id = ?";
2911
-		$query[] = "order by lc.logical_cid asc;";
2912
-		// fetch
2913
-		try { $circuits = $this->Database->getObjectsQuery(implode("\n", $query), [$circuit_id]); }
2914
-		catch (Exception $e) {
2915
-			$this->Result->show("danger", $e->getMessage(), true);
2916
-		}
2917
-		// return
2918
-		return sizeof($circuits)>0 ? $circuits : false;
2919
-	}
2920
-
2921
-	/**
2922
-	 * Fetch all members of logical circuit
2923
-	 *
2924
-	 * @method fetch_all_logical_circuit_members
2925
-	 * @param  int $logical_circuit_id
2926
-	 * @return array|false
2927
-	 */
2928
-  	public function fetch_all_logical_circuit_members ($logical_circuit_id) {
2929
-  		// set query
2930
-		$query2[] = "SELECT";
2931
-		$query2[] = "c.*";
2932
-		$query2[] = "FROM `circuits` c";
2933
-		$query2[] = "join `circuitsLogicalMapping` mapping on mapping.circuit_id=c.id";
2934
-		$query2[] = "where mapping.logicalCircuit_id = ?";
2935
-		$query2[] = "order by mapping.`order`;";
2936
-		// fetch
2937
-		try { $circuits = $this->Database->getObjectsQuery(implode("\n", $query2), $logical_circuit_id); }
2938
-		catch (Exception $e) {
2939
-			$this->Result->show("danger", $e->getMessage(), true);
2940
-		}
2941
-		return sizeof($circuits)>0 ? $circuits : false;
2942
-	}
2943
-
2944
-	/**
2945
-	 * Fetches all circuits for specific provider
2946
-	 *
2947
-	 * @method fetch_all_circuits
2948
-	 *
2949
-	 * @param  int $provider_id
2950
-	 * @param  array $custom_circuit_fields
2951
-	 *
2952
-	 * @return false|array
2953
-	 */
2954
-	public function fetch_all_provider_circuits ($provider_id, $custom_circuit_fields = array ()) {
2955
-		// set query
2956
-		$query[] = "select";
2957
-		$query[] = "c.id,c.cid,c.type,c.device1,c.location1,c.device2,c.location2,p.name,p.description,p.contact,c.capacity,p.id as pid,c.status";
2958
-		// custom fields
2959
-		if(is_array($custom_circuit_fields)) {
2960
-			if(sizeof($custom_circuit_fields)>0) {
2961
-				foreach ($custom_circuit_fields as $f) {
2962
-					$query[] = ",c.`".$f['name']."`";
2963
-				}
2964
-			}
2965
-		}
2966
-		$query[] = "from circuits as c, circuitProviders as p where c.provider = p.id and c.provider = ?";
2967
-		$query[] = "order by c.cid asc;";
2968
-		// fetch
2969
-		try { $circuits = $this->Database->getObjectsQuery(implode("\n", $query), array($provider_id)); }
2970
-		catch (Exception $e) {
2971
-			$this->Result->show("danger", $e->getMessage(), true);
2972
-		}
2973
-		// return
2974
-		return sizeof($circuits)>0 ? $circuits : false;
2975
-	}
2976
-
2977
-
2978
-	/**
2979
-	 * Fetches all circuits for specific device
2980
-	 *
2981
-	 * @method fetch_all_circuits
2982
-	 *
2983
-	 * @param  int $device_id
2984
-	 *
2985
-	 * @return false|array
2986
-	 */
2987
-	public function fetch_all_device_circuits ($device_id) {
2988
-		// set query
2989
-		$query = "select
2860
+    /**
2861
+     *	@misc methods
2862
+     *	------------------------------
2863
+     */
2864
+
2865
+    /**
2866
+     * Fetches all circuits from database
2867
+     *
2868
+     * @method fetch_all_circuits
2869
+     *
2870
+     * @param  array $custom_circuit_fields
2871
+     *
2872
+     * @return false|array
2873
+     */
2874
+    public function fetch_all_circuits ($custom_circuit_fields = array ()) {
2875
+        // set query
2876
+        $query[] = "select";
2877
+        $query[] = "c.id,c.cid,c.type,c.device1,c.location1,c.device2,c.location2,c.customer_id,p.name,p.description,p.contact,c.capacity,p.id as pid,c.status";
2878
+        // custom fields
2879
+        if(is_array($custom_circuit_fields)) {
2880
+            if(sizeof($custom_circuit_fields)>0) {
2881
+                foreach ($custom_circuit_fields as $f) {
2882
+                    $query[] = ",c.`".$f['name']."`";
2883
+                }
2884
+            }
2885
+        }
2886
+        $query[] = "from circuits as c, circuitProviders as p where c.provider = p.id";
2887
+        $query[] = "order by c.cid asc;";
2888
+        // fetch
2889
+        try { $circuits = $this->Database->getObjectsQuery(implode("\n", $query), array()); }
2890
+        catch (Exception $e) {
2891
+            $this->Result->show("danger", $e->getMessage(), true);
2892
+        }
2893
+        // return
2894
+        return sizeof($circuits)>0 ? $circuits : false;
2895
+    }
2896
+
2897
+    /**
2898
+     * Fetches all logical circuits belonging to circuit
2899
+     *
2900
+     * @method fetch_all_logical_circuits_using_circuit
2901
+     * @param  int $circuit_id
2902
+     * @return array|false
2903
+     */
2904
+    public function fetch_all_logical_circuits_using_circuit ($circuit_id) {
2905
+        // set query
2906
+        $query[] = "select";
2907
+        $query[] = "lc.*";
2908
+        $query[] = "from circuitsLogical as lc";
2909
+        $query[] = "join `circuitsLogicalMapping` mapping on mapping.logicalCircuit_id=lc.id";
2910
+        $query[] = "WHERE mapping.circuit_id = ?";
2911
+        $query[] = "order by lc.logical_cid asc;";
2912
+        // fetch
2913
+        try { $circuits = $this->Database->getObjectsQuery(implode("\n", $query), [$circuit_id]); }
2914
+        catch (Exception $e) {
2915
+            $this->Result->show("danger", $e->getMessage(), true);
2916
+        }
2917
+        // return
2918
+        return sizeof($circuits)>0 ? $circuits : false;
2919
+    }
2920
+
2921
+    /**
2922
+     * Fetch all members of logical circuit
2923
+     *
2924
+     * @method fetch_all_logical_circuit_members
2925
+     * @param  int $logical_circuit_id
2926
+     * @return array|false
2927
+     */
2928
+        public function fetch_all_logical_circuit_members ($logical_circuit_id) {
2929
+            // set query
2930
+        $query2[] = "SELECT";
2931
+        $query2[] = "c.*";
2932
+        $query2[] = "FROM `circuits` c";
2933
+        $query2[] = "join `circuitsLogicalMapping` mapping on mapping.circuit_id=c.id";
2934
+        $query2[] = "where mapping.logicalCircuit_id = ?";
2935
+        $query2[] = "order by mapping.`order`;";
2936
+        // fetch
2937
+        try { $circuits = $this->Database->getObjectsQuery(implode("\n", $query2), $logical_circuit_id); }
2938
+        catch (Exception $e) {
2939
+            $this->Result->show("danger", $e->getMessage(), true);
2940
+        }
2941
+        return sizeof($circuits)>0 ? $circuits : false;
2942
+    }
2943
+
2944
+    /**
2945
+     * Fetches all circuits for specific provider
2946
+     *
2947
+     * @method fetch_all_circuits
2948
+     *
2949
+     * @param  int $provider_id
2950
+     * @param  array $custom_circuit_fields
2951
+     *
2952
+     * @return false|array
2953
+     */
2954
+    public function fetch_all_provider_circuits ($provider_id, $custom_circuit_fields = array ()) {
2955
+        // set query
2956
+        $query[] = "select";
2957
+        $query[] = "c.id,c.cid,c.type,c.device1,c.location1,c.device2,c.location2,p.name,p.description,p.contact,c.capacity,p.id as pid,c.status";
2958
+        // custom fields
2959
+        if(is_array($custom_circuit_fields)) {
2960
+            if(sizeof($custom_circuit_fields)>0) {
2961
+                foreach ($custom_circuit_fields as $f) {
2962
+                    $query[] = ",c.`".$f['name']."`";
2963
+                }
2964
+            }
2965
+        }
2966
+        $query[] = "from circuits as c, circuitProviders as p where c.provider = p.id and c.provider = ?";
2967
+        $query[] = "order by c.cid asc;";
2968
+        // fetch
2969
+        try { $circuits = $this->Database->getObjectsQuery(implode("\n", $query), array($provider_id)); }
2970
+        catch (Exception $e) {
2971
+            $this->Result->show("danger", $e->getMessage(), true);
2972
+        }
2973
+        // return
2974
+        return sizeof($circuits)>0 ? $circuits : false;
2975
+    }
2976
+
2977
+
2978
+    /**
2979
+     * Fetches all circuits for specific device
2980
+     *
2981
+     * @method fetch_all_circuits
2982
+     *
2983
+     * @param  int $device_id
2984
+     *
2985
+     * @return false|array
2986
+     */
2987
+    public function fetch_all_device_circuits ($device_id) {
2988
+        // set query
2989
+        $query = "select
2990 2990
 					c.id,c.cid,c.type,c.device1,c.location1,c.device2,c.location2,p.name,p.description,p.contact,c.capacity,p.id as pid,c.status
2991 2991
 					from circuits as c, circuitProviders as p where c.provider = p.id and (c.device1 = :deviceid or c.device2 = :deviceid)
2992 2992
 					order by c.cid asc;";
2993
-		// fetch
2994
-		try { $circuits = $this->Database->getObjectsQuery($query, array("deviceid"=>$device_id)); }
2995
-		catch (Exception $e) {
2996
-			$this->Result->show("danger", $e->getMessage(), true);
2997
-		}
2998
-		// return
2999
-		return sizeof($circuits)>0 ? $circuits : false;
3000
-	}
3001
-
3002
-	/**
3003
-	 * Reformat circuit location
3004
-	 *
3005
-	 * If device is provided return device
3006
-	 * If location return location
3007
-	 *
3008
-	 * result will be false or array of:
3009
-	 * 	- type => "devices" / "locations"
3010
-	 *  - icon => "fa-desktop / fa-map"
3011
-	 *  - id => $id
3012
-	 *  - name => "location or device name"
3013
-	 *  - location => "location index or NULL"
3014
-	 *  - rack => "NULL if location, rack_id if device is set with rack otherwise NULL"
3015
-	 *
3016
-	 * @method reformat_circuit_location
3017
-	 *
3018
-	 * @param  int $deviceId
3019
-	 * @param  int $locationId
3020
-	 *
3021
-	 * @return false|array
3022
-	 */
3023
-	public function reformat_circuit_location ($deviceId = null, $locationId = null) {
3024
-		// check device
3025
-		if(is_numeric($deviceId) && $deviceId!=0) {
3026
-			// fetch device
3027
-			$device = $this->fetch_object ("devices", "id", $deviceId);
3028
-			// check
3029
-			if ($device === false) {
3030
-				return false;
3031
-			}
3032
-			else {
3033
-				$array = array (
3034
-								"type"     => "devices",
3035
-								"id"       => $device->id,
3036
-								"name"     => $device->hostname,
3037
-								"icon" 	   => "",
3038
-								"location" => is_null($device->location)||$device->location==0 ? NULL : $device->location,
3039
-								"rack"     => is_null($device->rack)||$device->rack==0 ? NULL : $device->rack
3040
-				                );
3041
-				// check rack location if not configured
3042
-				if ($array['location']==NULL && $array['rack']!=NULL) {
3043
-					$rack_location = $this->fetch_object ("racks", "id", $array['rack']);
3044
-					$array['location'] = $rack_location!==false ? $rack_location->location : NULL;
3045
-				}
3046
-				// result
3047
-				return $array;
3048
-			}
3049
-		}
3050
-		// check location
3051
-		elseif (is_numeric($locationId) && $locationId!=0) {
3052
-			// fetch location
3053
-			$location = $this->fetch_object ("locations", "id", $locationId);
3054
-			// check
3055
-			if ($device === false) {
3056
-				return false;
3057
-			}
3058
-			else {
3059
-				$array = array (
3060
-								"type"     => "locations",
3061
-								"id"       => $location->id,
3062
-								"name"     => $location->name,
3063
-								"icon" 	   => "fa-map",
3064
-								"location" => $location->id,
3065
-								"rack"     => NULL
3066
-				                );
3067
-				return $array;
3068
-			}
3069
-		}
3070
-		else {
3071
-			return false;
3072
-		}
3073
-	}
3074
-
3075
-	/**
3076
-	 * Fetch all l2 domans and vlans
3077
-	 *
3078
-	 * @access public
3079
-	 * @param string $search (default: false)
3080
-	 * @return array|bool
3081
-	 */
3082
-	public function fetch_all_domains_and_vlans ($search = false) {
3083
-		// set query
3084
-		$query[] = "select `d`.`name` as `domainName`,";
3085
-		$query[] = "	`d`.`description` as `domainDescription`,";
3086
-		$query[] = "	`v`.`domainId` as `domainId`,";
3087
-		$query[] = "	`v`.`name` as `name`,";
3088
-		$query[] = "	`d`.`name` as `domainName`,";
3089
-		$query[] = "	`v`.`number` as `number`,";
3090
-		$query[] = "	`v`.`description` as `description`,";
3091
-		$query[] = "	`v`.`customer_id` as `customer_id`,";
3092
-		// fetch custom fields
3093
-		$custom_vlan_fields = $this->fetch_custom_fields ("vlans");
3094
-		if ($custom_vlan_fields != false) {
3095
-    		foreach ($custom_vlan_fields as $f) {
3096
-        		$query[] = "  `v`.`$f[name]` as `$f[name]`,";
3097
-    		}
3098
-
3099
-		}
3100
-		$query[] = "	`v`.`vlanId` as `id`";
3101
-		$query[] = "	from";
3102
-		$query[] = "	`vlans` as `v`,";
3103
-		$query[] = "	`vlanDomains` as `d`";
3104
-		$query[] = "	where `v`.`domainId` = `d`.`id`";
3105
-		$query[] = "	order by `v`.`number` asc;";
3106
-
3107
-		// fetch
3108
-		try { $domains = $this->Database->getObjectsQuery(implode("\n",$query)); }
3109
-		catch (Exception $e) { $this->Result->show("danger", $e->getMessage(), true); }
3110
-		// filter if requested
3111
-		if ($search !== false && sizeof($domains)>0) {
3112
-			foreach ($domains as $k=>$d) {
3113
-				if (strpos($d->number, $search)===false && strpos($d->name, $search)===false && strpos($d->description, $search)===false) {
3114
-					unset($domains[$k]);
3115
-				}
3116
-			}
3117
-		}
3118
-		// return
3119
-		return sizeof($domains)>0 ? $domains : false;
3120
-	}
3121
-
3122
-	/**
3123
-	 * Fetch all objects belonging to customer
3124
-	 *
3125
-	 * @method fetch_customer_objects
3126
-	 * @param  int $customer_id
3127
-	 * @return void
3128
-	 */
3129
-	public function fetch_customer_objects ($customer_id) {
3130
-		// out
3131
-		$out = [];
3132
-		// fetch
3133
-		if(is_numeric($customer_id)) {
3134
-			foreach ($this->get_customer_object_types() as $table=>$name) {
3135
-				$objects = $this->fetch_multiple_objects ($table, "customer_id", $customer_id, $this->get_customer_object_types_sorts ($table));
3136
-				if ($objects!==false) {
3137
-					$out[$table] = $objects;
3138
-				}
3139
-			}
3140
-		}
3141
-		// return
3142
-		return $out;
3143
-	}
3144
-
3145
-	/**
3146
-	 * Return all possible customer object relations
3147
-	 *
3148
-	 * @method get_customer_object_types
3149
-	 * @return array
3150
-	 */
3151
-	public function get_customer_object_types () {
3152
-		return [
3153
-				"subnets"     => "Subnets",
3154
-				"ipaddresses" => "Addresses",
3155
-				"vlans"       => "VLAN",
3156
-				"vrf"         => "VRF",
3157
-				"circuits"    => "Circuits",
3158
-				"racks"       => "Racks"
3159
-				];
3160
-	}
3161
-
3162
-	/**
3163
-	 * Return sorting for fetch_multiple_objects
3164
-	 *
3165
-	 * @method get_customer_object_types_sorts
3166
-	 * @param  string $type
3167
-	 * @return string
3168
-	 */
3169
-	private function get_customer_object_types_sorts ($type) {
3170
-		switch ($type) {
3171
-			case "subnets"     : return "subnet";
3172
-			case "ipaddresses" : return "ip_addr";
3173
-			case "vlans"       : return "number";
3174
-			case "vrf"         : return "name";
3175
-			case "circuits"    : return "cid";
3176
-			case "racks"       : return "name";
3177
-			default            : return "id";
3178
-		}
3179
-	}
3180
-
3181
-	/**
3182
-	 * Parses import file
3183
-	 *
3184
-	 * @access public
3185
-	 * @param string $filetype (default: "xls")
3186
-	 * @param object $subnet
3187
-	 * @param array $custom_address_fields
3188
-	 * @return array
3189
-	 */
3190
-	public function parse_import_file ($filetype = "xls", $subnet = object, $custom_address_fields) {
3191
-    	# start object and get settings
3192
-    	$this->settings ();
3193
-    	$this->Subnets = new Subnets ($this->Database);
2993
+        // fetch
2994
+        try { $circuits = $this->Database->getObjectsQuery($query, array("deviceid"=>$device_id)); }
2995
+        catch (Exception $e) {
2996
+            $this->Result->show("danger", $e->getMessage(), true);
2997
+        }
2998
+        // return
2999
+        return sizeof($circuits)>0 ? $circuits : false;
3000
+    }
3001
+
3002
+    /**
3003
+     * Reformat circuit location
3004
+     *
3005
+     * If device is provided return device
3006
+     * If location return location
3007
+     *
3008
+     * result will be false or array of:
3009
+     * 	- type => "devices" / "locations"
3010
+     *  - icon => "fa-desktop / fa-map"
3011
+     *  - id => $id
3012
+     *  - name => "location or device name"
3013
+     *  - location => "location index or NULL"
3014
+     *  - rack => "NULL if location, rack_id if device is set with rack otherwise NULL"
3015
+     *
3016
+     * @method reformat_circuit_location
3017
+     *
3018
+     * @param  int $deviceId
3019
+     * @param  int $locationId
3020
+     *
3021
+     * @return false|array
3022
+     */
3023
+    public function reformat_circuit_location ($deviceId = null, $locationId = null) {
3024
+        // check device
3025
+        if(is_numeric($deviceId) && $deviceId!=0) {
3026
+            // fetch device
3027
+            $device = $this->fetch_object ("devices", "id", $deviceId);
3028
+            // check
3029
+            if ($device === false) {
3030
+                return false;
3031
+            }
3032
+            else {
3033
+                $array = array (
3034
+                                "type"     => "devices",
3035
+                                "id"       => $device->id,
3036
+                                "name"     => $device->hostname,
3037
+                                "icon" 	   => "",
3038
+                                "location" => is_null($device->location)||$device->location==0 ? NULL : $device->location,
3039
+                                "rack"     => is_null($device->rack)||$device->rack==0 ? NULL : $device->rack
3040
+                                );
3041
+                // check rack location if not configured
3042
+                if ($array['location']==NULL && $array['rack']!=NULL) {
3043
+                    $rack_location = $this->fetch_object ("racks", "id", $array['rack']);
3044
+                    $array['location'] = $rack_location!==false ? $rack_location->location : NULL;
3045
+                }
3046
+                // result
3047
+                return $array;
3048
+            }
3049
+        }
3050
+        // check location
3051
+        elseif (is_numeric($locationId) && $locationId!=0) {
3052
+            // fetch location
3053
+            $location = $this->fetch_object ("locations", "id", $locationId);
3054
+            // check
3055
+            if ($device === false) {
3056
+                return false;
3057
+            }
3058
+            else {
3059
+                $array = array (
3060
+                                "type"     => "locations",
3061
+                                "id"       => $location->id,
3062
+                                "name"     => $location->name,
3063
+                                "icon" 	   => "fa-map",
3064
+                                "location" => $location->id,
3065
+                                "rack"     => NULL
3066
+                                );
3067
+                return $array;
3068
+            }
3069
+        }
3070
+        else {
3071
+            return false;
3072
+        }
3073
+    }
3074
+
3075
+    /**
3076
+     * Fetch all l2 domans and vlans
3077
+     *
3078
+     * @access public
3079
+     * @param string $search (default: false)
3080
+     * @return array|bool
3081
+     */
3082
+    public function fetch_all_domains_and_vlans ($search = false) {
3083
+        // set query
3084
+        $query[] = "select `d`.`name` as `domainName`,";
3085
+        $query[] = "	`d`.`description` as `domainDescription`,";
3086
+        $query[] = "	`v`.`domainId` as `domainId`,";
3087
+        $query[] = "	`v`.`name` as `name`,";
3088
+        $query[] = "	`d`.`name` as `domainName`,";
3089
+        $query[] = "	`v`.`number` as `number`,";
3090
+        $query[] = "	`v`.`description` as `description`,";
3091
+        $query[] = "	`v`.`customer_id` as `customer_id`,";
3092
+        // fetch custom fields
3093
+        $custom_vlan_fields = $this->fetch_custom_fields ("vlans");
3094
+        if ($custom_vlan_fields != false) {
3095
+            foreach ($custom_vlan_fields as $f) {
3096
+                $query[] = "  `v`.`$f[name]` as `$f[name]`,";
3097
+            }
3098
+
3099
+        }
3100
+        $query[] = "	`v`.`vlanId` as `id`";
3101
+        $query[] = "	from";
3102
+        $query[] = "	`vlans` as `v`,";
3103
+        $query[] = "	`vlanDomains` as `d`";
3104
+        $query[] = "	where `v`.`domainId` = `d`.`id`";
3105
+        $query[] = "	order by `v`.`number` asc;";
3106
+
3107
+        // fetch
3108
+        try { $domains = $this->Database->getObjectsQuery(implode("\n",$query)); }
3109
+        catch (Exception $e) { $this->Result->show("danger", $e->getMessage(), true); }
3110
+        // filter if requested
3111
+        if ($search !== false && sizeof($domains)>0) {
3112
+            foreach ($domains as $k=>$d) {
3113
+                if (strpos($d->number, $search)===false && strpos($d->name, $search)===false && strpos($d->description, $search)===false) {
3114
+                    unset($domains[$k]);
3115
+                }
3116
+            }
3117
+        }
3118
+        // return
3119
+        return sizeof($domains)>0 ? $domains : false;
3120
+    }
3121
+
3122
+    /**
3123
+     * Fetch all objects belonging to customer
3124
+     *
3125
+     * @method fetch_customer_objects
3126
+     * @param  int $customer_id
3127
+     * @return void
3128
+     */
3129
+    public function fetch_customer_objects ($customer_id) {
3130
+        // out
3131
+        $out = [];
3132
+        // fetch
3133
+        if(is_numeric($customer_id)) {
3134
+            foreach ($this->get_customer_object_types() as $table=>$name) {
3135
+                $objects = $this->fetch_multiple_objects ($table, "customer_id", $customer_id, $this->get_customer_object_types_sorts ($table));
3136
+                if ($objects!==false) {
3137
+                    $out[$table] = $objects;
3138
+                }
3139
+            }
3140
+        }
3141
+        // return
3142
+        return $out;
3143
+    }
3144
+
3145
+    /**
3146
+     * Return all possible customer object relations
3147
+     *
3148
+     * @method get_customer_object_types
3149
+     * @return array
3150
+     */
3151
+    public function get_customer_object_types () {
3152
+        return [
3153
+                "subnets"     => "Subnets",
3154
+                "ipaddresses" => "Addresses",
3155
+                "vlans"       => "VLAN",
3156
+                "vrf"         => "VRF",
3157
+                "circuits"    => "Circuits",
3158
+                "racks"       => "Racks"
3159
+                ];
3160
+    }
3161
+
3162
+    /**
3163
+     * Return sorting for fetch_multiple_objects
3164
+     *
3165
+     * @method get_customer_object_types_sorts
3166
+     * @param  string $type
3167
+     * @return string
3168
+     */
3169
+    private function get_customer_object_types_sorts ($type) {
3170
+        switch ($type) {
3171
+            case "subnets"     : return "subnet";
3172
+            case "ipaddresses" : return "ip_addr";
3173
+            case "vlans"       : return "number";
3174
+            case "vrf"         : return "name";
3175
+            case "circuits"    : return "cid";
3176
+            case "racks"       : return "name";
3177
+            default            : return "id";
3178
+        }
3179
+    }
3180
+
3181
+    /**
3182
+     * Parses import file
3183
+     *
3184
+     * @access public
3185
+     * @param string $filetype (default: "xls")
3186
+     * @param object $subnet
3187
+     * @param array $custom_address_fields
3188
+     * @return array
3189
+     */
3190
+    public function parse_import_file ($filetype = "xls", $subnet = object, $custom_address_fields) {
3191
+        # start object and get settings
3192
+        $this->settings ();
3193
+        $this->Subnets = new Subnets ($this->Database);
3194 3194
 
3195 3195
         # CSV
3196 3196
         if (strtolower($filetype) == "csv")     { $outFile = $this->parse_import_file_csv (); }
@@ -3201,163 +3201,163 @@  discard block
 block discarded – undo
3201 3201
 
3202 3202
         # validate
3203 3203
         return $this->parse_validate_file ($outFile, $subnet);
3204
-	}
3205
-
3206
-	/**
3207
-	 * Parses xls import file
3208
-	 *
3209
-	 * @access private
3210
-	 * @param object $subnet
3211
-	 * @param array $custom_address_fields
3212
-	 * @return mixed
3213
-	 */
3214
-	private function parse_import_file_xls ($subnet, $custom_address_fields) {
3215
-     	# get excel object
3216
-    	require_once(dirname(__FILE__).'/../../functions/php-excel-reader/excel_reader2.php');				//excel reader 2.21
3217
-    	$data = new Spreadsheet_Excel_Reader(dirname(__FILE__) . '/../../app/subnets/import-subnet/upload/import.xls', false, 'utf-8');
3218
-
3219
-    	//get number of rows
3220
-    	$numRows = $data->rowcount(0);
3221
-    	$numRows++;
3222
-
3223
-    	$outFile = array();
3224
-
3225
-    	// set delimiter
3226
-    	$this->csv_delimiter = ";";
3227
-
3228
-    	//get all to array!
3229
-    	for($m=0; $m < $numRows; $m++) {
3230
-
3231
-    		//IP must be present!
3232
-    		if(filter_var($data->val($m,'A'), FILTER_VALIDATE_IP)) {
3233
-        		//for multicast
3234
-        		$mac = $data->val($m,'F');
3235
-        		if ($this->settings->enableMulticast=="1") {
3236
-            		if (strlen($data->val($m,'F'))==0 && $this->Subnets->is_multicast($data->val($m,'A')))    {
3237
-                		$mac = $this->Subnets->create_multicast_mac ($data->val($m,'A'));
3204
+    }
3205
+
3206
+    /**
3207
+     * Parses xls import file
3208
+     *
3209
+     * @access private
3210
+     * @param object $subnet
3211
+     * @param array $custom_address_fields
3212
+     * @return mixed
3213
+     */
3214
+    private function parse_import_file_xls ($subnet, $custom_address_fields) {
3215
+            # get excel object
3216
+        require_once(dirname(__FILE__).'/../../functions/php-excel-reader/excel_reader2.php');				//excel reader 2.21
3217
+        $data = new Spreadsheet_Excel_Reader(dirname(__FILE__) . '/../../app/subnets/import-subnet/upload/import.xls', false, 'utf-8');
3218
+
3219
+        //get number of rows
3220
+        $numRows = $data->rowcount(0);
3221
+        $numRows++;
3222
+
3223
+        $outFile = array();
3224
+
3225
+        // set delimiter
3226
+        $this->csv_delimiter = ";";
3227
+
3228
+        //get all to array!
3229
+        for($m=0; $m < $numRows; $m++) {
3230
+
3231
+            //IP must be present!
3232
+            if(filter_var($data->val($m,'A'), FILTER_VALIDATE_IP)) {
3233
+                //for multicast
3234
+                $mac = $data->val($m,'F');
3235
+                if ($this->settings->enableMulticast=="1") {
3236
+                    if (strlen($data->val($m,'F'))==0 && $this->Subnets->is_multicast($data->val($m,'A')))    {
3237
+                        $mac = $this->Subnets->create_multicast_mac ($data->val($m,'A'));
3238
+                    }
3239
+                }
3240
+
3241
+                $outFile[$m]  = $data->val($m,'A').$this->csv_delimiter.$data->val($m,'B').$this->csv_delimiter.$data->val($m,'C').$this->csv_delimiter.$data->val($m,'D').$this->csv_delimiter;
3242
+                $outFile[$m] .= $data->val($m,'E').$this->csv_delimiter.$mac.$this->csv_delimiter.$data->val($m,'G').$this->csv_delimiter.$data->val($m,'H').$this->csv_delimiter;
3243
+                $outFile[$m] .= $data->val($m,'I').$this->csv_delimiter.$data->val($m,'J').$this->csv_delimiter.$data->val($m,'K');
3244
+                //add custom fields
3245
+                if(sizeof($custom_address_fields) > 0) {
3246
+                    $currLett = "L";
3247
+                    foreach($custom_address_fields as $field) {
3248
+                        $outFile[$m] .= $this->csv_delimiter.$data->val($m,$currLett++);
3238 3249
                     }
3239 3250
                 }
3251
+                $outFile[$m] = $this->convert_encoding_to_UTF8($outFile[$m]);
3252
+            }
3253
+        };
3254
+        // return
3255
+        return $outFile;
3256
+    }
3257
+
3258
+    /**
3259
+     * Parses CSV import file
3260
+     *
3261
+     * @access private
3262
+     * @return array
3263
+     */
3264
+    private function parse_import_file_csv () {
3265
+        // get file to string
3266
+        $handle = fopen(dirname(__FILE__) . '/../../app/subnets/import-subnet/upload/import.csv', "r");
3267
+        if ($handle) {
3268
+            while (($outFile[] = fgets($handle)) !== false) {}
3269
+            fclose($handle);
3270
+        } else {
3271
+            $this->Result->show("danger", _('Cannot open upload/import.csv'), true);
3272
+        }
3273
+
3274
+        // delimiter
3275
+        if(isset($outFile[0]))
3276
+        $this->set_csv_delimiter ($outFile[0]);
3240 3277
 
3241
-    			$outFile[$m]  = $data->val($m,'A').$this->csv_delimiter.$data->val($m,'B').$this->csv_delimiter.$data->val($m,'C').$this->csv_delimiter.$data->val($m,'D').$this->csv_delimiter;
3242
-    			$outFile[$m] .= $data->val($m,'E').$this->csv_delimiter.$mac.$this->csv_delimiter.$data->val($m,'G').$this->csv_delimiter.$data->val($m,'H').$this->csv_delimiter;
3243
-    			$outFile[$m] .= $data->val($m,'I').$this->csv_delimiter.$data->val($m,'J').$this->csv_delimiter.$data->val($m,'K');
3244
-    			//add custom fields
3245
-    			if(sizeof($custom_address_fields) > 0) {
3246
-    				$currLett = "L";
3247
-    				foreach($custom_address_fields as $field) {
3248
-    					$outFile[$m] .= $this->csv_delimiter.$data->val($m,$currLett++);
3249
-    				}
3250
-    			}
3251
-    			$outFile[$m] = $this->convert_encoding_to_UTF8($outFile[$m]);
3252
-    		}
3253
-    	};
3254
-    	// return
3255
-    	return $outFile;
3256
-	}
3257
-
3258
-	/**
3259
-	 * Parses CSV import file
3260
-	 *
3261
-	 * @access private
3262
-	 * @return array
3263
-	 */
3264
-	private function parse_import_file_csv () {
3265
-    	// get file to string
3266
-		$handle = fopen(dirname(__FILE__) . '/../../app/subnets/import-subnet/upload/import.csv', "r");
3267
-		if ($handle) {
3268
-		    while (($outFile[] = fgets($handle)) !== false) {}
3269
-		    fclose($handle);
3270
-		} else {
3271
-		    $this->Result->show("danger", _('Cannot open upload/import.csv'), true);
3272
-		}
3273
-
3274
-    	// delimiter
3275
-    	if(isset($outFile[0]))
3276
-    	$this->set_csv_delimiter ($outFile[0]);
3277
-
3278
-    	/* validate IP */
3279
-    	foreach($outFile as $k=>$v) {
3280
-        	//put it to array
3281
-        	$field = str_getcsv ($v, $this->csv_delimiter);
3282
-
3283
-        	if(!filter_var($field[0], FILTER_VALIDATE_IP)) {
3284
-            	unset($outFile[$k]);
3285
-            	unset($field);
3286
-        	}
3287
-        	else {
3288
-            	# mac
3289
-        		if ($this->settings->enableMulticast=="1") {
3290
-            		if (strlen($field[5])==0 && $this->Subnets->is_multicast($field[0]))  {
3291
-                		$field[5] = $this->Subnets->create_multicast_mac ($field[0]);
3278
+        /* validate IP */
3279
+        foreach($outFile as $k=>$v) {
3280
+            //put it to array
3281
+            $field = str_getcsv ($v, $this->csv_delimiter);
3282
+
3283
+            if(!filter_var($field[0], FILTER_VALIDATE_IP)) {
3284
+                unset($outFile[$k]);
3285
+                unset($field);
3286
+            }
3287
+            else {
3288
+                # mac
3289
+                if ($this->settings->enableMulticast=="1") {
3290
+                    if (strlen($field[5])==0 && $this->Subnets->is_multicast($field[0]))  {
3291
+                        $field[5] = $this->Subnets->create_multicast_mac ($field[0]);
3292 3292
                     }
3293
-        		}
3294
-        	}
3295
-
3296
-        	# save
3297
-        	if(isset($field)) {
3298
-	        	$outFile[$k] = implode($this->csv_delimiter, $field);
3299
-    		}
3300
-    	}
3301
-
3302
-    	# return
3303
-    	return $outFile;
3304
-	}
3305
-
3306
-	/**
3307
-	 * Detects CSV delimiter
3308
-	 *
3309
-	 * @method set_csv_delimiter
3310
-	 * @param  string $outFile
3311
-	 * @return string
3312
-	 */
3313
-	public function set_csv_delimiter ($outFile) {
3314
-		// must be string
3315
-		if(is_string($outFile)) {
3316
-			// count occurences
3317
-			$cnt_coma  = substr_count($outFile, ",");
3318
-			$cnt_colon = substr_count($outFile, ";");
3319
-			// set higher
3320
-			$this->csv_delimiter = $cnt_coma > $cnt_colon ? "," : ";";
3321
-		}
3322
-		else {
3323
-			$this->csv_delimiter = ",";
3324
-		}
3325
-	}
3326
-
3327
-	/**
3328
-	 * Validates each import line from provided array
3329
-	 *
3330
-	 *      append class to array
3331
-	 *
3332
-	 * @access private
3333
-	 * @param mixed $outFile
3334
-	 * @param object $subnet
3335
-	 * @return void
3336
-	 */
3337
-	private function parse_validate_file ($outFile = array(), $subnet = object) {
3338
-    	$result = array();
3339
-    	# present ?
3340
-    	if (sizeof($outFile)>0) {
3293
+                }
3294
+            }
3295
+
3296
+            # save
3297
+            if(isset($field)) {
3298
+                $outFile[$k] = implode($this->csv_delimiter, $field);
3299
+            }
3300
+        }
3301
+
3302
+        # return
3303
+        return $outFile;
3304
+    }
3305
+
3306
+    /**
3307
+     * Detects CSV delimiter
3308
+     *
3309
+     * @method set_csv_delimiter
3310
+     * @param  string $outFile
3311
+     * @return string
3312
+     */
3313
+    public function set_csv_delimiter ($outFile) {
3314
+        // must be string
3315
+        if(is_string($outFile)) {
3316
+            // count occurences
3317
+            $cnt_coma  = substr_count($outFile, ",");
3318
+            $cnt_colon = substr_count($outFile, ";");
3319
+            // set higher
3320
+            $this->csv_delimiter = $cnt_coma > $cnt_colon ? "," : ";";
3321
+        }
3322
+        else {
3323
+            $this->csv_delimiter = ",";
3324
+        }
3325
+    }
3326
+
3327
+    /**
3328
+     * Validates each import line from provided array
3329
+     *
3330
+     *      append class to array
3331
+     *
3332
+     * @access private
3333
+     * @param mixed $outFile
3334
+     * @param object $subnet
3335
+     * @return void
3336
+     */
3337
+    private function parse_validate_file ($outFile = array(), $subnet = object) {
3338
+        $result = array();
3339
+        # present ?
3340
+        if (sizeof($outFile)>0) {
3341 3341
             foreach($outFile as $k=>$line) {
3342 3342
 
3343
-            	//convert encoding if necessary
3344
-            	$line = $this->convert_encoding_to_UTF8($line);
3343
+                //convert encoding if necessary
3344
+                $line = $this->convert_encoding_to_UTF8($line);
3345 3345
 
3346
-            	//put it to array
3347
-            	$field = str_getcsv ($line, $this->csv_delimiter);
3346
+                //put it to array
3347
+                $field = str_getcsv ($line, $this->csv_delimiter);
3348 3348
 
3349
-            	//verify IP address
3350
-            	if(!filter_var($field[0], FILTER_VALIDATE_IP)) 	{ $class = "danger";	$errors++; }
3351
-            	else											{ $class = ""; }
3349
+                //verify IP address
3350
+                if(!filter_var($field[0], FILTER_VALIDATE_IP)) 	{ $class = "danger";	$errors++; }
3351
+                else											{ $class = ""; }
3352 3352
 
3353
-            	// verify that address is in subnet for subnets
3354
-            	if($subnet->isFolder!="1") {
3355
-					// check if IP is IPv4 or IPv6
3356
-					$ipsm = "32";
3357
-                	if (!filter_var($field[0], FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) === false) { $ipsm = "128"; }
3353
+                // verify that address is in subnet for subnets
3354
+                if($subnet->isFolder!="1") {
3355
+                    // check if IP is IPv4 or IPv6
3356
+                    $ipsm = "32";
3357
+                    if (!filter_var($field[0], FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) === false) { $ipsm = "128"; }
3358 3358
                     if ($this->Subnets->is_subnet_inside_subnet ($field[0]."/" . $ipsm, $this->transform_address($subnet->subnet, "dotted")."/".$subnet->mask)==false)    { $class = "danger"; $errors++; }
3359 3359
                 }
3360
-            	// make sure mac does not exist
3360
+                // make sure mac does not exist
3361 3361
                 if ($this->settings->enableMulticast=="1" && strlen($class)==0) {
3362 3362
                     if (strlen($field[5])>0 && $this->Subnets->is_multicast($field[0])) {
3363 3363
                         if($this->Subnets->validate_multicast_mac ($field[5], $subnet->sectionId, $subnet->vlanId, MCUNIQUE)!==true) {
@@ -3376,106 +3376,106 @@  discard block
 block discarded – undo
3376 3376
 
3377 3377
         # return
3378 3378
         return $result;
3379
-	}
3380
-
3381
-	/**
3382
-	 * Counts number of IP addresses for statistics
3383
-	 *
3384
-	 * @access public
3385
-	 * @param string $type (default: "IPv4")
3386
-	 * @return int
3387
-	 */
3388
-	public function count_subnets ($type="IPv4") {
3389
-		# set proper query
3390
-		if($type=="IPv4")		{ $query = 'select count(*) as count from `ipaddresses` where cast(`ip_addr` as UNSIGNED) <= 4294967295;'; }
3391
-		elseif($type=="IPv6")	{ $query = 'select count(*) as count from `ipaddresses` where cast(`ip_addr` as UNSIGNED) >  4294967295;'; }
3392
-
3393
-		try { $count = $this->Database->getObjectQuery($query); }
3394
-		catch (Exception $e) { $this->Result->show("danger", $e->getMessage(), true); }
3395
-
3396
-		/* return true if it exists */
3397
-		return $count->count;
3398
-	}
3399
-
3400
-	/**
3401
-	 * Fetches top subnets for dashboard graphs
3402
-	 *
3403
-	 * @access public
3404
-	 * @param mixed $type
3405
-	 * @param string $limit (default: "10")
3406
-	 * @param bool $perc (default: false)
3407
-	 * @return array
3408
-	 */
3409
-	public function fetch_top_subnets ($type, $limit = "10", $perc = false) {
3410
-		# set limit & IPv4/IPv6 selector
3411
-		$limit = $limit<=0 ? '' : 'LIMIT '. (int) $limit;
3412
-		$type_operator = ($type === 'IPv6') ? '>' : '<=';
3413
-		$type_max_mask = ($type === 'IPv6') ? '128' : '32';
3414
-		$strict_mode   = ($type === 'IPv6') ? '0' : '2';
3415
-
3416
-		if($perc) {
3417
-			$query = "SELECT SQL_CACHE s.sectionId,s.id,s.subnet,mask,IF(char_length(s.description)>0,s.description,'No description') AS description,
3379
+    }
3380
+
3381
+    /**
3382
+     * Counts number of IP addresses for statistics
3383
+     *
3384
+     * @access public
3385
+     * @param string $type (default: "IPv4")
3386
+     * @return int
3387
+     */
3388
+    public function count_subnets ($type="IPv4") {
3389
+        # set proper query
3390
+        if($type=="IPv4")		{ $query = 'select count(*) as count from `ipaddresses` where cast(`ip_addr` as UNSIGNED) <= 4294967295;'; }
3391
+        elseif($type=="IPv6")	{ $query = 'select count(*) as count from `ipaddresses` where cast(`ip_addr` as UNSIGNED) >  4294967295;'; }
3392
+
3393
+        try { $count = $this->Database->getObjectQuery($query); }
3394
+        catch (Exception $e) { $this->Result->show("danger", $e->getMessage(), true); }
3395
+
3396
+        /* return true if it exists */
3397
+        return $count->count;
3398
+    }
3399
+
3400
+    /**
3401
+     * Fetches top subnets for dashboard graphs
3402
+     *
3403
+     * @access public
3404
+     * @param mixed $type
3405
+     * @param string $limit (default: "10")
3406
+     * @param bool $perc (default: false)
3407
+     * @return array
3408
+     */
3409
+    public function fetch_top_subnets ($type, $limit = "10", $perc = false) {
3410
+        # set limit & IPv4/IPv6 selector
3411
+        $limit = $limit<=0 ? '' : 'LIMIT '. (int) $limit;
3412
+        $type_operator = ($type === 'IPv6') ? '>' : '<=';
3413
+        $type_max_mask = ($type === 'IPv6') ? '128' : '32';
3414
+        $strict_mode   = ($type === 'IPv6') ? '0' : '2';
3415
+
3416
+        if($perc) {
3417
+            $query = "SELECT SQL_CACHE s.sectionId,s.id,s.subnet,mask,IF(char_length(s.description)>0,s.description,'No description') AS description,
3418 3418
 					COUNT(*) AS `usage`,ROUND(COUNT(*)/(POW(2,$type_max_mask-`mask`)-$strict_mode)*100,2) AS `percentage` FROM `ipaddresses` AS `i`
3419 3419
 					LEFT JOIN `subnets` AS `s` ON i.subnetId = s.id
3420 3420
 					WHERE s.mask < ($type_max_mask-1) AND CAST(s.subnet AS UNSIGNED) $type_operator 4294967295
3421 3421
 					GROUP BY i.subnetId
3422 3422
 					ORDER BY `percentage` DESC $limit;";
3423
-		} else {
3424
-			$query = "SELECT SQL_CACHE s.sectionId,s.id,s.subnet,mask,IF(char_length(s.description)>0,s.description,'No description') AS description,
3423
+        } else {
3424
+            $query = "SELECT SQL_CACHE s.sectionId,s.id,s.subnet,mask,IF(char_length(s.description)>0,s.description,'No description') AS description,
3425 3425
 					COUNT(*) AS `usage` FROM `ipaddresses` AS `i`
3426 3426
 					LEFT JOIN `subnets` AS `s` ON i.subnetId = s.id
3427 3427
 					WHERE CAST(s.subnet AS UNSIGNED) $type_operator 4294967295
3428 3428
 					GROUP BY i.subnetId
3429 3429
 					ORDER BY `usage` DESC $limit;";
3430
-		}
3431
-
3432
-		try { $stats = $this->Database->getObjectsQuery($query); }
3433
-		catch (Exception $e) { !$this->debugging ? : $this->Result->show("danger", $e->getMessage(), true);	return false; }
3434
-
3435
-		# return subnets array
3436
-		return (array) $stats;
3437
-	}
3438
-
3439
-	/**
3440
-	 * Fetches all addresses to export to hosts file
3441
-	 *
3442
-	 * @access public
3443
-	 * @return array
3444
-	 */
3445
-	public function fetch_addresses_for_export () {
3446
-		# fetch
3447
-	    try { $addresses = $this->Database->getObjectsQuery("select `id`,`subnetId`,`ip_addr`,`hostname` from `ipaddresses` where length(`hostname`)>1 order by `subnetId` asc;"); }
3448
-		catch (Exception $e) { $this->Result->show("danger", $e->getMessage(), false);	return false; }
3449
-		# return result
3450
-		return $addresses;
3451
-	}
3452
-
3453
-	/**
3454
-	 * Verify that translation exists
3455
-	 *
3456
-	 * @access public
3457
-	 * @param mixed $code		//lang code
3458
-	 * @return bool
3459
-	 */
3460
-	public function verify_translation ($code) {
3461
-		//verify that proper files exist
3462
-		return !file_exists("functions/locale/$code/LC_MESSAGES/phpipam.mo") ? false : true;
3463
-	}
3464
-
3465
-	/**
3466
-	 * Fetches translation version from code
3467
-	 *
3468
-	 * @access public
3469
-	 * @param mixed $code		//lang code
3470
-	 * @return string
3471
-	 */
3472
-	public function get_translation_version ($code) {
3473
-		//check for version
3474
-		$ver = shell_exec("grep 'Project-Id-Version:' ".dirname(__FILE__)."/../locale/$code/LC_MESSAGES/phpipam.po");
3475
-		//parse
3476
-		$ver = str_replace(array("Project-Id-Version:", " ", '"', "#",'\n', ":"), "", $ver);
3477
-		//return version
3478
-		return $ver;
3479
-	}
3430
+        }
3431
+
3432
+        try { $stats = $this->Database->getObjectsQuery($query); }
3433
+        catch (Exception $e) { !$this->debugging ? : $this->Result->show("danger", $e->getMessage(), true);	return false; }
3434
+
3435
+        # return subnets array
3436
+        return (array) $stats;
3437
+    }
3438
+
3439
+    /**
3440
+     * Fetches all addresses to export to hosts file
3441
+     *
3442
+     * @access public
3443
+     * @return array
3444
+     */
3445
+    public function fetch_addresses_for_export () {
3446
+        # fetch
3447
+        try { $addresses = $this->Database->getObjectsQuery("select `id`,`subnetId`,`ip_addr`,`hostname` from `ipaddresses` where length(`hostname`)>1 order by `subnetId` asc;"); }
3448
+        catch (Exception $e) { $this->Result->show("danger", $e->getMessage(), false);	return false; }
3449
+        # return result
3450
+        return $addresses;
3451
+    }
3452
+
3453
+    /**
3454
+     * Verify that translation exists
3455
+     *
3456
+     * @access public
3457
+     * @param mixed $code		//lang code
3458
+     * @return bool
3459
+     */
3460
+    public function verify_translation ($code) {
3461
+        //verify that proper files exist
3462
+        return !file_exists("functions/locale/$code/LC_MESSAGES/phpipam.mo") ? false : true;
3463
+    }
3464
+
3465
+    /**
3466
+     * Fetches translation version from code
3467
+     *
3468
+     * @access public
3469
+     * @param mixed $code		//lang code
3470
+     * @return string
3471
+     */
3472
+    public function get_translation_version ($code) {
3473
+        //check for version
3474
+        $ver = shell_exec("grep 'Project-Id-Version:' ".dirname(__FILE__)."/../locale/$code/LC_MESSAGES/phpipam.po");
3475
+        //parse
3476
+        $ver = str_replace(array("Project-Id-Version:", " ", '"', "#",'\n', ":"), "", $ver);
3477
+        //return version
3478
+        return $ver;
3479
+    }
3480 3480
 
3481 3481
 }
Please login to merge, or discard this patch.
Spacing   +511 added lines, -511 removed lines patch added patch discarded remove patch
@@ -94,13 +94,13 @@  discard block
 block discarded – undo
94 94
 	 *
95 95
 	 * @access public
96 96
 	 */
97
-	public function __construct (Database_PDO $database) {
97
+	public function __construct(Database_PDO $database) {
98 98
 		# set database object
99 99
 		$this->Database = $database;
100 100
 		# initialize Result
101
-		$this->Result = new Result ();
101
+		$this->Result = new Result();
102 102
 		# set debugging
103
-		$this->set_debugging ();
103
+		$this->set_debugging();
104 104
 	}
105 105
 
106 106
 
@@ -125,14 +125,14 @@  discard block
 block discarded – undo
125 125
 	 * @param int $domainId (default: 1)
126 126
 	 * @return array|bool
127 127
 	 */
128
-	public function fetch_vlans_and_subnets ($domainId=1) {
128
+	public function fetch_vlans_and_subnets($domainId = 1) {
129 129
 	    # custom fields
130 130
 	    $custom_fields = $this->fetch_custom_fields("vlans");
131 131
 		# if set add to query
132 132
 		$custom_fields_query = "";
133
-	    if(sizeof($custom_fields)>0) {
134
-			foreach($custom_fields as $myField) {
135
-				$custom_fields_query  .= ',`vlans`.`'.$myField['name'].'`';
133
+	    if (sizeof($custom_fields) > 0) {
134
+			foreach ($custom_fields as $myField) {
135
+				$custom_fields_query .= ',`vlans`.`'.$myField['name'].'`';
136 136
 			}
137 137
 		}
138 138
 	    # set query
@@ -164,14 +164,14 @@  discard block
 block discarded – undo
164 164
 	 * @param int $number
165 165
 	 * @return mixed|bool
166 166
 	 */
167
-	public function validate_vlan ($number) {
167
+	public function validate_vlan($number) {
168 168
 		# fetch highest vlan id
169 169
 		$settings = $this->get_settings();
170 170
 
171
-		if(empty($number)) 							{ return true; }
172
-		elseif(!is_numeric($number)) 				{ return _('VLAN must be numeric value!'); }
173
-		elseif ($number > $settings['vlanMax']) 	{ return _('Vlan number can be max '.$settings['vlanMax']); }
174
-		else 										{ return true; }
171
+		if (empty($number)) { return true; }
172
+		elseif (!is_numeric($number)) { return _('VLAN must be numeric value!'); }
173
+		elseif ($number > $settings['vlanMax']) { return _('Vlan number can be max '.$settings['vlanMax']); }
174
+		else { return true; }
175 175
 	}
176 176
 
177 177
 
@@ -198,9 +198,9 @@  discard block
 block discarded – undo
198 198
 	 */
199 199
 	public function search_addresses($search_term, $high = "", $low = "", $custom_fields = array()) {
200 200
 
201
-    	$tags = $this->fetch_all_objects ("ipTags", "id");
201
+    	$tags = $this->fetch_all_objects("ipTags", "id");
202 202
     	foreach ($tags as $t) {
203
-        	if(strtolower($t->type)==strtolower($search_term)) {
203
+        	if (strtolower($t->type) == strtolower($search_term)) {
204 204
             	$tags = $t->id;
205 205
             	break;
206 206
         	}
@@ -209,24 +209,24 @@  discard block
 block discarded – undo
209 209
 
210 210
 		# set search query
211 211
 		$query[] = "select * from `ipaddresses` ";
212
-		$query[] = "where `ip_addr` between :low and :high ";	//ip range
213
-		$query[] = "or `hostname` like :search_term ";			//hostname
214
-		$query[] = "or `owner` like :search_term ";				//owner
212
+		$query[] = "where `ip_addr` between :low and :high "; //ip range
213
+		$query[] = "or `hostname` like :search_term "; //hostname
214
+		$query[] = "or `owner` like :search_term "; //owner
215 215
 		# custom fields
216
-		if(sizeof($custom_fields) > 0) {
217
-			foreach($custom_fields as $myField) {
216
+		if (sizeof($custom_fields) > 0) {
217
+			foreach ($custom_fields as $myField) {
218 218
 				$myField['name'] = $this->Database->escape($myField['name']);
219 219
 				$query[] = "or `$myField[name]` like :search_term ";
220 220
 			}
221 221
 		}
222 222
 		$query[] = "or `switch` like :search_term ";
223
-		$query[] = "or `port` like :search_term ";				//port search
224
-		$query[] = "or `description` like :search_term ";		//descriptions
225
-		$query[] = "or `note` like :search_term ";				//note
226
-		$query[] = "or `mac` like :search_term ";				//mac
223
+		$query[] = "or `port` like :search_term "; //port search
224
+		$query[] = "or `description` like :search_term "; //descriptions
225
+		$query[] = "or `note` like :search_term "; //note
226
+		$query[] = "or `mac` like :search_term "; //mac
227 227
 		//tag
228
-		if($tags!==false)
229
-		$query[] = "or `state` like :tags ";				//tag
228
+		if ($tags !== false)
229
+		$query[] = "or `state` like :tags "; //tag
230 230
 		$query[] = "order by `ip_addr` asc;";
231 231
 
232 232
 		# join query
@@ -258,11 +258,11 @@  discard block
 block discarded – undo
258 258
 	 */
259 259
 	public function search_subnets($search_term, $high = "", $low = "", $search_req, $custom_fields = array()) {
260 260
 		# first search if range provided
261
-		$result1 = $this->search_subnets_range  ($search_term, $high, $low, $custom_fields);
261
+		$result1 = $this->search_subnets_range($search_term, $high, $low, $custom_fields);
262 262
 		# search inside subnets even if IP does not exist!
263
-		$result2 = $this->search_subnets_inside ($high, $low);
263
+		$result2 = $this->search_subnets_inside($high, $low);
264 264
 		# search inside subnets even if IP does not exist - IPv6
265
-		$result3 = $this->search_subnets_inside_v6 ($high, $low, $search_req);
265
+		$result3 = $this->search_subnets_inside_v6($high, $low, $search_req);
266 266
 		# merge arrays
267 267
 		$result = array_merge($result1, $result2, $result3);
268 268
 	    # result
@@ -279,16 +279,16 @@  discard block
 block discarded – undo
279 279
 	 * @param mixed $custom_fields (default: array())
280 280
 	 * @return array
281 281
 	 */
282
-	private function search_subnets_range ($search_term, $high, $low, $custom_fields = array()) {
282
+	private function search_subnets_range($search_term, $high, $low, $custom_fields = array()) {
283 283
 		# reformat low/high
284
-		if($high==0 && $low==0)	{ $high = "1"; $low="1"; }
284
+		if ($high == 0 && $low == 0) { $high = "1"; $low = "1"; }
285 285
 
286 286
 		# set search query
287 287
 		$query[] = "select * from `subnets` where `description` like :search_term ";
288 288
 		$query[] = "or `subnet` between :low and :high ";
289 289
 		# custom
290
-	    if(sizeof($custom_fields) > 0) {
291
-			foreach($custom_fields as $myField) {
290
+	    if (sizeof($custom_fields) > 0) {
291
+			foreach ($custom_fields as $myField) {
292 292
 				$myField['name'] = $this->Database->escape($myField['name']);
293 293
 				$query[] = " or `$myField[name]` like :search_term ";
294 294
 			}
@@ -316,45 +316,45 @@  discard block
 block discarded – undo
316 316
 	 * @param string $low
317 317
 	 * @return array
318 318
 	 */
319
-	private function search_subnets_inside ($high, $low) {
320
-		if($low==$high) {
319
+	private function search_subnets_inside($high, $low) {
320
+		if ($low == $high) {
321 321
 			# subnets class
322
-			$Subnets = new Subnets ($this->Database);
322
+			$Subnets = new Subnets($this->Database);
323 323
 			# fetch all subnets
324 324
 			$subnets = $Subnets->fetch_all_subnets_search();
325 325
 			# loop and search
326 326
 			$ids = array();
327
-			foreach($subnets as $s) {
327
+			foreach ($subnets as $s) {
328 328
 				# cast
329 329
 				$s = (array) $s;
330 330
 
331 331
 				//first verify address type
332 332
 				$type = $this->identify_address($s['subnet']);
333 333
 
334
-				if($type == "IPv4") {
334
+				if ($type == "IPv4") {
335 335
 					# Initialize PEAR NET object
336
-					$this->initialize_pear_net_IPv4 ();
336
+					$this->initialize_pear_net_IPv4();
337 337
 					# parse address
338 338
 					$net = $this->Net_IPv4->parseAddress($this->transform_address($s['subnet']).'/'.$s['mask'], "dotted");
339 339
 
340
-					if($low>$this->transform_to_decimal(@$net->network) && $low<$this->transform_address($net->broadcast, "decimal")) {
340
+					if ($low > $this->transform_to_decimal(@$net->network) && $low < $this->transform_address($net->broadcast, "decimal")) {
341 341
 						$ids[] = $s['id'];
342 342
 					}
343 343
 				}
344 344
 			}
345 345
 			# filter
346
-			$ids = sizeof(@$ids)>0 ? array_filter($ids) : array();
346
+			$ids = sizeof(@$ids) > 0 ? array_filter($ids) : array();
347 347
 
348 348
 			$result = array();
349 349
 
350 350
 			# search
351
-			if(sizeof($ids)>0) {
352
-				foreach($ids as $id) {
351
+			if (sizeof($ids) > 0) {
352
+				foreach ($ids as $id) {
353 353
 					$result[] = $Subnets->fetch_subnet(null, $id);
354 354
 				}
355 355
 			}
356 356
 			# return
357
-			return sizeof(@$result)>0 ? array_filter($result) : array();
357
+			return sizeof(@$result) > 0 ? array_filter($result) : array();
358 358
 		}
359 359
 		else {
360 360
 			return array();
@@ -370,42 +370,42 @@  discard block
 block discarded – undo
370 370
 	 * @param string $low
371 371
 	 * @return array
372 372
 	 */
373
-	private function search_subnets_inside_v6 ($high, $low, $search_req) {
373
+	private function search_subnets_inside_v6($high, $low, $search_req) {
374 374
 		// same
375
-		if($low==$high) {
375
+		if ($low == $high) {
376 376
 			# Initialize PEAR NET object
377
-			$this->initialize_pear_net_IPv6 ();
377
+			$this->initialize_pear_net_IPv6();
378 378
 
379 379
 			// validate
380 380
 			if ($this->Net_IPv6->checkIPv6($search_req)) {
381 381
 				# subnets class
382
-				$Subnets = new Subnets ($this->Database);
382
+				$Subnets = new Subnets($this->Database);
383 383
 				# fetch all subnets
384 384
 				$subnets = $Subnets->fetch_all_subnets_search("IPv6");
385 385
 				# loop and search
386 386
 				$ids = array();
387
-				foreach($subnets as $s) {
387
+				foreach ($subnets as $s) {
388 388
 					# cast
389 389
 					$s = (array) $s;
390 390
 					# parse address
391 391
 					$net = $this->Net_IPv6->parseAddress($this->transform_address($s['subnet'], "dotted").'/'.$s['mask']);
392 392
 
393
-					if(gmp_cmp($low, $this->transform_address(@$net['start'], "decimal")) == 1 && gmp_cmp($low, $this->transform_address(@$net['end'], "decimal")) == -1) {
393
+					if (gmp_cmp($low, $this->transform_address(@$net['start'], "decimal")) == 1 && gmp_cmp($low, $this->transform_address(@$net['end'], "decimal")) == -1) {
394 394
 						$ids[] = $s['id'];
395 395
 
396 396
 					}
397 397
 				}
398 398
 				# filter
399
-				$ids = sizeof(@$ids)>0 ? array_filter($ids) : array();
399
+				$ids = sizeof(@$ids) > 0 ? array_filter($ids) : array();
400 400
 				# search
401 401
 				$result = array();
402
-				if(sizeof($ids)>0) {
403
-					foreach($ids as $id) {
402
+				if (sizeof($ids) > 0) {
403
+					foreach ($ids as $id) {
404 404
 						$result[] = $Subnets->fetch_subnet(null, $id);
405 405
 					}
406 406
 				}
407 407
 				# return
408
-				return sizeof(@$result)>0 ? array_filter($result) : array();
408
+				return sizeof(@$result) > 0 ? array_filter($result) : array();
409 409
 			}
410 410
 			// empty
411 411
 			else {
@@ -429,8 +429,8 @@  discard block
 block discarded – undo
429 429
 		# query
430 430
 		$query[] = "select * from `vlans` where `name` like :search_term or `description` like :search_term or `number` like :search_term ";
431 431
 		# custom
432
-	    if(sizeof($custom_fields) > 0) {
433
-			foreach($custom_fields as $myField) {
432
+	    if (sizeof($custom_fields) > 0) {
433
+			foreach ($custom_fields as $myField) {
434 434
 				$myField['name'] = $this->Database->escape($myField['name']);
435 435
 				$query[] = " or `$myField[name]` like :search_term ";
436 436
 			}
@@ -459,12 +459,12 @@  discard block
 block discarded – undo
459 459
 	 * @param array $custom_fields (default: array())
460 460
 	 * @return array
461 461
 	 */
462
-	public function search_vrfs ($search_term, $custom_fields = array()) {
462
+	public function search_vrfs($search_term, $custom_fields = array()) {
463 463
 		# query
464 464
 		$query[] = "select * from `vrf` where `name` like :search_term or `description` like :search_term or `rd` like :search_term ";
465 465
 		# custom
466
-	    if(sizeof($custom_fields) > 0) {
467
-			foreach($custom_fields as $myField) {
466
+	    if (sizeof($custom_fields) > 0) {
467
+			foreach ($custom_fields as $myField) {
468 468
 				$myField['name'] = $this->Database->escape($myField['name']);
469 469
 				$query[] = " or `$myField[name]` like :search_term ";
470 470
 			}
@@ -492,12 +492,12 @@  discard block
 block discarded – undo
492 492
 	 * @param array $custom_prefix_fields (default: array())
493 493
 	 * @return array
494 494
 	 */
495
-	public function search_pstn_refixes ($search_term, $custom_prefix_fields = array()) {
495
+	public function search_pstn_refixes($search_term, $custom_prefix_fields = array()) {
496 496
 		# query
497 497
 		$query[] = "select *,concat(prefix,start) as raw from `pstnPrefixes` where `prefix` like :search_term or `name` like :search_term or `description` like :search_term ";
498 498
 		# custom
499
-	    if(sizeof($custom_prefix_fields) > 0) {
500
-			foreach($custom_prefix_fields as $myField) {
499
+	    if (sizeof($custom_prefix_fields) > 0) {
500
+			foreach ($custom_prefix_fields as $myField) {
501 501
 				$myField['name'] = $this->Database->escape($myField['name']);
502 502
 				$query[] = " or `$myField[name]` like :search_term ";
503 503
 			}
@@ -525,12 +525,12 @@  discard block
 block discarded – undo
525 525
 	 * @param array $custom_prefix_fields (default: array())
526 526
 	 * @return array
527 527
 	 */
528
-	public function search_pstn_numbers ($search_term, $custom_prefix_fields = array()) {
528
+	public function search_pstn_numbers($search_term, $custom_prefix_fields = array()) {
529 529
 		# query
530 530
 		$query[] = "select * from `pstnNumbers` where `number` like :search_term or `name` like :search_term or `description` like :search_term or `owner` like :search_term ";
531 531
 		# custom
532
-	    if(sizeof($custom_prefix_fields) > 0) {
533
-			foreach($custom_prefix_fields as $myField) {
532
+	    if (sizeof($custom_prefix_fields) > 0) {
533
+			foreach ($custom_prefix_fields as $myField) {
534 534
 				$myField['name'] = $this->Database->escape($myField['name']);
535 535
 				$query[] = " or `$myField[name]` like :search_term ";
536 536
 			}
@@ -558,15 +558,15 @@  discard block
 block discarded – undo
558 558
 	 * @param array $custom_circuit_fields (default: array())
559 559
 	 * @return array
560 560
 	 */
561
-	public function search_circuits ($search_term, $custom_circuit_fields = array()) {
561
+	public function search_circuits($search_term, $custom_circuit_fields = array()) {
562 562
 		# query
563 563
 		$query[] = "select c.id,c.cid,c.type,c.device1,c.location1,c.device2,c.location2,p.name,p.description,p.contact,c.capacity,p.id as pid,c.status ";
564 564
 		$query[] = "from circuits as c, circuitProviders as p ";
565 565
 		$query[] = "where c.provider = p.id";
566 566
 		$query[] = "and (`cid` like :search_term or `type` like :search_term or `capacity` like :search_term or `comment` like :search_term or `name` like :search_term)";
567 567
 		# custom
568
-	    if(sizeof($custom_circuit_fields) > 0) {
569
-			foreach($custom_circuit_fields as $myField) {
568
+	    if (sizeof($custom_circuit_fields) > 0) {
569
+			foreach ($custom_circuit_fields as $myField) {
570 570
 				$myField['name'] = $this->Database->escape($myField['name']);
571 571
 				$query[] = " or `$myField[name]` like :search_term ";
572 572
 			}
@@ -596,12 +596,12 @@  discard block
 block discarded – undo
596 596
 	 * @param array $custom_circuit_fields (default: array())
597 597
 	 * @return array
598 598
 	 */
599
-	public function search_circuit_providers ($search_term, $custom_circuit_fields = array()) {
599
+	public function search_circuit_providers($search_term, $custom_circuit_fields = array()) {
600 600
 		# query
601 601
 		$query[] = "select * from `circuitProviders` where `name` like :search_term or `description` like :search_term or `contact` like :search_term ";
602 602
 		# custom
603
-	    if(sizeof($custom_circuit_fields) > 0) {
604
-			foreach($custom_circuit_fields as $myField) {
603
+	    if (sizeof($custom_circuit_fields) > 0) {
604
+			foreach ($custom_circuit_fields as $myField) {
605 605
 				$myField['name'] = $this->Database->escape($myField['name']);
606 606
 				$query[] = " or `$myField[name]` like :search_term ";
607 607
 			}
@@ -630,16 +630,16 @@  discard block
 block discarded – undo
630 630
 	 * @param mixed $address
631 631
 	 * @return array high/low decimal address
632 632
 	 */
633
-	public function reformat_IPv4_for_search ($address) {
633
+	public function reformat_IPv4_for_search($address) {
634 634
 		# remove % sign if present
635 635
 		$address = str_replace("%", "", $address);
636 636
 		# we need Addresses class
637
-		$Addresses = new Addresses ($this->Database);
637
+		$Addresses = new Addresses($this->Database);
638 638
 
639 639
 		# if subnet is provided we have all data
640
-		if(strpos($address, "/")>0) {
640
+		if (strpos($address, "/") > 0) {
641 641
 			# Initialize PEAR NET object
642
-			$this->initialize_pear_net_IPv4 ();
642
+			$this->initialize_pear_net_IPv4();
643 643
 			$net = $this->Net_IPv4->parseAddress($address);
644 644
 
645 645
 			$result['low']   = $Addresses->transform_to_decimal($net->network);
@@ -650,8 +650,8 @@  discard block
 block discarded – undo
650 650
 			# if subnet is not provided maybe wildcard is, so explode it to array
651 651
 			$address = explode(".", $address);
652 652
             # remove empty
653
-            foreach($address as $k=>$a) {
654
-                if (strlen($a)==0)  unset($address[$k]);
653
+            foreach ($address as $k=>$a) {
654
+                if (strlen($a) == 0)  unset($address[$k]);
655 655
             }
656 656
 
657 657
 			# 4 pieces is ok, host
@@ -665,13 +665,13 @@  discard block
 block discarded – undo
665 665
 			}
666 666
 			# 2 pieces also
667 667
 			elseif (sizeof($address) == 2) {
668
-				$result['low']  = $Addresses->transform_to_decimal(implode(".", array_merge($address, array(0,0))));
669
-				$result['high'] = $Addresses->transform_to_decimal(implode(".", array_merge($address, array(255,255))));
668
+				$result['low']  = $Addresses->transform_to_decimal(implode(".", array_merge($address, array(0, 0))));
669
+				$result['high'] = $Addresses->transform_to_decimal(implode(".", array_merge($address, array(255, 255))));
670 670
 			}
671 671
 			# 1 piece also
672 672
 			elseif (sizeof($address) == 1) {
673
-				$result['low']  = $Addresses->transform_to_decimal(implode(".", array_merge($address, array(0,0,0))));
674
-				$result['high'] = $Addresses->transform_to_decimal(implode(".", array_merge($address, array(255,255,255))));
673
+				$result['low']  = $Addresses->transform_to_decimal(implode(".", array_merge($address, array(0, 0, 0))));
674
+				$result['high'] = $Addresses->transform_to_decimal(implode(".", array_merge($address, array(255, 255, 255))));
675 675
 			}
676 676
 			# else return same value
677 677
 			else {
@@ -695,20 +695,20 @@  discard block
 block discarded – undo
695 695
 	 * @param mixed $address
696 696
 	 * @return array
697 697
 	 */
698
-	public function reformat_IPv6_for_search ($address) {
698
+	public function reformat_IPv6_for_search($address) {
699 699
 		# parse address
700
-		$this->initialize_pear_net_IPv6 ();
700
+		$this->initialize_pear_net_IPv6();
701 701
 
702 702
 		$return = array();
703 703
 
704 704
 		# validate
705
-		if ($this->Net_IPv6->checkIPv6($address)==false) {
705
+		if ($this->Net_IPv6->checkIPv6($address) == false) {
706 706
 			// return 0
707 707
 			return array("high"=>0, "low"=>0);
708 708
 		}
709 709
 		else {
710 710
 			# fake mask
711
-			if (strpos($address, "/")==0)	{ $address .= "/128"; }
711
+			if (strpos($address, "/") == 0) { $address .= "/128"; }
712 712
 
713 713
 			# parse address
714 714
 			$parsed = $this->Net_IPv6->parseAddress($address);
@@ -746,14 +746,14 @@  discard block
 block discarded – undo
746 746
 	 * @param mixed $table
747 747
 	 * @return array
748 748
 	 */
749
-	public function fetch_custom_fields ($table) {
749
+	public function fetch_custom_fields($table) {
750 750
     	# fetch columns
751
-		$fields = $this->fetch_columns ($table);
751
+		$fields = $this->fetch_columns($table);
752 752
 
753 753
 		$res = array();
754 754
 
755 755
 		# save Field values only
756
-		foreach($fields as $field) {
756
+		foreach ($fields as $field) {
757 757
 			# cast
758 758
 			$field = (array) $field;
759 759
 
@@ -765,14 +765,14 @@  discard block
 block discarded – undo
765 765
 		}
766 766
 
767 767
 		# fetch standard fields
768
-		$standard = $this->fetch_standard_fields ($table);
768
+		$standard = $this->fetch_standard_fields($table);
769 769
 
770 770
 		# remove them
771
-		foreach($standard as $st) {
771
+		foreach ($standard as $st) {
772 772
 			unset($res[$st]);
773 773
 		}
774 774
 		# return array
775
-		return sizeof($res)==0 ? array() : $res;
775
+		return sizeof($res) == 0 ? array() : $res;
776 776
 	}
777 777
 
778 778
 	/**
@@ -782,12 +782,12 @@  discard block
 block discarded – undo
782 782
 	 * @param mixed $table
783 783
 	 * @return array
784 784
 	 */
785
-	public function fetch_custom_fields_numeric ($table) {
785
+	public function fetch_custom_fields_numeric($table) {
786 786
 		# fetch all custom fields
787
-		$custom_fields = $this->fetch_custom_fields ($table);
787
+		$custom_fields = $this->fetch_custom_fields($table);
788 788
 		# make numberic array
789
-		if(sizeof($custom_fields)>0) {
790
-			foreach($custom_fields as $f) {
789
+		if (sizeof($custom_fields) > 0) {
790
+			foreach ($custom_fields as $f) {
791 791
 				$out[] = $f;
792 792
 			}
793 793
 			# result
@@ -805,14 +805,14 @@  discard block
 block discarded – undo
805 805
 	 * @param mixed $table
806 806
 	 * @return array
807 807
 	 */
808
-	private function fetch_columns ($table) {
808
+	private function fetch_columns($table) {
809 809
 		# escape method/table
810 810
 		$table = $this->Database->escape($table);
811 811
     	# fetch columns
812
-		$query    = "show full columns from `$table`;";
812
+		$query = "show full columns from `$table`;";
813 813
 		# fetch
814 814
 	    try { $fields = $this->Database->getObjectsQuery($query); }
815
-		catch (Exception $e) { $this->Result->show("danger", $e->getMessage(), false);	return false; }
815
+		catch (Exception $e) { $this->Result->show("danger", $e->getMessage(), false); return false; }
816 816
 
817 817
 		return (array) $fields;
818 818
 	}
@@ -824,7 +824,7 @@  discard block
 block discarded – undo
824 824
 	 * @return array
825 825
 	 */
826 826
 	private function read_db_schema() {
827
-		$fh = fopen(dirname(__FILE__) . '/../../db/SCHEMA.sql', 'r');
827
+		$fh = fopen(dirname(__FILE__).'/../../db/SCHEMA.sql', 'r');
828 828
 		$schema = str_replace("\r\n", "\n", fread($fh, 100000));
829 829
 		return $schema;
830 830
 	}
@@ -836,22 +836,22 @@  discard block
 block discarded – undo
836 836
 	 * @param mixed $table
837 837
 	 * @return array
838 838
 	 */
839
-	public function fetch_standard_fields ($table) {
839
+	public function fetch_standard_fields($table) {
840 840
 		# get SCHEMA.SQL file
841 841
 		$schema = $this->read_db_schema();
842 842
 
843 843
 		# get definition
844 844
 		$definition = strstr($schema, "CREATE TABLE `$table` (");
845
-		$definition = trim(strstr($definition, ";" . "\n", true));
845
+		$definition = trim(strstr($definition, ";"."\n", true));
846 846
 
847 847
 		# get each line to array
848 848
 		$definition = explode("\n", $definition);
849 849
 
850 850
 		# go through,if it begins with ` use it !
851 851
 		$out = array();
852
-		foreach($definition as $d) {
852
+		foreach ($definition as $d) {
853 853
 			$d = trim($d);
854
-			if(strpos(trim($d), "`")==0) {
854
+			if (strpos(trim($d), "`") == 0) {
855 855
 				$d = strstr(trim($d, "`"), "`", true);
856 856
 				$out[] = substr($d, strpos($d, "`"));
857 857
 			}
@@ -865,7 +865,7 @@  discard block
 block discarded – undo
865 865
 	 *
866 866
 	 * @return array
867 867
 	 */
868
-	public function fetch_standard_tables () {
868
+	public function fetch_standard_tables() {
869 869
 		# get SCHEMA.SQL file
870 870
 		$schema = $this->read_db_schema();
871 871
 
@@ -873,8 +873,8 @@  discard block
 block discarded – undo
873 873
 		$creates = explode("CREATE TABLE `", $schema);
874 874
 		# fill tables array
875 875
 		$tables = array();
876
-		foreach($creates as $k=>$c) {
877
-			if($k>0)	{ $tables[] = strstr($c, "`", true); }	//we exclude first !
876
+		foreach ($creates as $k=>$c) {
877
+			if ($k > 0) { $tables[] = strstr($c, "`", true); }	//we exclude first !
878 878
 		}
879 879
 
880 880
 		# return array of tables
@@ -891,12 +891,12 @@  discard block
 block discarded – undo
891 891
 	 * @param mixed $field
892 892
 	 * @return array
893 893
 	 */
894
-	public function fetch_full_field_definition ($table, $field) {
894
+	public function fetch_full_field_definition($table, $field) {
895 895
 		# escape field
896 896
 		$table = $this->Database->escape($table);
897 897
 		# fetch
898 898
 	    try { $field_data = $this->Database->getObjectQuery("show full columns from `$table` where `Field` = ?;", array($field)); }
899
-		catch (Exception $e) { $this->Result->show("danger", $e->getMessage(), false);	return false; }
899
+		catch (Exception $e) { $this->Result->show("danger", $e->getMessage(), false); return false; }
900 900
 		# result
901 901
 	    return($field_data);
902 902
 	}
@@ -925,22 +925,22 @@  discard block
 block discarded – undo
925 925
 	 * @param bool $inactive (default: false)
926 926
 	 * @return array
927 927
 	 */
928
-	public function fetch_widgets ($admin = false, $inactive = false) {
928
+	public function fetch_widgets($admin = false, $inactive = false) {
929 929
 
930 930
 		# inactive also - only for administration
931
-		if($inactive) 			{ $query = "select * from `widgets`; "; }
931
+		if ($inactive) { $query = "select * from `widgets`; "; }
932 932
 		else {
933 933
 			# admin?
934
-			if($admin) 			{ $query = "select * from `widgets` where `wactive` = 'yes'; "; }
935
-			else				{ $query = "select * from `widgets` where `wadminonly` = 'no' and `wactive` = 'yes'; "; }
934
+			if ($admin) { $query = "select * from `widgets` where `wactive` = 'yes'; "; }
935
+			else { $query = "select * from `widgets` where `wadminonly` = 'no' and `wactive` = 'yes'; "; }
936 936
 		}
937 937
 	    # fetch
938 938
 	    try { $widgets = $this->Database->getObjectsQuery($query); }
939
-		catch (Exception $e) { $this->Result->show("danger", $e->getMessage(), false);	return false; }
939
+		catch (Exception $e) { $this->Result->show("danger", $e->getMessage(), false); return false; }
940 940
 
941 941
 	    # reindex
942 942
 	    $wout = array();
943
-	    foreach($widgets as $w) {
943
+	    foreach ($widgets as $w) {
944 944
 			$wout[$w->wfile] = $w;
945 945
 	    }
946 946
 
@@ -954,8 +954,8 @@  discard block
 block discarded – undo
954 954
 	 * @access public
955 955
 	 * @return bool
956 956
 	 */
957
-	public function verify_widget ($file) {
958
-		return file_exists(dirname(__FILE__)."/../../app/dashboard/widgets/$file.php")||file_exists(dirname(__FILE__)."/../../app/dashboard/widgets/custom/$file.php") ? true : false;
957
+	public function verify_widget($file) {
958
+		return file_exists(dirname(__FILE__)."/../../app/dashboard/widgets/$file.php") || file_exists(dirname(__FILE__)."/../../app/dashboard/widgets/custom/$file.php") ? true : false;
959 959
 	}
960 960
 
961 961
 
@@ -978,8 +978,8 @@  discard block
 block discarded – undo
978 978
 	 * @access public
979 979
 	 * @return int|array
980 980
 	 */
981
-	public function requests_fetch ($num = true) {
982
-		return $num ? $this->requests_fetch_num () : $this->requests_fetch_objects ();
981
+	public function requests_fetch($num = true) {
982
+		return $num ? $this->requests_fetch_num() : $this->requests_fetch_objects();
983 983
 	}
984 984
 
985 985
 	/**
@@ -988,8 +988,8 @@  discard block
 block discarded – undo
988 988
 	 * @access private
989 989
 	 * @return int
990 990
 	 */
991
-	private function requests_fetch_num () {
992
-    	return $this->count_database_objects ("requests", "processed", 0);
991
+	private function requests_fetch_num() {
992
+    	return $this->count_database_objects("requests", "processed", 0);
993 993
 	}
994 994
 
995 995
 	/**
@@ -998,8 +998,8 @@  discard block
 block discarded – undo
998 998
 	 * @access private
999 999
 	 * @return array
1000 1000
 	 */
1001
-	private function requests_fetch_objects () {
1002
-    	return $this->fetch_multiple_objects ("requests", "processed", 0);
1001
+	private function requests_fetch_objects() {
1002
+    	return $this->fetch_multiple_objects("requests", "processed", 0);
1003 1003
 	}
1004 1004
 
1005 1005
 	/**
@@ -1008,12 +1008,12 @@  discard block
 block discarded – undo
1008 1008
 	 * @access public
1009 1009
 	 * @return array|null
1010 1010
 	 */
1011
-	public function requests_fetch_available_subnets () {
1011
+	public function requests_fetch_available_subnets() {
1012 1012
 		try { $subnets = $this->Database->getObjectsQuery("SELECT * FROM `subnets` where `allowRequests`=1 and `isFull` != 1 ORDER BY `subnet`;"); }
1013
-		catch (Exception $e) { $this->Result->show("danger", $e->getMessage(), false);	return false; }
1013
+		catch (Exception $e) { $this->Result->show("danger", $e->getMessage(), false); return false; }
1014 1014
 
1015 1015
 		# save
1016
-		return sizeof($subnets)>0 ? (array) $subnets : NULL;
1016
+		return sizeof($subnets) > 0 ? (array) $subnets : NULL;
1017 1017
 	}
1018 1018
 
1019 1019
 	/**
@@ -1024,9 +1024,9 @@  discard block
 block discarded – undo
1024 1024
 	 * @param mixed $values
1025 1025
 	 * @return bool
1026 1026
 	 */
1027
-	public function ip_request_send_mail ($action="new", $values) {
1027
+	public function ip_request_send_mail($action = "new", $values) {
1028 1028
 
1029
-		$this->get_settings ();
1029
+		$this->get_settings();
1030 1030
 
1031 1031
 		# try to send
1032 1032
 		try {
@@ -1037,26 +1037,26 @@  discard block
 block discarded – undo
1037 1037
 			$phpipam_mail = new phpipam_mail($this->settings, $mail_settings);
1038 1038
 
1039 1039
 			# get all users and check who to end mail to
1040
-			$recipients = $this->ip_request_get_mail_recipients ($values['subnetId']);
1040
+			$recipients = $this->ip_request_get_mail_recipients($values['subnetId']);
1041 1041
 
1042 1042
 			# add requester to cc
1043 1043
 			$recipients_requester = $values['requester'];
1044 1044
 
1045 1045
 			# reformat key / vaues
1046
-			$values = $this->ip_request_reformat_mail_values ($values);
1046
+			$values = $this->ip_request_reformat_mail_values($values);
1047 1047
 			#reformat empty
1048
-			$values = $this->reformat_empty_array_fields ($values, "/");
1048
+			$values = $this->reformat_empty_array_fields($values, "/");
1049 1049
 
1050 1050
 			# generate content
1051
-			if ($action=="new")			{ $subject	= "New IP address request"; }
1052
-			elseif ($action=="accept")	{ $subject	= "IP address request accepted"; }
1053
-			elseif ($action=="reject")	{ $subject	= "IP address request rejected"; }
1054
-			else						{ $this->Result->show("danger", _("Invalid request action"), true); }
1051
+			if ($action == "new") { $subject = "New IP address request"; }
1052
+			elseif ($action == "accept") { $subject	= "IP address request accepted"; }
1053
+			elseif ($action == "reject") { $subject	= "IP address request rejected"; }
1054
+			else { $this->Result->show("danger", _("Invalid request action"), true); }
1055 1055
 
1056 1056
 			// set html content
1057 1057
 			$content[] = "<table style='margin-left:10px;margin-top:20px;width:auto;padding:0px;border-collapse:collapse;'>";
1058 1058
 			$content[] = "<tr><td colspan='2' style='margin:0px;>$this->mail_font_style <strong>$subject</strong></font></td></tr>";
1059
-			foreach($values as $k=>$v) {
1059
+			foreach ($values as $k=>$v) {
1060 1060
 			// title search
1061 1061
 			if (preg_match("/s_title_/", $k)) {
1062 1062
 			$content[] = "<tr><td colspan='2' style='margin:0px;border-bottom:1px solid #eeeeee;'>$this->mail_font_style<strong>$v</strong></font></td></tr>";
@@ -1072,19 +1072,19 @@  discard block
 block discarded – undo
1072 1072
 			$content[] = "<tr><td style='padding-top:15px;padding-bottom:3px;text-align:right;color:#ccc;'>$this->mail_font_style Sent at ".date('Y/m/d H:i')."</font></td></tr>";
1073 1073
 			//set alt content
1074 1074
 			$content_plain[] = "$subject"."\r\n------------------------------\r\n";
1075
-			foreach($values as $k=>$v) {
1075
+			foreach ($values as $k=>$v) {
1076 1076
 			$content_plain[] = $k." => ".$v;
1077 1077
 			}
1078 1078
 			$content_plain[] = "\r\n\r\nSent at ".date('Y/m/d H:i');
1079 1079
 			$content[] = "</table>";
1080 1080
 
1081 1081
 			// set content
1082
-			$content 		= $phpipam_mail->generate_message (implode("\r\n", $content));
1083
-			$content_plain 	= implode("\r\n",$content_plain);
1082
+			$content 		= $phpipam_mail->generate_message(implode("\r\n", $content));
1083
+			$content_plain = implode("\r\n", $content_plain);
1084 1084
 
1085 1085
 			$phpipam_mail->Php_mailer->setFrom($mail_settings->mAdminMail, $mail_settings->mAdminName);
1086
-			if ($recipients!==false) {
1087
-			foreach($recipients as $r) {
1086
+			if ($recipients !== false) {
1087
+			foreach ($recipients as $r) {
1088 1088
 			$phpipam_mail->Php_mailer->addAddress(addslashes(trim($r->email)));
1089 1089
 			}
1090 1090
 			$phpipam_mail->Php_mailer->AddCC(addslashes(trim($recipients_requester)));
@@ -1115,34 +1115,34 @@  discard block
 block discarded – undo
1115 1115
 	 * @param bool|mixed $subnetId
1116 1116
 	 * @return array|bool
1117 1117
 	 */
1118
-	private function ip_request_get_mail_recipients ($subnetId = false) {
1118
+	private function ip_request_get_mail_recipients($subnetId = false) {
1119 1119
     	// fetch all users with mailNotify
1120
-        $notification_users = $this->fetch_multiple_objects ("users", "mailNotify", "Yes", "id", true);
1120
+        $notification_users = $this->fetch_multiple_objects("users", "mailNotify", "Yes", "id", true);
1121 1121
         // recipients array
1122 1122
         $recipients = array();
1123 1123
         // any ?
1124
-        if ($notification_users!==false) {
1124
+        if ($notification_users !== false) {
1125 1125
          	// if subnetId is set check who has permissions
1126 1126
         	if (isset($subnetId)) {
1127 1127
              	foreach ($notification_users as $u) {
1128 1128
                 	// inti object
1129
-                	$Subnets = new Subnets ($this->Database);
1129
+                	$Subnets = new Subnets($this->Database);
1130 1130
                 	//check permissions
1131 1131
                 	$subnet_permission = $Subnets->check_permission($u, $subnetId);
1132 1132
                 	// if 3 than add
1133
-                	if ($subnet_permission==3) {
1133
+                	if ($subnet_permission == 3) {
1134 1134
                     	$recipients[] = $u;
1135 1135
                 	}
1136 1136
             	}
1137 1137
         	}
1138 1138
         	else {
1139 1139
             	foreach ($notification_users as $u) {
1140
-                	if($u->role=="Administrator") {
1140
+                	if ($u->role == "Administrator") {
1141 1141
                     	$recipients[] = $u;
1142 1142
                 	}
1143 1143
             	}
1144 1144
         	}
1145
-        	return sizeof($recipients)>0 ? $recipients : false;
1145
+        	return sizeof($recipients) > 0 ? $recipients : false;
1146 1146
         }
1147 1147
         else {
1148 1148
             return false;
@@ -1156,81 +1156,81 @@  discard block
 block discarded – undo
1156 1156
 	 * @param mixed $values
1157 1157
 	 * @return array
1158 1158
 	 */
1159
-	private function ip_request_reformat_mail_values ($values) {
1159
+	private function ip_request_reformat_mail_values($values) {
1160 1160
 		// no array
1161 1161
 		if (!is_array($values)) { return $values; }
1162 1162
 
1163 1163
 		// addresses
1164
-		$this->Addresses = new Addresses ($this->Database);
1164
+		$this->Addresses = new Addresses($this->Database);
1165 1165
 
1166 1166
 		$mail = array();
1167 1167
 
1168 1168
 		// change fields for mailings
1169 1169
 		foreach ($values as $k=>$v) {
1170 1170
 			// subnetId
1171
-			if ($k=="subnetId")	{
1171
+			if ($k == "subnetId") {
1172 1172
 				// add title
1173 1173
 				$mail["s_title_1"] = "<br>Subnet details";
1174 1174
 
1175 1175
 				$subnet = $this->fetch_object("subnets", "id", $v);
1176
-				$mail["Subnet"]  = $this->transform_address ($subnet->subnet, "dotted")."/".$subnet->mask;
1177
-				$mail["Subnet"] .= strlen($subnet->description)>0 ? " - ".$subnet->description : "";
1176
+				$mail["Subnet"]  = $this->transform_address($subnet->subnet, "dotted")."/".$subnet->mask;
1177
+				$mail["Subnet"] .= strlen($subnet->description) > 0 ? " - ".$subnet->description : "";
1178 1178
 			}
1179 1179
 			// ip_addr
1180
-			elseif ($k=="ip_addr") {
1180
+			elseif ($k == "ip_addr") {
1181 1181
 				// add title
1182 1182
 				$mail["s_title_2"] = "<br>Address details";
1183 1183
 
1184
-				if (strlen($v)>0) {
1184
+				if (strlen($v) > 0) {
1185 1185
 					$mail['IP address'] = $this->transform_address($v, "dotted");
1186 1186
 				} else {
1187 1187
 					$mail['IP address'] = "Automatic";
1188 1188
 				}
1189 1189
 			}
1190 1190
 			// state
1191
-			elseif ($k=="state") {
1192
-				$mail['State'] = $this->Addresses-> address_type_index_to_type ($v);
1191
+			elseif ($k == "state") {
1192
+				$mail['State'] = $this->Addresses-> address_type_index_to_type($v);
1193 1193
 			}
1194 1194
 			// description
1195
-			elseif ($k=="descriotion") {
1195
+			elseif ($k == "descriotion") {
1196 1196
 				$mail['Description'] = $v;
1197 1197
 			}
1198 1198
 			// hostname
1199
-			elseif ($k=="hostname") {
1199
+			elseif ($k == "hostname") {
1200 1200
 				$mail['Hostname'] = $v;
1201 1201
 			}
1202 1202
 			// owner
1203
-			elseif ($k=="owner") {
1203
+			elseif ($k == "owner") {
1204 1204
 				$mail['Address owner'] = $v;
1205 1205
 			}
1206 1206
 			// requester
1207
-			elseif ($k=="requester") {
1207
+			elseif ($k == "requester") {
1208 1208
 				$mail['Requested by'] = $v;
1209 1209
 			}
1210 1210
 			// comment
1211
-			elseif ($k=="comment") {
1211
+			elseif ($k == "comment") {
1212 1212
 				$mail['Request comment'] = $v;
1213 1213
 			}
1214 1214
 			// admin comment
1215
-			elseif ($k=="adminComment") {
1215
+			elseif ($k == "adminComment") {
1216 1216
 				// add title
1217 1217
 				$mail["s_title_3"] = "<br>Admin comment";
1218 1218
 
1219 1219
 				$mail['Admin comment'] = $v;
1220 1220
 			}
1221 1221
 			// admin comment
1222
-			elseif ($k=="gateway") {
1222
+			elseif ($k == "gateway") {
1223 1223
 				$mail['Gateway'] = $v;
1224 1224
 			}
1225 1225
 			// nameservers
1226
-			elseif ($k=="dns") {
1227
-				if (strlen($v)>0) {
1226
+			elseif ($k == "dns") {
1227
+				if (strlen($v) > 0) {
1228 1228
 				$mail['DNS servers'] = $v;
1229 1229
 				}
1230 1230
 			}
1231 1231
 			// vlans
1232
-			elseif ($k=="vlan") {
1233
-				if (strlen($v)>0) {
1232
+			elseif ($k == "vlan") {
1233
+				if (strlen($v) > 0) {
1234 1234
 				$mail['VLAN'] = $v;
1235 1235
 				}
1236 1236
 			}
@@ -1261,31 +1261,31 @@  discard block
 block discarded – undo
1261 1261
 	 * @access public
1262 1262
 	 * @return array
1263 1263
 	 */
1264
-	public function verify_database () {
1264
+	public function verify_database() {
1265 1265
 
1266 1266
 		# required tables from SCHEMA.sql
1267 1267
 		$tables = $this->fetch_standard_tables();
1268 1268
 
1269 1269
 		# fetch required fields
1270
-		foreach($tables as $t) {
1271
-			$fields[$t] = $this->fetch_standard_fields ($t);
1270
+		foreach ($tables as $t) {
1271
+			$fields[$t] = $this->fetch_standard_fields($t);
1272 1272
 		}
1273 1273
 
1274 1274
 		/**
1275 1275
 		 * check that each database exist - if it does check also fields
1276 1276
 		 *		2 errors -> $tableError, $fieldError[table] = field
1277 1277
 		 ****************************************************************/
1278
-		foreach($tables as $table) {
1278
+		foreach ($tables as $table) {
1279 1279
 
1280 1280
 			//check if table exists
1281
-			if(!$this->table_exists($table)) {
1281
+			if (!$this->table_exists($table)) {
1282 1282
 				$error['tableError'][] = $table;
1283 1283
 			}
1284 1284
 			//check for each field
1285 1285
 			else {
1286
-				foreach($fields[$table] as $field) {
1286
+				foreach ($fields[$table] as $field) {
1287 1287
 					//if it doesnt exist store error
1288
-					if(!$this->field_exists($table, $field)) {
1288
+					if (!$this->field_exists($table, $field)) {
1289 1289
 						$error['fieldError'][$table][] = $field;
1290 1290
 					}
1291 1291
 				}
@@ -1293,11 +1293,11 @@  discard block
 block discarded – undo
1293 1293
 		}
1294 1294
 
1295 1295
 		# return array
1296
-		if(isset($error)) {
1296
+		if (isset($error)) {
1297 1297
 			return $error;
1298
-		} else 	{
1298
+		} else {
1299 1299
 			# update check field
1300
-			$this->update_db_verify_field ();
1300
+			$this->update_db_verify_field();
1301 1301
 			# return empty array
1302 1302
 			return array();
1303 1303
 		}
@@ -1314,13 +1314,13 @@  discard block
 block discarded – undo
1314 1314
 	 * @param bool $quit
1315 1315
 	 * @return bool
1316 1316
 	 */
1317
-	public function table_exists ($tablename, $quit = false) {
1317
+	public function table_exists($tablename, $quit = false) {
1318 1318
 	    # query
1319 1319
 	    $query = 'SELECT COUNT(*) AS count FROM information_schema.tables WHERE table_schema = "'.$this->Database->dbname.'" AND table_name = ?;';
1320 1320
 		try { $count = $this->Database->getObjectQuery($query, array($tablename)); }
1321
-		catch (Exception $e) { !$quit ? : $this->Result->show("danger", $e->getMessage(), true);	return false; }
1321
+		catch (Exception $e) { !$quit ?: $this->Result->show("danger", $e->getMessage(), true); return false; }
1322 1322
 		# return
1323
-		return $count->count ==1 ? true : false;
1323
+		return $count->count == 1 ? true : false;
1324 1324
 	}
1325 1325
 
1326 1326
 	/**
@@ -1333,15 +1333,15 @@  discard block
 block discarded – undo
1333 1333
 	 * @param mixed $fieldname
1334 1334
 	 * @return bool
1335 1335
 	 */
1336
-	public function field_exists ($tablename, $fieldname) {
1336
+	public function field_exists($tablename, $fieldname) {
1337 1337
 	    # escape
1338 1338
 	    $tablename = $this->Database->escape($tablename);
1339 1339
 		# check
1340 1340
 	    $query = "DESCRIBE `$tablename` `$fieldname`;";
1341 1341
 		try { $count = $this->Database->getObjectQuery($query); }
1342
-		catch (Exception $e) { $this->Result->show("danger", $e->getMessage(), true);	return false; }
1342
+		catch (Exception $e) { $this->Result->show("danger", $e->getMessage(), true); return false; }
1343 1343
 		# return true if it exists
1344
-		return $count!== null ? true : false;
1344
+		return $count !== null ? true : false;
1345 1345
 	}
1346 1346
 
1347 1347
 	/**
@@ -1349,11 +1349,11 @@  discard block
 block discarded – undo
1349 1349
 	 *
1350 1350
 	 * @access private
1351 1351
 	 */
1352
-	private function update_db_verify_field () {
1352
+	private function update_db_verify_field() {
1353 1353
 		# query
1354 1354
 		$query = "update `settings` set `dbverified`=1 where `id` = 1; ";
1355 1355
 		try { $this->Database->runQuery($query); }
1356
-		catch (Exception $e) { !$this->debugging ? : $this->Result->show("danger", $e->getMessage(), false); }
1356
+		catch (Exception $e) { !$this->debugging ?: $this->Result->show("danger", $e->getMessage(), false); }
1357 1357
 	}
1358 1358
 
1359 1359
 	/**
@@ -1363,7 +1363,7 @@  discard block
 block discarded – undo
1363 1363
 	 * @param mixed $table
1364 1364
 	 * @return false|string
1365 1365
 	 */
1366
-	public function get_table_fix ($table) {
1366
+	public function get_table_fix($table) {
1367 1367
 		$file = $this->read_db_schema();
1368 1368
 
1369 1369
 		//go from delimiter on
@@ -1371,7 +1371,7 @@  discard block
 block discarded – undo
1371 1371
 		$file = trim(strstr($file, "# Dump of table", true));
1372 1372
 
1373 1373
 		# check
1374
-		if(strpos($file, "DROP TABLE IF EXISTS `$table`;") > 0 )	return false;
1374
+		if (strpos($file, "DROP TABLE IF EXISTS `$table`;") > 0)	return false;
1375 1375
 		else														return $file;
1376 1376
 	}
1377 1377
 
@@ -1383,7 +1383,7 @@  discard block
 block discarded – undo
1383 1383
 	 * @param mixed $field
1384 1384
 	 * @return string|false
1385 1385
 	 */
1386
-	public function get_field_fix ($table, $field) {
1386
+	public function get_field_fix($table, $field) {
1387 1387
 		$file = $this->read_db_schema();
1388 1388
 
1389 1389
 		//go from delimiter on
@@ -1392,8 +1392,8 @@  discard block
 block discarded – undo
1392 1392
 
1393 1393
 		//get proper line
1394 1394
 		$file = explode("\n", $file);
1395
-		foreach($file as $k=>$l) {
1396
-			if(strpos(trim($l), "$field`")==1) {
1395
+		foreach ($file as $k=>$l) {
1396
+			if (strpos(trim($l), "$field`") == 1) {
1397 1397
 				$res = trim($l, ",");
1398 1398
 				$res .= ";";
1399 1399
 
@@ -1410,7 +1410,7 @@  discard block
 block discarded – undo
1410 1410
 	 * @param mixed $table
1411 1411
 	 * @return bool
1412 1412
 	 */
1413
-	public function fix_table ($table) {
1413
+	public function fix_table($table) {
1414 1414
 		# first fetch fix query
1415 1415
 		$query = $this->get_table_fix($table);
1416 1416
 		# fix
@@ -1430,10 +1430,10 @@  discard block
 block discarded – undo
1430 1430
 	 * @param mixed $field
1431 1431
 	 * @return bool
1432 1432
 	 */
1433
-	public function fix_field ($table, $field) {
1433
+	public function fix_field($table, $field) {
1434 1434
 		# set fix query
1435 1435
 		$query  = "alter table `$table` add ";
1436
-		$query .= trim($this->get_field_fix ($table, $field), ",");
1436
+		$query .= trim($this->get_field_fix($table, $field), ",");
1437 1437
 		$query .= ";";
1438 1438
 
1439 1439
 		# fix
@@ -1451,20 +1451,20 @@  discard block
 block discarded – undo
1451 1451
 	 * @method verify_database_indexes
1452 1452
 	 * @return bool
1453 1453
 	 */
1454
-	public function verify_database_indexes () {
1454
+	public function verify_database_indexes() {
1455 1455
 		// get indexes from schema
1456 1456
 		$schema_indexes = $this->get_schema_indexes();
1457 1457
 		// get existing indexes
1458 1458
 		$missing = $this->get_missing_database_indexes($schema_indexes);
1459 1459
 
1460 1460
 		// if false all indexes are ok, otherwise fix
1461
-		if ($missing===false) {
1461
+		if ($missing === false) {
1462 1462
 			return true;
1463 1463
 		}
1464 1464
 		else {
1465 1465
 			foreach ($missing as $table=>$index_id) {
1466 1466
 				foreach ($index_id as $index_name) {
1467
-					$this->fix_missing_index ($table, $index_name);
1467
+					$this->fix_missing_index($table, $index_name);
1468 1468
 				}
1469 1469
 			}
1470 1470
 		}
@@ -1479,22 +1479,22 @@  discard block
 block discarded – undo
1479 1479
 	 * @method get_schema_indexes
1480 1480
 	 * @return array
1481 1481
 	 */
1482
-	private function get_schema_indexes () {
1482
+	private function get_schema_indexes() {
1483 1483
 		// Discover indexes required for phpipam
1484 1484
 		$schema = $this->read_db_schema();
1485 1485
 
1486 1486
 		# get definitions to array, explode with CREATE TABLE `
1487 1487
 		$creates = explode("CREATE TABLE `", $schema);
1488 1488
 
1489
-		$indexes = array ();
1490
-		foreach($creates as $k=>$c) {
1491
-			if($k == 0) continue;
1492
-			$c = trim(strstr($c, ";" . "\n", true));
1489
+		$indexes = array();
1490
+		foreach ($creates as $k=>$c) {
1491
+			if ($k == 0) continue;
1492
+			$c = trim(strstr($c, ";"."\n", true));
1493 1493
 
1494 1494
 			$table = strstr($c, "`", true);
1495 1495
 
1496 1496
 			$definitions = explode("\n", $c);
1497
-			foreach($definitions as $definition) {
1497
+			foreach ($definitions as $definition) {
1498 1498
 				if (preg_match('/(KEY|UNIQUE KEY) +`(.*)` +\(/', $definition, $matches)) {
1499 1499
 					$indexes[$table][] = $matches[2];
1500 1500
 				}
@@ -1510,7 +1510,7 @@  discard block
 block discarded – undo
1510 1510
 	 * @param array $schema_indexes
1511 1511
 	 * @return array|null
1512 1512
 	 */
1513
-	private function get_missing_database_indexes ($schema_indexes) {
1513
+	private function get_missing_database_indexes($schema_indexes) {
1514 1514
 		// loop
1515 1515
 		foreach ($schema_indexes as $table=>$index) {
1516 1516
 			try { $indexes = $this->Database->getObjectsQuery("SHOW INDEX from `$table` where `Key_name` != 'PRIMARY';"); }
@@ -1518,21 +1518,21 @@  discard block
 block discarded – undo
1518 1518
 				$this->Result->show("danger", _("Invalid query for `$table` database index check : ").$e->getMessage(), true);
1519 1519
 			}
1520 1520
 			// remove existing
1521
-			if ($indexes!==false) {
1521
+			if ($indexes !== false) {
1522 1522
 				foreach ($indexes as $i) {
1523 1523
 					// remove indexes
1524
-					if(($key = array_search($i->Key_name, $schema_indexes[$table])) !== false) {
1524
+					if (($key = array_search($i->Key_name, $schema_indexes[$table])) !== false) {
1525 1525
 						unset($schema_indexes[$table][$key]);
1526 1526
 					}
1527 1527
 				}
1528 1528
 			}
1529 1529
 			// remove also empty table
1530
-			if(sizeof($schema_indexes[$table])==0) {
1530
+			if (sizeof($schema_indexes[$table]) == 0) {
1531 1531
 				unset($schema_indexes[$table]);
1532 1532
 			}
1533 1533
 		}
1534 1534
 		// return diff
1535
-		return sizeof($schema_indexes)==0 ? false : $schema_indexes;
1535
+		return sizeof($schema_indexes) == 0 ? false : $schema_indexes;
1536 1536
 	}
1537 1537
 
1538 1538
 	/**
@@ -1543,7 +1543,7 @@  discard block
 block discarded – undo
1543 1543
 	 * @param  string $index_name
1544 1544
 	 * @return void
1545 1545
 	 */
1546
-	private function fix_missing_index ($table, $index_name) {
1546
+	private function fix_missing_index($table, $index_name) {
1547 1547
 		// get definition
1548 1548
 		$file = $this->read_db_schema();
1549 1549
 
@@ -1555,12 +1555,12 @@  discard block
 block discarded – undo
1555 1555
 		$file = explode("\n", $file);
1556 1556
 
1557 1557
 		$line = false;
1558
-		foreach($file as $k=>$l) {
1558
+		foreach ($file as $k=>$l) {
1559 1559
 			// trim
1560 1560
 			$l = trim($l);
1561
-			if(strpos($l, "KEY `".$index_name."`")!==false) {
1561
+			if (strpos($l, "KEY `".$index_name."`") !== false) {
1562 1562
 				// remove last ,
1563
-				if(substr($l, -1)==",") {
1563
+				if (substr($l, -1) == ",") {
1564 1564
 					$l = substr($l, 0, -1);
1565 1565
 				}
1566 1566
 				// set query and run
@@ -1599,15 +1599,15 @@  discard block
 block discarded – undo
1599 1599
 	 * @param bool $print_error (default: false)
1600 1600
 	 * @return string|bool
1601 1601
 	 */
1602
-	public function check_latest_phpipam_version ($print_error = false) {
1602
+	public function check_latest_phpipam_version($print_error = false) {
1603 1603
 		# fetch settings
1604
-		$this->get_settings ();
1604
+		$this->get_settings();
1605 1605
 		# check for release
1606 1606
     	# try to fetch
1607 1607
     	$release_gh = @file('https://github.com/phpipam/phpipam/releases.atom');
1608 1608
     	# check
1609
-    	if ($release_gh===false) {
1610
-        	if($print_error) {
1609
+    	if ($release_gh === false) {
1610
+        	if ($print_error) {
1611 1611
             	$this->Result->show("danger", "Cannot fetch https://github.com/phpipam/phpipam/releases.atom", false);
1612 1612
             }
1613 1613
         	return false;
@@ -1618,7 +1618,7 @@  discard block
 block discarded – undo
1618 1618
 		$xml = simplexml_load_string($feed);
1619 1619
 
1620 1620
 		// if ok
1621
-		if ($xml!==false) {
1621
+		if ($xml !== false) {
1622 1622
 			// encode to json
1623 1623
 			$json = json_decode(json_encode($xml));
1624 1624
 			// save all releases
@@ -1646,11 +1646,11 @@  discard block
 block discarded – undo
1646 1646
 	 *
1647 1647
 	 * @access public
1648 1648
 	 */
1649
-	public function update_phpipam_checktime () {
1649
+	public function update_phpipam_checktime() {
1650 1650
 		# query
1651 1651
 		$query = "update `settings` set `vcheckDate`='".date("Y-m-d H:i:s")."';";
1652 1652
 		try { $this->Database->runQuery($query); }
1653
-		catch (Exception $e) { !$this->debugging ? : $this->Result->show("danger", $e->getMessage(), false); }
1653
+		catch (Exception $e) { !$this->debugging ?: $this->Result->show("danger", $e->getMessage(), false); }
1654 1654
 	}
1655 1655
 
1656 1656
 
@@ -1673,9 +1673,9 @@  discard block
 block discarded – undo
1673 1673
 	 * @param mixed $cidr
1674 1674
 	 * @return mixed
1675 1675
 	 */
1676
-	public function calculate_ip_calc_results ($cidr) {
1676
+	public function calculate_ip_calc_results($cidr) {
1677 1677
 		# detect address and calculate
1678
-		return $this->identify_address($cidr)=="IPv6" ? $this->calculate_IPv6_calc_results($cidr) : $this->calculate_IPv4_calc_results($cidr);
1678
+		return $this->identify_address($cidr) == "IPv6" ? $this->calculate_IPv6_calc_results($cidr) : $this->calculate_IPv4_calc_results($cidr);
1679 1679
 	}
1680 1680
 
1681 1681
 	/**
@@ -1685,31 +1685,31 @@  discard block
 block discarded – undo
1685 1685
 	 * @param mixed $cidr
1686 1686
 	 * @return array
1687 1687
 	 */
1688
-	private function calculate_IPv4_calc_results ($cidr) {
1688
+	private function calculate_IPv4_calc_results($cidr) {
1689 1689
 		# initialize subnets Class
1690 1690
 		$Subnets = new Subnets($this->Database);
1691 1691
 		# Initialize PEAR NET object
1692
-		$this->initialize_pear_net_IPv4 ();
1692
+		$this->initialize_pear_net_IPv4();
1693 1693
 
1694 1694
 		# parse address
1695
-        $net = $this->Net_IPv4->parseAddress( $cidr );
1695
+        $net = $this->Net_IPv4->parseAddress($cidr);
1696 1696
 
1697 1697
         # set ip address type
1698 1698
         $out = array();
1699 1699
         $out['Type']            = 'IPv4';
1700 1700
 
1701 1701
         # calculate network details
1702
-        $out['IP address']      = $net->ip;        // 192.168.0.50
1703
-        $out['Network']         = $net->network;   // 192.168.0.0
1702
+        $out['IP address']      = $net->ip; // 192.168.0.50
1703
+        $out['Network']         = $net->network; // 192.168.0.0
1704 1704
         $out['Broadcast']       = $net->broadcast; // 192.168.255.255
1705
-        $out['Subnet bitmask']  = $net->bitmask;   // 16
1706
-        $out['Subnet netmask']  = $net->netmask;   // 255.255.0.0
1707
-        $out['Subnet wildcard'] = long2ip(~ip2long($net->netmask));	//0.0.255.255
1705
+        $out['Subnet bitmask']  = $net->bitmask; // 16
1706
+        $out['Subnet netmask']  = $net->netmask; // 255.255.0.0
1707
+        $out['Subnet wildcard'] = long2ip(~ip2long($net->netmask)); //0.0.255.255
1708 1708
 
1709 1709
         # calculate min/max IP address
1710 1710
         $out['Min host IP']     = long2ip(ip2long($net->network) + 1);
1711 1711
         $out['Max host IP']     = long2ip(ip2long($net->broadcast) - 1);
1712
-        $out['Number of hosts'] = $Subnets->get_max_hosts ($net->bitmask, "IPv4");;
1712
+        $out['Number of hosts'] = $Subnets->get_max_hosts($net->bitmask, "IPv4"); ;
1713 1713
 
1714 1714
         # subnet class
1715 1715
         $out['Subnet Class']    = $this->get_ipv4_address_type($net->network, $net->broadcast);
@@ -1719,7 +1719,7 @@  discard block
 block discarded – undo
1719 1719
             $out['IP address'] = "/";
1720 1720
         }
1721 1721
         # /32 and /32 fixes
1722
-        if($net->bitmask==31 || $net->bitmask==32) {
1722
+        if ($net->bitmask == 31 || $net->bitmask == 32) {
1723 1723
 			$out['Min host IP'] = $out['Network'];
1724 1724
 			$out['Max host IP'] = $out['Broadcast'];
1725 1725
         }
@@ -1735,13 +1735,13 @@  discard block
 block discarded – undo
1735 1735
 	 * @param $broadcast
1736 1736
 	 * @return string|false
1737 1737
 	 */
1738
-	private function get_ipv4_address_type ($network, $broadcast) {
1738
+	private function get_ipv4_address_type($network, $broadcast) {
1739 1739
 		# get all possible classes
1740
-		$classes = $this->define_ipv4_address_types ();
1740
+		$classes = $this->define_ipv4_address_types();
1741 1741
 		# Initialize PEAR NET object
1742
-		$this->initialize_pear_net_IPv4 ();
1742
+		$this->initialize_pear_net_IPv4();
1743 1743
 		# check for each if member
1744
-	    foreach( $classes as $key=>$class ) {
1744
+	    foreach ($classes as $key=>$class) {
1745 1745
 	        if ($this->Net_IPv4->ipInNetwork($network, $class)) {
1746 1746
 	            if ($this->Net_IPv4->ipInNetwork($broadcast, $class)) {
1747 1747
 	                return($key);
@@ -1758,7 +1758,7 @@  discard block
 block discarded – undo
1758 1758
 	 * @access private
1759 1759
 	 * @return array
1760 1760
 	 */
1761
-	private function define_ipv4_address_types () {
1761
+	private function define_ipv4_address_types() {
1762 1762
 	    # define classes
1763 1763
 	    $classes = array();
1764 1764
 	    $classes['private A']          = '10.0.0.0/8';
@@ -1785,11 +1785,11 @@  discard block
 block discarded – undo
1785 1785
 	 * @param mixed $cidr
1786 1786
 	 * @return array
1787 1787
 	 */
1788
-	private function calculate_IPv6_calc_results ($cidr) {
1788
+	private function calculate_IPv6_calc_results($cidr) {
1789 1789
 		# initialize subnets Class
1790 1790
 		$Subnets = new Subnets($this->Database);
1791 1791
 		# Initialize PEAR NET object
1792
-		$this->initialize_pear_net_IPv6 ();
1792
+		$this->initialize_pear_net_IPv6();
1793 1793
 
1794 1794
         # set ip address type
1795 1795
         $out = array();
@@ -1797,13 +1797,13 @@  discard block
 block discarded – undo
1797 1797
 
1798 1798
         # calculate network details
1799 1799
         $out['Host address']              = $cidr;
1800
-        $out['Host address']              = $this->Net_IPv6->compress ( $out['Host address'], 1 );
1801
-        $out['Host address (uncompressed)'] = $this->Net_IPv6->uncompress ( $out['Host address'] );
1800
+        $out['Host address']              = $this->Net_IPv6->compress($out['Host address'], 1);
1801
+        $out['Host address (uncompressed)'] = $this->Net_IPv6->uncompress($out['Host address']);
1802 1802
 
1803
-        $mask                             = $this->Net_IPv6->getNetmaskSpec( $cidr );
1804
-        $subnet                           = $this->Net_IPv6->getNetmask( $cidr );
1805
-        $out['Subnet prefix']             = $this->Net_IPv6->compress ( $subnet ) .'/'. $mask;
1806
-        $out['Prefix length']             = $this->Net_IPv6->getNetmaskSpec( $cidr );
1803
+        $mask                             = $this->Net_IPv6->getNetmaskSpec($cidr);
1804
+        $subnet                           = $this->Net_IPv6->getNetmask($cidr);
1805
+        $out['Subnet prefix']             = $this->Net_IPv6->compress($subnet).'/'.$mask;
1806
+        $out['Prefix length']             = $this->Net_IPv6->getNetmaskSpec($cidr);
1807 1807
 
1808 1808
         # get reverse DNS entries
1809 1809
         $out['Host Reverse DNS']   = $this->reverse_IPv6($out['Host address (uncompressed)']);
@@ -1817,15 +1817,15 @@  discard block
 block discarded – undo
1817 1817
         }
1818 1818
 
1819 1819
         # /min / max hosts
1820
-        $maxIp = gmp_strval(gmp_add(gmp_pow(2, 128 - $mask),$this->ip2long6 ($subnet)));
1820
+        $maxIp = gmp_strval(gmp_add(gmp_pow(2, 128 - $mask), $this->ip2long6($subnet)));
1821 1821
 		$maxIp = gmp_strval(gmp_sub($maxIp, 1));
1822 1822
 
1823 1823
         $out['Min host IP']               = $subnet;
1824
-        $out['Max host IP']               = $this->long2ip6 ($maxIp);
1825
-        $out['Number of hosts']           = $Subnets->get_max_hosts ($mask, "IPv6");
1824
+        $out['Max host IP']               = $this->long2ip6($maxIp);
1825
+        $out['Number of hosts']           = $Subnets->get_max_hosts($mask, "IPv6");
1826 1826
 
1827 1827
         # set address type
1828
-        $out['Address type']              = $this->get_ipv6_address_type( $cidr );
1828
+        $out['Address type']              = $this->get_ipv6_address_type($cidr);
1829 1829
 		# result
1830 1830
 		return $out;
1831 1831
 	}
@@ -1840,18 +1840,18 @@  discard block
 block discarded – undo
1840 1840
 	 * @param int $pflen (default: 128)
1841 1841
 	 * @return string
1842 1842
 	 */
1843
-	public function reverse_IPv6 ($addresses, $pflen=128) {
1843
+	public function reverse_IPv6($addresses, $pflen = 128) {
1844 1844
 		# Initialize PEAR NET object
1845
-		$this->initialize_pear_net_IPv6 ();
1845
+		$this->initialize_pear_net_IPv6();
1846 1846
 		//uncompress
1847 1847
 	    $uncompressed = $this->Net_IPv6->removeNetmaskSpec($this->Net_IPv6->uncompress($addresses));
1848 1848
 	    $len = $pflen / 4;
1849 1849
 	    $parts = explode(':', $uncompressed);
1850 1850
 	    $res = '';
1851
-	    foreach($parts as $part) {
1851
+	    foreach ($parts as $part) {
1852 1852
 	        $res .= str_pad($part, 4, '0', STR_PAD_LEFT);
1853 1853
 	    }
1854
-	    $res = implode('.', str_split(strrev(substr($res, 0, $len)))) . '.ip6.arpa';
1854
+	    $res = implode('.', str_split(strrev(substr($res, 0, $len)))).'.ip6.arpa';
1855 1855
 	    if ($pflen % 4 != 0) {
1856 1856
 	        $res .= " "._("(closest parent)");
1857 1857
 	    }
@@ -1865,13 +1865,13 @@  discard block
 block discarded – undo
1865 1865
 	 * @param CIDR $cidr
1866 1866
 	 * @return string|false
1867 1867
 	 */
1868
-	private function get_ipv6_address_type ($cidr) {
1868
+	private function get_ipv6_address_type($cidr) {
1869 1869
 		# Initialize PEAR NET object
1870
-		$this->initialize_pear_net_IPv6 ();
1870
+		$this->initialize_pear_net_IPv6();
1871 1871
 		# get type in number
1872 1872
 		$type = $this->Net_IPv6->getAddressType($cidr);
1873 1873
 		# fetch types
1874
-		$all_types = $this->define_ipv6_address_types ();
1874
+		$all_types = $this->define_ipv6_address_types();
1875 1875
 		# translate
1876 1876
 		return array_key_exists($type, $all_types) ? $all_types[$type] : false;
1877 1877
 	}
@@ -1882,7 +1882,7 @@  discard block
 block discarded – undo
1882 1882
 	 * @access private
1883 1883
 	 * @return string[]
1884 1884
 	 */
1885
-	private function define_ipv6_address_types () {
1885
+	private function define_ipv6_address_types() {
1886 1886
         $all_types[10] = "NET_IPV6_NO_NETMASK";
1887 1887
         $all_types[1]  = "NET_IPV6";
1888 1888
         $all_types[11] = "NET_IPV6_RESERVED";
@@ -1930,7 +1930,7 @@  discard block
 block discarded – undo
1930 1930
      * @param int|bool object_id (default: false) - to bold it
1931 1931
      * @return array|bool
1932 1932
      */
1933
-    public function translate_nat_objects_for_display ($json_objects, $nat_id = false, $admin = false, $object_type = false, $object_id=false) {
1933
+    public function translate_nat_objects_for_display($json_objects, $nat_id = false, $admin = false, $object_type = false, $object_id = false) {
1934 1934
         // to array "subnets"=>array(1,2,3)
1935 1935
         $objects = json_decode($json_objects, true);
1936 1936
         // init out array
@@ -1939,20 +1939,20 @@  discard block
 block discarded – undo
1939 1939
         $this->get_settings();
1940 1940
         $statuses = explode(";", $this->settings->pingStatus);
1941 1941
         // check
1942
-        if(is_array($objects)) {
1943
-            if(sizeof($objects)>0) {
1942
+        if (is_array($objects)) {
1943
+            if (sizeof($objects) > 0) {
1944 1944
                 foreach ($objects as $ot=>$ids) {
1945
-                    if (sizeof($ids)>0) {
1945
+                    if (sizeof($ids) > 0) {
1946 1946
                         foreach ($ids as $id) {
1947 1947
                             // fetch
1948 1948
                             $item = $this->fetch_object($ot, "id", $id);
1949
-                            if($item!==false) {
1949
+                            if ($item !== false) {
1950 1950
                                 // bold
1951
-                                $bold = $item->id==$object_id && $ot==$object_type ? "<span class='strong'>" : "<span>";
1951
+                                $bold = $item->id == $object_id && $ot == $object_type ? "<span class='strong'>" : "<span>";
1952 1952
                                 // remove
1953
-                                $remove = $admin&&$nat_id ? "<span class='remove-nat-item-wrapper_".$ot."_".$item->id."'><a class='btn btn-xs btn-danger removeNatItem' data-id='$nat_id' data-type='$ot' data-item-id='$item->id' rel='tooltip' title='"._('Remove')."'><i class='fa fa-times'></i></a>" : "<span>";
1953
+                                $remove = $admin && $nat_id ? "<span class='remove-nat-item-wrapper_".$ot."_".$item->id."'><a class='btn btn-xs btn-danger removeNatItem' data-id='$nat_id' data-type='$ot' data-item-id='$item->id' rel='tooltip' title='"._('Remove')."'><i class='fa fa-times'></i></a>" : "<span>";
1954 1954
                                 // subnets
1955
-                                if ($ot=="subnets") {
1955
+                                if ($ot == "subnets") {
1956 1956
                                     $out[] = "$remove $bold<a href='".create_link("subnets", $item->sectionId, $item->id)."'>".$this->transform_address($item->subnet, "dotted")."/".$item->mask."</a></span></span>";
1957 1957
                                 }
1958 1958
                                 // addresses
@@ -1960,23 +1960,23 @@  discard block
 block discarded – undo
1960 1960
                                     // subnet
1961 1961
                                     $snet = $this->fetch_object("subnets", "id", $item->subnetId);
1962 1962
                                     // append status
1963
-                                    if ($snet->pingSubnet=="1") {
1963
+                                    if ($snet->pingSubnet == "1") {
1964 1964
                                         //calculate
1965 1965
                                         $tDiff = time() - strtotime($item->lastSeen);
1966
-                                        if($item->excludePing=="1" )    { $hStatus = "padded"; $hTooltip = ""; }
1967
-                                        elseif(is_null($item->lastSeen)) { $hStatus = "neutral"; $hTooltip = "rel='tooltip' data-container='body' data-html='true' data-placement='left' title='"._("Address was never online")."'"; }
1968
-                                        elseif($tDiff < $statuses[0])	{ $hStatus = "success";	$hTooltip = "rel='tooltip' data-container='body' data-html='true' data-placement='left' title='"._("Address is alive")."<hr>"._("Last seen").": ".$item->lastSeen."'"; }
1969
-                                        elseif($tDiff < $statuses[1])	{ $hStatus = "warning"; $hTooltip = "rel='tooltip' data-container='body' data-html='true' data-placement='left' title='"._("Address warning")."<hr>"._("Last seen").": ".$item->lastSeen."'"; }
1970
-                                        elseif($tDiff > $statuses[1])	{ $hStatus = "error"; 	$hTooltip = "rel='tooltip' data-container='body' data-html='true' data-placement='left' title='"._("Address is offline")."<hr>"._("Last seen").": ".$item->lastSeen."'";}
1971
-                                        elseif($item->lastSeen == "0000-00-00 00:00:00") { $hStatus = "neutral"; 	$hTooltip = "rel='tooltip' data-container='body' data-html='true' data-placement='left' title='"._("Address is offline")."<hr>"._("Last seen").": "._("Never")."'";}
1972
-                                        elseif($item->lastSeen == "1970-01-01 00:00:01") { $hStatus = "neutral"; 	$hTooltip = "rel='tooltip' data-container='body' data-html='true' data-placement='left' title='"._("Address is offline")."<hr>"._("Last seen").": "._("Never")."'";}
1973
-                                        else							{ $hStatus = "neutral"; $hTooltip = "rel='tooltip' data-container='body' data-html='true' data-placement='left' title='"._("Address status unknown")."'";}
1966
+                                        if ($item->excludePing == "1") { $hStatus = "padded"; $hTooltip = ""; }
1967
+                                        elseif (is_null($item->lastSeen)) { $hStatus = "neutral"; $hTooltip = "rel='tooltip' data-container='body' data-html='true' data-placement='left' title='"._("Address was never online")."'"; }
1968
+                                        elseif ($tDiff < $statuses[0]) { $hStatus = "success"; $hTooltip = "rel='tooltip' data-container='body' data-html='true' data-placement='left' title='"._("Address is alive")."<hr>"._("Last seen").": ".$item->lastSeen."'"; }
1969
+                                        elseif ($tDiff < $statuses[1]) { $hStatus = "warning"; $hTooltip = "rel='tooltip' data-container='body' data-html='true' data-placement='left' title='"._("Address warning")."<hr>"._("Last seen").": ".$item->lastSeen."'"; }
1970
+                                        elseif ($tDiff > $statuses[1]) { $hStatus = "error"; $hTooltip = "rel='tooltip' data-container='body' data-html='true' data-placement='left' title='"._("Address is offline")."<hr>"._("Last seen").": ".$item->lastSeen."'"; }
1971
+                                        elseif ($item->lastSeen == "0000-00-00 00:00:00") { $hStatus = "neutral"; $hTooltip = "rel='tooltip' data-container='body' data-html='true' data-placement='left' title='"._("Address is offline")."<hr>"._("Last seen").": "._("Never")."'"; }
1972
+                                        elseif ($item->lastSeen == "1970-01-01 00:00:01") { $hStatus = "neutral"; $hTooltip = "rel='tooltip' data-container='body' data-html='true' data-placement='left' title='"._("Address is offline")."<hr>"._("Last seen").": "._("Never")."'"; }
1973
+                                        else { $hStatus = "neutral"; $hTooltip = "rel='tooltip' data-container='body' data-html='true' data-placement='left' title='"._("Address status unknown")."'"; }
1974 1974
                                     }
1975 1975
                                     else {
1976 1976
                                         $hStatus = "hidden";
1977 1977
                                         $hTooltip = "";
1978 1978
                                     }
1979
-                                    if($remove=="<span>") {
1979
+                                    if ($remove == "<span>") {
1980 1980
                                         $remove .= "<span class='status status-$hStatus' $hTooltip></span>";
1981 1981
                                     }
1982 1982
 
@@ -1989,7 +1989,7 @@  discard block
 block discarded – undo
1989 1989
             }
1990 1990
         }
1991 1991
         // result
1992
-        return sizeof($out)>0 ? $out : false;
1992
+        return sizeof($out) > 0 ? $out : false;
1993 1993
     }
1994 1994
 
1995 1995
     /**
@@ -2006,40 +2006,40 @@  discard block
 block discarded – undo
2006 2006
      * @param array $all_nats (default: array())
2007 2007
      * @return array
2008 2008
      */
2009
-    public function reindex_nat_objects ($all_nats = array()) {
2009
+    public function reindex_nat_objects($all_nats = array()) {
2010 2010
         // out array
2011 2011
         $out = array(
2012 2012
             "ipaddresses"=>array(),
2013 2013
             "subnets"=>array()
2014 2014
         );
2015 2015
         // loop
2016
-        if(is_array($all_nats)) {
2017
-            if (sizeof($all_nats)>0) {
2016
+        if (is_array($all_nats)) {
2017
+            if (sizeof($all_nats) > 0) {
2018 2018
                 foreach ($all_nats as $n) {
2019 2019
                     $src = json_decode($n->src, true);
2020 2020
                     $dst = json_decode($n->dst, true);
2021 2021
 
2022 2022
                     // src
2023
-                    if(is_array($src)) {
2024
-                        if(is_array(@$src['subnets'])) {
2023
+                    if (is_array($src)) {
2024
+                        if (is_array(@$src['subnets'])) {
2025 2025
                             foreach ($src['subnets'] as $s) {
2026 2026
                                 $out['subnets'][$s][] = $n->id;
2027 2027
                             }
2028 2028
                         }
2029
-                        if(is_array(@$src['ipaddresses'])) {
2029
+                        if (is_array(@$src['ipaddresses'])) {
2030 2030
                             foreach ($src['ipaddresses'] as $s) {
2031 2031
                                 $out['ipaddresses'][$s][] = $n->id;
2032 2032
                             }
2033 2033
                         }
2034 2034
                     }
2035 2035
                     // dst
2036
-                    if(is_array($dst)) {
2037
-                        if(is_array(@$dst['subnets'])) {
2036
+                    if (is_array($dst)) {
2037
+                        if (is_array(@$dst['subnets'])) {
2038 2038
                             foreach ($dst['subnets'] as $s) {
2039 2039
                                 $out['subnets'][$s][] = $n->id;
2040 2040
                             }
2041 2041
                         }
2042
-                        if(is_array(@$dst['ipaddresses'])) {
2042
+                        if (is_array(@$dst['ipaddresses'])) {
2043 2043
                             foreach ($dst['ipaddresses'] as $s) {
2044 2044
                                 $out['ipaddresses'][$s][] = $n->id;
2045 2045
                             }
@@ -2064,30 +2064,30 @@  discard block
 block discarded – undo
2064 2064
      * @param bool $object_id (default: false)
2065 2065
      * @return string
2066 2066
      */
2067
-    public function print_nat_table ($n, $is_admin = false, $nat_id = false, $admin = false, $object_type = false, $object_id=false) {
2067
+    public function print_nat_table($n, $is_admin = false, $nat_id = false, $admin = false, $object_type = false, $object_id = false) {
2068 2068
         // cast to object to be sure if array provided
2069 2069
         $n = (object) $n;
2070 2070
 
2071 2071
         // translate json to array, links etc
2072
-        $sources      = $this->translate_nat_objects_for_display ($n->src, $nat_id, $admin, $object_type, $object_id);
2073
-        $destinations = $this->translate_nat_objects_for_display ($n->dst, $nat_id, $admin, $object_type, $object_id);
2072
+        $sources      = $this->translate_nat_objects_for_display($n->src, $nat_id, $admin, $object_type, $object_id);
2073
+        $destinations = $this->translate_nat_objects_for_display($n->dst, $nat_id, $admin, $object_type, $object_id);
2074 2074
 
2075 2075
         // no src/dst
2076
-        if ($sources===false)
2076
+        if ($sources === false)
2077 2077
             $sources = array("<span class='badge badge1 badge5 alert-danger'>"._("None")."</span>");
2078
-        if ($destinations===false)
2078
+        if ($destinations === false)
2079 2079
             $destinations = array("<span class='badge badge1 badge5 alert-danger'>"._("None")."</span>");
2080 2080
 
2081 2081
         // description
2082 2082
         $n->description = str_replace("\n", "<br>", $n->description);
2083
-        $n->description = strlen($n->description)>0 ? "<br>$n->description" : "";
2083
+        $n->description = strlen($n->description) > 0 ? "<br>$n->description" : "";
2084 2084
 
2085 2085
         // device
2086 2086
         if (strlen($n->device)) {
2087
-            if($n->device !== 0) {
2088
-                $device = $this->fetch_object ("devices", "id", $n->device);
2089
-                $description = strlen($device->description)>0 ? " ($device->description)" : "";
2090
-                $n->device = $device===false ? "/" : "<a href='".create_link("tools", "devices", $device->id)."'>$device->hostname</a> ($device->ip_addr) <span class='text-muted'>$description</span>";
2087
+            if ($n->device !== 0) {
2088
+                $device = $this->fetch_object("devices", "id", $n->device);
2089
+                $description = strlen($device->description) > 0 ? " ($device->description)" : "";
2090
+                $n->device = $device === false ? "/" : "<a href='".create_link("tools", "devices", $device->id)."'>$device->hostname</a> ($device->ip_addr) <span class='text-muted'>$description</span>";
2091 2091
             }
2092 2092
         }
2093 2093
         else {
@@ -2095,7 +2095,7 @@  discard block
 block discarded – undo
2095 2095
         }
2096 2096
 
2097 2097
         // icon
2098
-        $icon =  $n->type=="static" ? "fa-arrows-h" : "fa-long-arrow-right";
2098
+        $icon = $n->type == "static" ? "fa-arrows-h" : "fa-long-arrow-right";
2099 2099
 
2100 2100
         // to html
2101 2101
         $html = array();
@@ -2110,7 +2110,7 @@  discard block
 block discarded – undo
2110 2110
         $html[] = "</tr>";
2111 2111
 
2112 2112
         // append ports
2113
-        if(($n->type=="static" || $n->type=="destination") && (strlen($n->src_port)>0 && strlen($n->dst_port)>0)) {
2113
+        if (($n->type == "static" || $n->type == "destination") && (strlen($n->src_port) > 0 && strlen($n->dst_port) > 0)) {
2114 2114
             $sources      = implode("<br>", $sources)." /".$n->src_port;
2115 2115
             $destinations = implode("<br>", $destinations)." /".$n->dst_port;
2116 2116
         }
@@ -2134,7 +2134,7 @@  discard block
 block discarded – undo
2134 2134
         $html[] = "</tr>";
2135 2135
 
2136 2136
         // actions
2137
-        if($is_admin) {
2137
+        if ($is_admin) {
2138 2138
         $html[] = "<tr>";
2139 2139
         $html[] = "<td colspan='4'><hr></td>";
2140 2140
         $html[] = "</tr>";
@@ -2171,8 +2171,8 @@  discard block
 block discarded – undo
2171 2171
      * @param bool $recursive (default: false)
2172 2172
      * @return array|bool
2173 2173
      */
2174
-    public function fetch_all_prefixes ($master = false, $recursive = false) {
2175
-	    if($master && !$recursive) {
2174
+    public function fetch_all_prefixes($master = false, $recursive = false) {
2175
+	    if ($master && !$recursive) {
2176 2176
     	    $query = 'select *,concat(prefix,start) as raw from pstnPrefixes where master = ? order by raw asc;';
2177 2177
     	    $params = array($master);
2178 2178
 	    }
@@ -2187,26 +2187,26 @@  discard block
 block discarded – undo
2187 2187
 			return false;
2188 2188
 		}
2189 2189
         // for master + recursive we need to go from master id to next 0 (root
2190
-        if($master && $recursive && $prefixes) {
2190
+        if ($master && $recursive && $prefixes) {
2191 2191
             $master_set = false;
2192 2192
             $out = array();
2193 2193
 
2194 2194
             foreach ($prefixes as $k=>$p) {
2195
-        	    if($p->id == $master) {
2195
+        	    if ($p->id == $master) {
2196 2196
             	    $out[] = $p;
2197 2197
             	    $master_set = true;
2198 2198
         	    }
2199
-        	    elseif ($master_set && $p->master!=0) {
2199
+        	    elseif ($master_set && $p->master != 0) {
2200 2200
             	    $out[] = $p;
2201 2201
         	    }
2202
-        	    elseif ($master_set && $p->master!=0) {
2202
+        	    elseif ($master_set && $p->master != 0) {
2203 2203
             	    break;
2204 2204
         	    }
2205 2205
             }
2206 2206
             $prefixes = $out;
2207 2207
         }
2208 2208
 		# result
2209
-		return sizeof($prefixes)>0 ? array_values($prefixes) : false;
2209
+		return sizeof($prefixes) > 0 ? array_values($prefixes) : false;
2210 2210
     }
2211 2211
 
2212 2212
     /**
@@ -2216,7 +2216,7 @@  discard block
 block discarded – undo
2216 2216
      * @param mixed $number
2217 2217
      * @return mixed
2218 2218
      */
2219
-    public function prefix_normalize ($number) {
2219
+    public function prefix_normalize($number) {
2220 2220
         return str_replace(array("+", " ", "-"), "", $number);
2221 2221
     }
2222 2222
 
@@ -2227,19 +2227,19 @@  discard block
 block discarded – undo
2227 2227
 	 * @param mixed $id
2228 2228
 	 * @return array
2229 2229
 	 */
2230
-	public function fetch_prefix_parents_recursive ($id) {
2230
+	public function fetch_prefix_parents_recursive($id) {
2231 2231
 		$parents = array();
2232 2232
 		$root = false;
2233 2233
 
2234
-		while($root === false) {
2235
-			$subd = $this->fetch_object("pstnPrefixes", "id", $id);		# get subnet details
2234
+		while ($root === false) {
2235
+			$subd = $this->fetch_object("pstnPrefixes", "id", $id); # get subnet details
2236 2236
 
2237
-			if($subd!==false) {
2237
+			if ($subd !== false) {
2238 2238
     			$subd = (array) $subd;
2239 2239
 				# not root yet
2240
-				if(@$subd['master']!=0) {
2240
+				if (@$subd['master'] != 0) {
2241 2241
 					array_unshift($parents, $subd['master']);
2242
-					$id  = $subd['master'];
2242
+					$id = $subd['master'];
2243 2243
 				}
2244 2244
 				# root
2245 2245
 				else {
@@ -2272,20 +2272,20 @@  discard block
 block discarded – undo
2272 2272
 	 *
2273 2273
 	 * @return array
2274 2274
 	 */
2275
-	public function fetch_parents_recursive ($table, $parent_field, $return_field, $id, $reverse = false) {
2275
+	public function fetch_parents_recursive($table, $parent_field, $return_field, $id, $reverse = false) {
2276 2276
 		$parents = array();
2277 2277
 		$root = false;
2278 2278
 
2279
-		while($root === false) {
2279
+		while ($root === false) {
2280 2280
 			$subd = $this->fetch_object($table, "id", $id);
2281 2281
 
2282
-			if($subd!==false) {
2282
+			if ($subd !== false) {
2283 2283
     			$subd = (array) $subd;
2284 2284
 				# not root yet
2285
-				if(@$subd[$parent_field]!=0) {
2285
+				if (@$subd[$parent_field] != 0) {
2286 2286
 					// array_unshift($parents, $subd[$parent_field]);
2287 2287
 					$parents[$subd['id']] = $subd[$return_field];
2288
-					$id  = $subd[$parent_field];
2288
+					$id = $subd[$parent_field];
2289 2289
 				}
2290 2290
 				# root
2291 2291
 				else {
@@ -2298,7 +2298,7 @@  discard block
 block discarded – undo
2298 2298
 			}
2299 2299
 		}
2300 2300
 		# return array
2301
-		return $reverse ? array_reverse($parents, truetrue) :$parents;
2301
+		return $reverse ? array_reverse($parents, truetrue) : $parents;
2302 2302
 	}
2303 2303
 
2304 2304
 	/**
@@ -2309,8 +2309,8 @@  discard block
 block discarded – undo
2309 2309
 	 * @param bool $number (default: false)
2310 2310
 	 * @return null|boolean
2311 2311
 	 */
2312
-	public function check_number_duplicates ($prefix = false, $number = false) {
2313
-    	if($prefix===false && $number===false) {
2312
+	public function check_number_duplicates($prefix = false, $number = false) {
2313
+    	if ($prefix === false && $number === false) {
2314 2314
         	$this->Result->show("danger", "Duplicate chck failed", true);
2315 2315
     	}
2316 2316
     	else {
@@ -2322,7 +2322,7 @@  discard block
 block discarded – undo
2322 2322
     			return false;
2323 2323
     		}
2324 2324
     		# result
2325
-    		return $cnt->cnt>0 ? true : false;
2325
+    		return $cnt->cnt > 0 ? true : false;
2326 2326
     	}
2327 2327
 	}
2328 2328
 
@@ -2335,8 +2335,8 @@  discard block
 block discarded – undo
2335 2335
 	 * @param object $user
2336 2336
 	 * @return int
2337 2337
 	 */
2338
-	public function check_prefix_permission ($user) {
2339
-        return $user->role=="Administrator" ? 3 : $user->pstn;
2338
+	public function check_prefix_permission($user) {
2339
+        return $user->role == "Administrator" ? 3 : $user->pstn;
2340 2340
 	}
2341 2341
 
2342 2342
 	/**
@@ -2348,10 +2348,10 @@  discard block
 block discarded – undo
2348 2348
 	 * @param mixed $custom_fields
2349 2349
 	 * @return mixed
2350 2350
 	 */
2351
-	public function print_menu_prefixes ( $user, $prefixes, $custom_fields ) {
2351
+	public function print_menu_prefixes($user, $prefixes, $custom_fields) {
2352 2352
 
2353 2353
 		# set hidden fields
2354
-		$this->get_settings ();
2354
+		$this->get_settings();
2355 2355
 		$hidden_fields = json_decode($this->settings->hiddenCustomFields, true);
2356 2356
 		$hidden_fields = is_array($hidden_fields['subnets']) ? $hidden_fields['subnets'] : array();
2357 2357
 
@@ -2361,17 +2361,17 @@  discard block
 block discarded – undo
2361 2361
 		$rootId = 0;
2362 2362
 
2363 2363
 		# remove all not permitted!
2364
-		if(sizeof($prefixes)>0) {
2365
-		foreach($prefixes as $k=>$s) {
2366
-			$permission = $this->check_prefix_permission ($user);
2367
-			if($permission == 0) { unset($prefixes[$k]); }
2364
+		if (sizeof($prefixes) > 0) {
2365
+		foreach ($prefixes as $k=>$s) {
2366
+			$permission = $this->check_prefix_permission($user);
2367
+			if ($permission == 0) { unset($prefixes[$k]); }
2368 2368
 		}
2369 2369
 		}
2370 2370
 
2371 2371
 		# create loop array
2372
-		if(sizeof($prefixes) > 0) {
2372
+		if (sizeof($prefixes) > 0) {
2373 2373
         $children_prefixes = array();
2374
-		foreach ( $prefixes as $item ) {
2374
+		foreach ($prefixes as $item) {
2375 2375
 			$item = (array) $item;
2376 2376
 			$children_prefixes[$item['master']][] = $item;
2377 2377
 		}
@@ -2381,7 +2381,7 @@  discard block
 block discarded – undo
2381 2381
 		}
2382 2382
 
2383 2383
 		# loop will be false if the root has no children (i.e., an empty menu!)
2384
-		$loop = !empty( $children_prefixes[$rootId] );
2384
+		$loop = !empty($children_prefixes[$rootId]);
2385 2385
 
2386 2386
 		# initializing $parent as the root
2387 2387
 		$parent = $rootId;
@@ -2391,12 +2391,12 @@  discard block
 block discarded – undo
2391 2391
 		$old_count = 0;
2392 2392
 
2393 2393
 		# return table content (tr and td's)
2394
-		reset( $children_prefixes[$parent] );
2395
-		while ( $loop && ( ( $option = current( $children_prefixes[$parent] ) ) || ( $parent > $rootId ) ) )
2394
+		reset($children_prefixes[$parent]);
2395
+		while ($loop && (($option = current($children_prefixes[$parent])) || ($parent > $rootId)))
2396 2396
 		{
2397
-			next( $children_prefixes[$parent] );
2397
+			next($children_prefixes[$parent]);
2398 2398
 
2399
-			if(count($parent_stack) == 0) {
2399
+			if (count($parent_stack) == 0) {
2400 2400
 				$margin = "0px";
2401 2401
 				$padding = "0px";
2402 2402
 			}
@@ -2405,41 +2405,41 @@  discard block
 block discarded – undo
2405 2405
 				$padding = "10px";
2406 2406
 
2407 2407
 				# margin
2408
-				$margin  = (count($parent_stack) * 10) -10;
2409
-				$margin  = $margin *1.5;
2408
+				$margin  = (count($parent_stack) * 10) - 10;
2409
+				$margin  = $margin * 1.5;
2410 2410
 				$margin  = $margin."px";
2411 2411
 			}
2412 2412
 
2413 2413
 			# count levels
2414
-			$count = count( $parent_stack ) + 1;
2414
+			$count = count($parent_stack) + 1;
2415 2415
 
2416 2416
 			# description
2417
-			$name = strlen($option['name'])==0 ? "/" : $option['name'];
2417
+			$name = strlen($option['name']) == 0 ? "/" : $option['name'];
2418 2418
 
2419 2419
 			# print table line
2420
-			if(strlen($option['prefix']) > 0) {
2420
+			if (strlen($option['prefix']) > 0) {
2421 2421
     			# count change?
2422 2422
 				$html[] = "<tr class='level$count'>";
2423 2423
 
2424 2424
 				//which level?
2425
-				if($count==1) {
2425
+				if ($count == 1) {
2426 2426
 					# last?
2427
-					if(!empty( $children_prefixes[$option['id']])) {
2428
-						$html[] = "	<td class='level$count'><span class='structure-last' style='padding-left:$padding; margin-left:$margin;'></span><i class='fa fa-gray fa-pad-right-3 fa-folder-open-o'></i><a href='".create_link($_GET['page'],"pstn-prefixes",$option['id'])."'>".$option['prefix']." </a></td>";
2427
+					if (!empty($children_prefixes[$option['id']])) {
2428
+						$html[] = "	<td class='level$count'><span class='structure-last' style='padding-left:$padding; margin-left:$margin;'></span><i class='fa fa-gray fa-pad-right-3 fa-folder-open-o'></i><a href='".create_link($_GET['page'], "pstn-prefixes", $option['id'])."'>".$option['prefix']." </a></td>";
2429 2429
 						$html[] = "	<td class='level$count'><span class='structure-last' style='padding-left:$padding; margin-left:$margin;'></span><i class='fa fa-gray fa-pad-right-3 fa-folder-open-o'></i> <strong>$name</strong></td>";
2430 2430
 					} else {
2431
-						$html[] = "	<td class='level$count'><span class='structure' style='padding-left:$padding; margin-left:$margin;'></span><i class='fa fa-gray fa-pad-right-3 fa-angle-right'></i><a href='".create_link($_GET['page'],"pstn-prefixes",$option['id'])."'>".$option['prefix']." </a></td>";
2431
+						$html[] = "	<td class='level$count'><span class='structure' style='padding-left:$padding; margin-left:$margin;'></span><i class='fa fa-gray fa-pad-right-3 fa-angle-right'></i><a href='".create_link($_GET['page'], "pstn-prefixes", $option['id'])."'>".$option['prefix']." </a></td>";
2432 2432
 						$html[] = "	<td class='level$count'><span class='structure' style='padding-left:$padding; margin-left:$margin;'></span><i class='fa fa-gray fa-pad-right-3 fa-angle-right'></i> <strong>$name</strong></td>";
2433 2433
 					}
2434 2434
 				}
2435 2435
 				else {
2436 2436
 					# last?
2437
-					if(!empty( $children_prefixes[$option['id']])) {
2438
-						$html[] = "	<td class='level$count'><span class='structure-last' style='padding-left:$padding; margin-left:$margin;'></span><i class='fa fa-gray fa-pad-right-3 fa-folder-open-o'></i> <a href='".create_link($_GET['page'],"pstn-prefixes",$option['id'])."'>  ".$option['prefix']."</a></td>";
2437
+					if (!empty($children_prefixes[$option['id']])) {
2438
+						$html[] = "	<td class='level$count'><span class='structure-last' style='padding-left:$padding; margin-left:$margin;'></span><i class='fa fa-gray fa-pad-right-3 fa-folder-open-o'></i> <a href='".create_link($_GET['page'], "pstn-prefixes", $option['id'])."'>  ".$option['prefix']."</a></td>";
2439 2439
 						$html[] = "	<td class='level$count'><span class='structure-last' style='padding-left:$padding; margin-left:$margin;'></span><i class='fa fa-gray fa-pad-right-3 fa-folder-open-o'></i> <strong>$name</strong></td>";
2440 2440
 					}
2441 2441
 					else {
2442
-						$html[] = "	<td class='level$count'><span class='structure' style='padding-left:$padding; margin-left:$margin;'></span><i class='fa fa-gray fa-pad-right-3 fa-angle-right'></i> <a href='".create_link($_GET['page'],"pstn-prefixes",$option['id'])."'>  ".$option['prefix']."</a></td>";
2442
+						$html[] = "	<td class='level$count'><span class='structure' style='padding-left:$padding; margin-left:$margin;'></span><i class='fa fa-gray fa-pad-right-3 fa-angle-right'></i> <a href='".create_link($_GET['page'], "pstn-prefixes", $option['id'])."'>  ".$option['prefix']."</a></td>";
2443 2443
 						$html[] = "	<td class='level$count'><span class='structure' style='padding-left:$padding; margin-left:$margin;'></span><i class='fa fa-gray fa-pad-right-3 fa-angle-right'></i> <strong>$name</strong></td>";
2444 2444
 					}
2445 2445
 				}
@@ -2457,54 +2457,54 @@  discard block
 block discarded – undo
2457 2457
                 $html[] = "	<td><span class='badge badge1 badge5'>".$cnt."</span></td>";
2458 2458
 
2459 2459
 				//device
2460
-				$device = ( $option['deviceId']==0 || empty($option['deviceId']) ) ? false : true;
2460
+				$device = ($option['deviceId'] == 0 || empty($option['deviceId'])) ? false : true;
2461 2461
 
2462
-				if($device===false) { $html[] ='	<td>/</td>' . "\n"; }
2462
+				if ($device === false) { $html[] = '	<td>/</td>'."\n"; }
2463 2463
 				else {
2464
-					$device = $this->fetch_object ("devices", "id", $option['deviceId']);
2465
-					if ($device!==false) {
2466
-						$html[] = "	<td><a href='".create_link("tools","devices",$device->id)."'>".$device->hostname .'</a></td>' . "\n";
2464
+					$device = $this->fetch_object("devices", "id", $option['deviceId']);
2465
+					if ($device !== false) {
2466
+						$html[] = "	<td><a href='".create_link("tools", "devices", $device->id)."'>".$device->hostname.'</a></td>'."\n";
2467 2467
 					}
2468 2468
 					else {
2469
-						$html[] ='	<td>/</td>' . "\n";
2469
+						$html[] = '	<td>/</td>'."\n";
2470 2470
 					}
2471 2471
 				}
2472 2472
 
2473 2473
 				//custom
2474
-				if(sizeof($custom_fields) > 0) {
2475
-			   		foreach($custom_fields as $field) {
2474
+				if (sizeof($custom_fields) > 0) {
2475
+			   		foreach ($custom_fields as $field) {
2476 2476
 				   		# hidden?
2477
-				   		if(!in_array($field['name'], $hidden_fields)) {
2477
+				   		if (!in_array($field['name'], $hidden_fields)) {
2478 2478
 
2479
-				   			$html[] =  "<td class='hidden-xs hidden-sm hidden-md'>";
2479
+				   			$html[] = "<td class='hidden-xs hidden-sm hidden-md'>";
2480 2480
 
2481 2481
 				   			//booleans
2482
-							if($field['type']=="tinyint(1)")	{
2483
-								if($option[$field['name']] == "0")			{ $html[] = _("No"); }
2484
-								elseif($option[$field['name']] == "1")		{ $html[] = _("Yes"); }
2482
+							if ($field['type'] == "tinyint(1)") {
2483
+								if ($option[$field['name']] == "0") { $html[] = _("No"); }
2484
+								elseif ($option[$field['name']] == "1") { $html[] = _("Yes"); }
2485 2485
 							}
2486 2486
 							//text
2487
-							elseif($field['type']=="text") {
2488
-								if(strlen($option[$field['name']])>0)		{ $html[] = "<i class='fa fa-gray fa-comment' rel='tooltip' data-container='body' data-html='true' title='".str_replace("\n", "<br>", $option[$field['name']])."'>"; }
2489
-								else												{ $html[] = ""; }
2487
+							elseif ($field['type'] == "text") {
2488
+								if (strlen($option[$field['name']]) > 0) { $html[] = "<i class='fa fa-gray fa-comment' rel='tooltip' data-container='body' data-html='true' title='".str_replace("\n", "<br>", $option[$field['name']])."'>"; }
2489
+								else { $html[] = ""; }
2490 2490
 							}
2491 2491
 							else {
2492 2492
 								$html[] = $option[$field['name']];
2493 2493
 
2494 2494
 							}
2495 2495
 
2496
-				   			$html[] =  "</td>";
2496
+				   			$html[] = "</td>";
2497 2497
 			   			}
2498 2498
 			    	}
2499 2499
 			    }
2500 2500
 
2501 2501
 				# set permission
2502
-				$permission = $this->check_prefix_permission ($user);
2502
+				$permission = $this->check_prefix_permission($user);
2503 2503
 
2504 2504
 				$html[] = "	<td class='actions' style='padding:0px;'>";
2505 2505
 				$html[] = "	<div class='btn-group'>";
2506 2506
 
2507
-				if($permission>2) {
2507
+				if ($permission > 2) {
2508 2508
 					$html[] = "		<button class='btn btn-xs btn-default editPSTN' data-action='edit'   data-id='".$option['id']."'><i class='fa fa-pencil'></i></button>";
2509 2509
 					$html[] = "		<button class='btn btn-xs btn-default editPSTN' data-action='delete' data-id='".$option['id']."'><i class='fa fa-times'></i></button>";
2510 2510
 				}
@@ -2521,10 +2521,10 @@  discard block
 block discarded – undo
2521 2521
                 $old_count = $count;
2522 2522
 			}
2523 2523
 
2524
-			if ( $option === false ) { $parent = array_pop( $parent_stack ); }
2524
+			if ($option === false) { $parent = array_pop($parent_stack); }
2525 2525
 			# Has slave subnets
2526
-			elseif ( !empty( $children_prefixes[$option['id']] ) ) {
2527
-				array_push( $parent_stack, $option['master'] );
2526
+			elseif (!empty($children_prefixes[$option['id']])) {
2527
+				array_push($parent_stack, $option['master']);
2528 2528
 				$parent = $option['id'];
2529 2529
 			}
2530 2530
 		}
@@ -2542,25 +2542,25 @@  discard block
 block discarded – undo
2542 2542
 	 * @param bool $prefixId (default: false)
2543 2543
 	 * @return mixed
2544 2544
 	 */
2545
-	public function print_masterprefix_dropdown_menu ($prefixId = false) {
2545
+	public function print_masterprefix_dropdown_menu($prefixId = false) {
2546 2546
 
2547 2547
 		# initialize vars
2548 2548
 		$children_prefixes = array();
2549 2549
 		$parent_stack_prefixes = array();
2550 2550
 		$html = array();
2551
-		$rootId = 0;			// root is 0
2552
-		$parent = $rootId;      // initializing $parent as the root
2551
+		$rootId = 0; // root is 0
2552
+		$parent = $rootId; // initializing $parent as the root
2553 2553
 
2554 2554
 		# fetch all prefixes in section
2555
-		$all_prefixes = $this->fetch_all_prefixes ();
2555
+		$all_prefixes = $this->fetch_all_prefixes();
2556 2556
 		if (!is_array($all_prefixes)) $all_prefixes = array();
2557 2557
 		# folder or subnet?
2558
-		foreach($all_prefixes as $s) {
2558
+		foreach ($all_prefixes as $s) {
2559 2559
 			$children_prefixes[$s->master][] = (array) $s;
2560 2560
 		}
2561 2561
 
2562 2562
 		# loop will be false if the root has no children (i.e., an empty menu!)
2563
-		$loop  = !empty( $children_prefixes[$rootId] );
2563
+		$loop = !empty($children_prefixes[$rootId]);
2564 2564
 
2565 2565
 		# structure
2566 2566
 		$html[] = "<select name='master' class='form-control input-sm input-w-auto input-max-200'>";
@@ -2569,29 +2569,29 @@  discard block
 block discarded – undo
2569 2569
 		$html[] = "<option value='0'>"._("Root subnet")."</option>";
2570 2570
 
2571 2571
 		# return table content (tr and td's) - subnets
2572
-		if(sizeof($children_prefixes)>0) {
2573
-		reset( $children_prefixes[$parent] );
2574
-		while ( $loop && ( ( $option = current( $children_prefixes[$parent] ) ) || ( $parent > $rootId ) ) )
2572
+		if (sizeof($children_prefixes) > 0) {
2573
+		reset($children_prefixes[$parent]);
2574
+		while ($loop && (($option = current($children_prefixes[$parent])) || ($parent > $rootId)))
2575 2575
 		{
2576
-			next( $children_prefixes[$parent] );
2576
+			next($children_prefixes[$parent]);
2577 2577
 			# repeat
2578
-			$repeat  = str_repeat( " &nbsp;&nbsp; ", ( count($parent_stack_prefixes)) );
2578
+			$repeat = str_repeat(" &nbsp;&nbsp; ", (count($parent_stack_prefixes)));
2579 2579
 
2580 2580
 			# selected
2581 2581
 			$selected = $option['id'] == $prefixId ? "selected='selected'" : "";
2582
-			if($option['id'])
2582
+			if ($option['id'])
2583 2583
             $html[] = "<option value='".$option['id']."' $selected>$repeat ".$option['prefix']." (".$option['name'].")</option>";
2584 2584
 
2585
-			if ( $option === false ) { $parent = array_pop( $parent_stack_prefixes ); }
2585
+			if ($option === false) { $parent = array_pop($parent_stack_prefixes); }
2586 2586
 			# Has slave subnets
2587
-			elseif ( !empty( $children_prefixes[$option['id']] ) ) {
2588
-				array_push( $parent_stack_prefixes, $option['master'] );
2587
+			elseif (!empty($children_prefixes[$option['id']])) {
2588
+				array_push($parent_stack_prefixes, $option['master']);
2589 2589
 				$parent = $option['id'];
2590 2590
 			}		}
2591 2591
 		}
2592 2592
 		$html[] = "</select>";
2593 2593
 		# join and print
2594
-		print implode( "\n", $html );
2594
+		print implode("\n", $html);
2595 2595
 	}
2596 2596
 
2597 2597
 
@@ -2607,18 +2607,18 @@  discard block
 block discarded – undo
2607 2607
 	 * @param array $numbers
2608 2608
 	 * @return array
2609 2609
 	 */
2610
-	public function compress_pstn_ranges ($numbers, $state=4) {
2610
+	public function compress_pstn_ranges($numbers, $state = 4) {
2611 2611
     	# set size
2612 2612
     	$size = sizeof($numbers);
2613 2613
     	// vars
2614 2614
     	$numbers_formatted = array();
2615 2615
 
2616 2616
 		# loop through IP addresses
2617
-		for($c=0; $c<$size; $c++) {
2617
+		for ($c = 0; $c < $size; $c++) {
2618 2618
 			# ignore already comressed range
2619
-			if($numbers[$c]->class!="compressed-range") {
2619
+			if ($numbers[$c]->class != "compressed-range") {
2620 2620
 				# gap between this and previous
2621
-				if(gmp_strval( @gmp_sub($numbers[$c]->number, $numbers[$c-1]->number)) != 1) {
2621
+				if (gmp_strval(@gmp_sub($numbers[$c]->number, $numbers[$c - 1]->number)) != 1) {
2622 2622
 					# remove index flag
2623 2623
 					unset($fIndex);
2624 2624
 					# save IP address
@@ -2626,9 +2626,9 @@  discard block
 block discarded – undo
2626 2626
 					$numbers_formatted[$c]->class = "ip";
2627 2627
 
2628 2628
 					# no gap this -> next
2629
-					if(gmp_strval( @gmp_sub($numbers[$c]->number, $numbers[$c+1]->number)) == -1 && $numbers[$c]->state==$state) {
2629
+					if (gmp_strval(@gmp_sub($numbers[$c]->number, $numbers[$c + 1]->number)) == -1 && $numbers[$c]->state == $state) {
2630 2630
 						//is state the same?
2631
-						if($numbers[$c]->state==$numbers[$c+1]->state) {
2631
+						if ($numbers[$c]->state == $numbers[$c + 1]->state) {
2632 2632
 							$fIndex = $c;
2633 2633
 							$numbers_formatted[$fIndex]->startIP = $numbers[$c]->number;
2634 2634
 							$numbers_formatted[$c]->class = "compressed-range";
@@ -2638,9 +2638,9 @@  discard block
 block discarded – undo
2638 2638
 				# no gap between this and previous
2639 2639
 				else {
2640 2640
 					# is state same as previous?
2641
-					if($numbers[$c]->state==$numbers[$c-1]->state && $numbers[$c]->state==$state) {
2642
-						$numbers_formatted[$fIndex]->stopIP = $numbers[$c]->number;	//adds dhcp state
2643
-						$numbers_formatted[$fIndex]->numHosts = gmp_strval( gmp_add(@gmp_sub($numbers[$c]->number, $numbers_formatted[$fIndex]->number),1));	//add number of hosts
2641
+					if ($numbers[$c]->state == $numbers[$c - 1]->state && $numbers[$c]->state == $state) {
2642
+						$numbers_formatted[$fIndex]->stopIP = $numbers[$c]->number; //adds dhcp state
2643
+						$numbers_formatted[$fIndex]->numHosts = gmp_strval(gmp_add(@gmp_sub($numbers[$c]->number, $numbers_formatted[$fIndex]->number), 1)); //add number of hosts
2644 2644
 					}
2645 2645
 					# different state
2646 2646
 					else {
@@ -2650,7 +2650,7 @@  discard block
 block discarded – undo
2650 2650
 						$numbers_formatted[$c] = $numbers[$c];
2651 2651
 						$numbers_formatted[$c]->class = "ip";
2652 2652
 						# check if state is same as next to start range
2653
-						if($numbers[$c]->state==@$numbers[$c+1]->state &&  gmp_strval( @gmp_sub($numbers[$c]->number, $numbers[$c+1]->number)) == -1 && $numbers[$c]->state==$state) {
2653
+						if ($numbers[$c]->state == @$numbers[$c + 1]->state && gmp_strval(@gmp_sub($numbers[$c]->number, $numbers[$c + 1]->number)) == -1 && $numbers[$c]->state == $state) {
2654 2654
 							$fIndex = $c;
2655 2655
 							$numbers_formatted[$fIndex]->startIP = $numbers[$c]->number;
2656 2656
 							$numbers_formatted[$c]->class = "compressed-range";
@@ -2677,26 +2677,26 @@  discard block
 block discarded – undo
2677 2677
 	 * @param obj $numbers	     //netmask in decimal format
2678 2678
 	 * @return array
2679 2679
 	 */
2680
-	public function calculate_prefix_usege ($prefix, $numbers) {
2680
+	public function calculate_prefix_usege($prefix, $numbers) {
2681 2681
 	    # calculate max number of hosts
2682 2682
 	    $details = array();
2683 2683
 	    $details['maxhosts'] = ($prefix->stop - $prefix->start + 1);
2684 2684
 
2685 2685
 		# get IP address count per address type
2686
-		if($numbers!==false) {
2687
-		    $details_p = $this->calculate_prefix_usage_sort_numbers ($numbers);
2688
-    	    foreach($this->address_types as $t) {
2689
-    		    $details[$t['type']."_percent"] = round( ( ($details_p[$t['type']] * 100) / $details['maxhosts']), 2 );
2686
+		if ($numbers !== false) {
2687
+		    $details_p = $this->calculate_prefix_usage_sort_numbers($numbers);
2688
+    	    foreach ($this->address_types as $t) {
2689
+    		    $details[$t['type']."_percent"] = round((($details_p[$t['type']] * 100) / $details['maxhosts']), 2);
2690 2690
     	    }
2691 2691
 
2692 2692
             # calculate free hosts
2693
-            $details['freehosts'] =  $details['maxhosts'] - sizeof($numbers);
2693
+            $details['freehosts'] = $details['maxhosts'] - sizeof($numbers);
2694 2694
         }
2695 2695
         else {
2696
-            $details['freehosts'] =  $details['maxhosts'];
2696
+            $details['freehosts'] = $details['maxhosts'];
2697 2697
         }
2698 2698
 	    # calculate use percentage for each type
2699
-	    $details['freehosts_percent'] = round( ( ($details['freehosts'] * 100) / $details['maxhosts']), 2 );
2699
+	    $details['freehosts_percent'] = round((($details['freehosts'] * 100) / $details['maxhosts']), 2);
2700 2700
 
2701 2701
 	    # result
2702 2702
 	    return $details;
@@ -2709,18 +2709,18 @@  discard block
 block discarded – undo
2709 2709
 	 * @param mixed $numbers
2710 2710
 	 * @return array
2711 2711
 	 */
2712
-	public function calculate_prefix_usage_sort_numbers ($numbers) {
2712
+	public function calculate_prefix_usage_sort_numbers($numbers) {
2713 2713
 		$count = array();
2714
-		$count['used'] = 0;				//initial sum count
2714
+		$count['used'] = 0; //initial sum count
2715 2715
 		# fetch address types
2716 2716
 		$this->get_addresses_types();
2717 2717
 		# create array of keys with initial value of 0
2718
-		foreach($this->address_types as $a) {
2718
+		foreach ($this->address_types as $a) {
2719 2719
 			$count[$a['type']] = 0;
2720 2720
 		}
2721 2721
 		# count
2722
-		if($numbers!==false) {
2723
-			foreach($numbers as $n) {
2722
+		if ($numbers !== false) {
2723
+			foreach ($numbers as $n) {
2724 2724
 				$count[$this->translate_address_type($n->state)]++;
2725 2725
 				$count['used'] = gmp_strval(gmp_add($count['used'], 1));
2726 2726
 			}
@@ -2734,15 +2734,15 @@  discard block
 block discarded – undo
2734 2734
 	 *
2735 2735
 	 * @access public
2736 2736
 	 */
2737
-	public function get_addresses_types () {
2737
+	public function get_addresses_types() {
2738 2738
 		# from cache
2739
-		if($this->address_types == null) {
2739
+		if ($this->address_types == null) {
2740 2740
         	# fetch
2741
-        	$types = $this->fetch_all_objects ("ipTags", "id");
2741
+        	$types = $this->fetch_all_objects("ipTags", "id");
2742 2742
 
2743 2743
             # save to array
2744 2744
 			$types_out = array();
2745
-			foreach($types as $t) {
2745
+			foreach ($types as $t) {
2746 2746
 				$types_out[$t->id] = (array) $t;
2747 2747
 			}
2748 2748
 			# save to cache
@@ -2759,7 +2759,7 @@  discard block
 block discarded – undo
2759 2759
 	 * @param mixed $index
2760 2760
 	 * @return array
2761 2761
 	 */
2762
-	public function translate_address_type ($index) {
2762
+	public function translate_address_type($index) {
2763 2763
 		# fetch
2764 2764
 		$this->get_addresses_types();
2765 2765
 		# return
@@ -2791,10 +2791,10 @@  discard block
 block discarded – undo
2791 2791
      * @param bool count (default: false)
2792 2792
      * @return array|bool
2793 2793
      */
2794
-    public function fetch_location_objects ($id = false, $count = false) {
2794
+    public function fetch_location_objects($id = false, $count = false) {
2795 2795
         // check
2796
-        if(is_numeric($id)) {
2797
-            $id = $this->Database->escape ($id);
2796
+        if (is_numeric($id)) {
2797
+            $id = $this->Database->escape($id);
2798 2798
             // count ?
2799 2799
             $select = $count ? "count(*) as cnt " : "*";
2800 2800
             // query
@@ -2848,7 +2848,7 @@  discard block
 block discarded – undo
2848 2848
     		catch (Exception $e) { $this->Result->show("danger", $e->getMessage(), true); }
2849 2849
 
2850 2850
     		// return
2851
-    		return sizeof($objects)>0 ? $objects : false;
2851
+    		return sizeof($objects) > 0 ? $objects : false;
2852 2852
         }
2853 2853
         else {
2854 2854
             return false;
@@ -2871,13 +2871,13 @@  discard block
 block discarded – undo
2871 2871
 	 *
2872 2872
 	 * @return false|array
2873 2873
 	 */
2874
-	public function fetch_all_circuits ($custom_circuit_fields = array ()) {
2874
+	public function fetch_all_circuits($custom_circuit_fields = array()) {
2875 2875
 		// set query
2876 2876
 		$query[] = "select";
2877 2877
 		$query[] = "c.id,c.cid,c.type,c.device1,c.location1,c.device2,c.location2,c.customer_id,p.name,p.description,p.contact,c.capacity,p.id as pid,c.status";
2878 2878
 		// custom fields
2879
-		if(is_array($custom_circuit_fields)) {
2880
-			if(sizeof($custom_circuit_fields)>0) {
2879
+		if (is_array($custom_circuit_fields)) {
2880
+			if (sizeof($custom_circuit_fields) > 0) {
2881 2881
 				foreach ($custom_circuit_fields as $f) {
2882 2882
 					$query[] = ",c.`".$f['name']."`";
2883 2883
 				}
@@ -2891,7 +2891,7 @@  discard block
 block discarded – undo
2891 2891
 			$this->Result->show("danger", $e->getMessage(), true);
2892 2892
 		}
2893 2893
 		// return
2894
-		return sizeof($circuits)>0 ? $circuits : false;
2894
+		return sizeof($circuits) > 0 ? $circuits : false;
2895 2895
 	}
2896 2896
 
2897 2897
 	/**
@@ -2901,7 +2901,7 @@  discard block
 block discarded – undo
2901 2901
 	 * @param  int $circuit_id
2902 2902
 	 * @return array|false
2903 2903
 	 */
2904
-	public function fetch_all_logical_circuits_using_circuit ($circuit_id) {
2904
+	public function fetch_all_logical_circuits_using_circuit($circuit_id) {
2905 2905
 		// set query
2906 2906
 		$query[] = "select";
2907 2907
 		$query[] = "lc.*";
@@ -2915,7 +2915,7 @@  discard block
 block discarded – undo
2915 2915
 			$this->Result->show("danger", $e->getMessage(), true);
2916 2916
 		}
2917 2917
 		// return
2918
-		return sizeof($circuits)>0 ? $circuits : false;
2918
+		return sizeof($circuits) > 0 ? $circuits : false;
2919 2919
 	}
2920 2920
 
2921 2921
 	/**
@@ -2925,7 +2925,7 @@  discard block
 block discarded – undo
2925 2925
 	 * @param  int $logical_circuit_id
2926 2926
 	 * @return array|false
2927 2927
 	 */
2928
-  	public function fetch_all_logical_circuit_members ($logical_circuit_id) {
2928
+  	public function fetch_all_logical_circuit_members($logical_circuit_id) {
2929 2929
   		// set query
2930 2930
 		$query2[] = "SELECT";
2931 2931
 		$query2[] = "c.*";
@@ -2938,7 +2938,7 @@  discard block
 block discarded – undo
2938 2938
 		catch (Exception $e) {
2939 2939
 			$this->Result->show("danger", $e->getMessage(), true);
2940 2940
 		}
2941
-		return sizeof($circuits)>0 ? $circuits : false;
2941
+		return sizeof($circuits) > 0 ? $circuits : false;
2942 2942
 	}
2943 2943
 
2944 2944
 	/**
@@ -2951,13 +2951,13 @@  discard block
 block discarded – undo
2951 2951
 	 *
2952 2952
 	 * @return false|array
2953 2953
 	 */
2954
-	public function fetch_all_provider_circuits ($provider_id, $custom_circuit_fields = array ()) {
2954
+	public function fetch_all_provider_circuits($provider_id, $custom_circuit_fields = array()) {
2955 2955
 		// set query
2956 2956
 		$query[] = "select";
2957 2957
 		$query[] = "c.id,c.cid,c.type,c.device1,c.location1,c.device2,c.location2,p.name,p.description,p.contact,c.capacity,p.id as pid,c.status";
2958 2958
 		// custom fields
2959
-		if(is_array($custom_circuit_fields)) {
2960
-			if(sizeof($custom_circuit_fields)>0) {
2959
+		if (is_array($custom_circuit_fields)) {
2960
+			if (sizeof($custom_circuit_fields) > 0) {
2961 2961
 				foreach ($custom_circuit_fields as $f) {
2962 2962
 					$query[] = ",c.`".$f['name']."`";
2963 2963
 				}
@@ -2971,7 +2971,7 @@  discard block
 block discarded – undo
2971 2971
 			$this->Result->show("danger", $e->getMessage(), true);
2972 2972
 		}
2973 2973
 		// return
2974
-		return sizeof($circuits)>0 ? $circuits : false;
2974
+		return sizeof($circuits) > 0 ? $circuits : false;
2975 2975
 	}
2976 2976
 
2977 2977
 
@@ -2984,7 +2984,7 @@  discard block
 block discarded – undo
2984 2984
 	 *
2985 2985
 	 * @return false|array
2986 2986
 	 */
2987
-	public function fetch_all_device_circuits ($device_id) {
2987
+	public function fetch_all_device_circuits($device_id) {
2988 2988
 		// set query
2989 2989
 		$query = "select
2990 2990
 					c.id,c.cid,c.type,c.device1,c.location1,c.device2,c.location2,p.name,p.description,p.contact,c.capacity,p.id as pid,c.status
@@ -2996,7 +2996,7 @@  discard block
 block discarded – undo
2996 2996
 			$this->Result->show("danger", $e->getMessage(), true);
2997 2997
 		}
2998 2998
 		// return
2999
-		return sizeof($circuits)>0 ? $circuits : false;
2999
+		return sizeof($circuits) > 0 ? $circuits : false;
3000 3000
 	}
3001 3001
 
3002 3002
 	/**
@@ -3020,43 +3020,43 @@  discard block
 block discarded – undo
3020 3020
 	 *
3021 3021
 	 * @return false|array
3022 3022
 	 */
3023
-	public function reformat_circuit_location ($deviceId = null, $locationId = null) {
3023
+	public function reformat_circuit_location($deviceId = null, $locationId = null) {
3024 3024
 		// check device
3025
-		if(is_numeric($deviceId) && $deviceId!=0) {
3025
+		if (is_numeric($deviceId) && $deviceId != 0) {
3026 3026
 			// fetch device
3027
-			$device = $this->fetch_object ("devices", "id", $deviceId);
3027
+			$device = $this->fetch_object("devices", "id", $deviceId);
3028 3028
 			// check
3029 3029
 			if ($device === false) {
3030 3030
 				return false;
3031 3031
 			}
3032 3032
 			else {
3033
-				$array = array (
3033
+				$array = array(
3034 3034
 								"type"     => "devices",
3035 3035
 								"id"       => $device->id,
3036 3036
 								"name"     => $device->hostname,
3037 3037
 								"icon" 	   => "",
3038
-								"location" => is_null($device->location)||$device->location==0 ? NULL : $device->location,
3039
-								"rack"     => is_null($device->rack)||$device->rack==0 ? NULL : $device->rack
3038
+								"location" => is_null($device->location) || $device->location == 0 ? NULL : $device->location,
3039
+								"rack"     => is_null($device->rack) || $device->rack == 0 ? NULL : $device->rack
3040 3040
 				                );
3041 3041
 				// check rack location if not configured
3042
-				if ($array['location']==NULL && $array['rack']!=NULL) {
3043
-					$rack_location = $this->fetch_object ("racks", "id", $array['rack']);
3044
-					$array['location'] = $rack_location!==false ? $rack_location->location : NULL;
3042
+				if ($array['location'] == NULL && $array['rack'] != NULL) {
3043
+					$rack_location = $this->fetch_object("racks", "id", $array['rack']);
3044
+					$array['location'] = $rack_location !== false ? $rack_location->location : NULL;
3045 3045
 				}
3046 3046
 				// result
3047 3047
 				return $array;
3048 3048
 			}
3049 3049
 		}
3050 3050
 		// check location
3051
-		elseif (is_numeric($locationId) && $locationId!=0) {
3051
+		elseif (is_numeric($locationId) && $locationId != 0) {
3052 3052
 			// fetch location
3053
-			$location = $this->fetch_object ("locations", "id", $locationId);
3053
+			$location = $this->fetch_object("locations", "id", $locationId);
3054 3054
 			// check
3055 3055
 			if ($device === false) {
3056 3056
 				return false;
3057 3057
 			}
3058 3058
 			else {
3059
-				$array = array (
3059
+				$array = array(
3060 3060
 								"type"     => "locations",
3061 3061
 								"id"       => $location->id,
3062 3062
 								"name"     => $location->name,
@@ -3079,7 +3079,7 @@  discard block
 block discarded – undo
3079 3079
 	 * @param string $search (default: false)
3080 3080
 	 * @return array|bool
3081 3081
 	 */
3082
-	public function fetch_all_domains_and_vlans ($search = false) {
3082
+	public function fetch_all_domains_and_vlans($search = false) {
3083 3083
 		// set query
3084 3084
 		$query[] = "select `d`.`name` as `domainName`,";
3085 3085
 		$query[] = "	`d`.`description` as `domainDescription`,";
@@ -3090,7 +3090,7 @@  discard block
 block discarded – undo
3090 3090
 		$query[] = "	`v`.`description` as `description`,";
3091 3091
 		$query[] = "	`v`.`customer_id` as `customer_id`,";
3092 3092
 		// fetch custom fields
3093
-		$custom_vlan_fields = $this->fetch_custom_fields ("vlans");
3093
+		$custom_vlan_fields = $this->fetch_custom_fields("vlans");
3094 3094
 		if ($custom_vlan_fields != false) {
3095 3095
     		foreach ($custom_vlan_fields as $f) {
3096 3096
         		$query[] = "  `v`.`$f[name]` as `$f[name]`,";
@@ -3105,18 +3105,18 @@  discard block
 block discarded – undo
3105 3105
 		$query[] = "	order by `v`.`number` asc;";
3106 3106
 
3107 3107
 		// fetch
3108
-		try { $domains = $this->Database->getObjectsQuery(implode("\n",$query)); }
3108
+		try { $domains = $this->Database->getObjectsQuery(implode("\n", $query)); }
3109 3109
 		catch (Exception $e) { $this->Result->show("danger", $e->getMessage(), true); }
3110 3110
 		// filter if requested
3111
-		if ($search !== false && sizeof($domains)>0) {
3111
+		if ($search !== false && sizeof($domains) > 0) {
3112 3112
 			foreach ($domains as $k=>$d) {
3113
-				if (strpos($d->number, $search)===false && strpos($d->name, $search)===false && strpos($d->description, $search)===false) {
3113
+				if (strpos($d->number, $search) === false && strpos($d->name, $search) === false && strpos($d->description, $search) === false) {
3114 3114
 					unset($domains[$k]);
3115 3115
 				}
3116 3116
 			}
3117 3117
 		}
3118 3118
 		// return
3119
-		return sizeof($domains)>0 ? $domains : false;
3119
+		return sizeof($domains) > 0 ? $domains : false;
3120 3120
 	}
3121 3121
 
3122 3122
 	/**
@@ -3126,14 +3126,14 @@  discard block
 block discarded – undo
3126 3126
 	 * @param  int $customer_id
3127 3127
 	 * @return void
3128 3128
 	 */
3129
-	public function fetch_customer_objects ($customer_id) {
3129
+	public function fetch_customer_objects($customer_id) {
3130 3130
 		// out
3131 3131
 		$out = [];
3132 3132
 		// fetch
3133
-		if(is_numeric($customer_id)) {
3133
+		if (is_numeric($customer_id)) {
3134 3134
 			foreach ($this->get_customer_object_types() as $table=>$name) {
3135
-				$objects = $this->fetch_multiple_objects ($table, "customer_id", $customer_id, $this->get_customer_object_types_sorts ($table));
3136
-				if ($objects!==false) {
3135
+				$objects = $this->fetch_multiple_objects($table, "customer_id", $customer_id, $this->get_customer_object_types_sorts($table));
3136
+				if ($objects !== false) {
3137 3137
 					$out[$table] = $objects;
3138 3138
 				}
3139 3139
 			}
@@ -3148,7 +3148,7 @@  discard block
 block discarded – undo
3148 3148
 	 * @method get_customer_object_types
3149 3149
 	 * @return array
3150 3150
 	 */
3151
-	public function get_customer_object_types () {
3151
+	public function get_customer_object_types() {
3152 3152
 		return [
3153 3153
 				"subnets"     => "Subnets",
3154 3154
 				"ipaddresses" => "Addresses",
@@ -3166,7 +3166,7 @@  discard block
 block discarded – undo
3166 3166
 	 * @param  string $type
3167 3167
 	 * @return string
3168 3168
 	 */
3169
-	private function get_customer_object_types_sorts ($type) {
3169
+	private function get_customer_object_types_sorts($type) {
3170 3170
 		switch ($type) {
3171 3171
 			case "subnets"     : return "subnet";
3172 3172
 			case "ipaddresses" : return "ip_addr";
@@ -3187,20 +3187,20 @@  discard block
 block discarded – undo
3187 3187
 	 * @param array $custom_address_fields
3188 3188
 	 * @return array
3189 3189
 	 */
3190
-	public function parse_import_file ($filetype = "xls", $subnet = object, $custom_address_fields) {
3190
+	public function parse_import_file($filetype = "xls", $subnet = object, $custom_address_fields) {
3191 3191
     	# start object and get settings
3192
-    	$this->settings ();
3193
-    	$this->Subnets = new Subnets ($this->Database);
3192
+    	$this->settings();
3193
+    	$this->Subnets = new Subnets($this->Database);
3194 3194
 
3195 3195
         # CSV
3196
-        if (strtolower($filetype) == "csv")     { $outFile = $this->parse_import_file_csv (); }
3196
+        if (strtolower($filetype) == "csv") { $outFile = $this->parse_import_file_csv(); }
3197 3197
         # XLS
3198
-        elseif(strtolower($filetype) == "xls")  { $outFile = $this->parse_import_file_xls ($subnet, $custom_address_fields); }
3198
+        elseif (strtolower($filetype) == "xls") { $outFile = $this->parse_import_file_xls($subnet, $custom_address_fields); }
3199 3199
         # error
3200
-        else                                    { $this->Result->show("danger", _('Invalid filetype'), true); }
3200
+        else { $this->Result->show("danger", _('Invalid filetype'), true); }
3201 3201
 
3202 3202
         # validate
3203
-        return $this->parse_validate_file ($outFile, $subnet);
3203
+        return $this->parse_validate_file($outFile, $subnet);
3204 3204
 	}
3205 3205
 
3206 3206
 	/**
@@ -3211,10 +3211,10 @@  discard block
 block discarded – undo
3211 3211
 	 * @param array $custom_address_fields
3212 3212
 	 * @return mixed
3213 3213
 	 */
3214
-	private function parse_import_file_xls ($subnet, $custom_address_fields) {
3214
+	private function parse_import_file_xls($subnet, $custom_address_fields) {
3215 3215
      	# get excel object
3216
-    	require_once(dirname(__FILE__).'/../../functions/php-excel-reader/excel_reader2.php');				//excel reader 2.21
3217
-    	$data = new Spreadsheet_Excel_Reader(dirname(__FILE__) . '/../../app/subnets/import-subnet/upload/import.xls', false, 'utf-8');
3216
+    	require_once(dirname(__FILE__).'/../../functions/php-excel-reader/excel_reader2.php'); //excel reader 2.21
3217
+    	$data = new Spreadsheet_Excel_Reader(dirname(__FILE__).'/../../app/subnets/import-subnet/upload/import.xls', false, 'utf-8');
3218 3218
 
3219 3219
     	//get number of rows
3220 3220
     	$numRows = $data->rowcount(0);
@@ -3226,26 +3226,26 @@  discard block
 block discarded – undo
3226 3226
     	$this->csv_delimiter = ";";
3227 3227
 
3228 3228
     	//get all to array!
3229
-    	for($m=0; $m < $numRows; $m++) {
3229
+    	for ($m = 0; $m < $numRows; $m++) {
3230 3230
 
3231 3231
     		//IP must be present!
3232
-    		if(filter_var($data->val($m,'A'), FILTER_VALIDATE_IP)) {
3232
+    		if (filter_var($data->val($m, 'A'), FILTER_VALIDATE_IP)) {
3233 3233
         		//for multicast
3234
-        		$mac = $data->val($m,'F');
3235
-        		if ($this->settings->enableMulticast=="1") {
3236
-            		if (strlen($data->val($m,'F'))==0 && $this->Subnets->is_multicast($data->val($m,'A')))    {
3237
-                		$mac = $this->Subnets->create_multicast_mac ($data->val($m,'A'));
3234
+        		$mac = $data->val($m, 'F');
3235
+        		if ($this->settings->enableMulticast == "1") {
3236
+            		if (strlen($data->val($m, 'F')) == 0 && $this->Subnets->is_multicast($data->val($m, 'A'))) {
3237
+                		$mac = $this->Subnets->create_multicast_mac($data->val($m, 'A'));
3238 3238
                     }
3239 3239
                 }
3240 3240
 
3241
-    			$outFile[$m]  = $data->val($m,'A').$this->csv_delimiter.$data->val($m,'B').$this->csv_delimiter.$data->val($m,'C').$this->csv_delimiter.$data->val($m,'D').$this->csv_delimiter;
3242
-    			$outFile[$m] .= $data->val($m,'E').$this->csv_delimiter.$mac.$this->csv_delimiter.$data->val($m,'G').$this->csv_delimiter.$data->val($m,'H').$this->csv_delimiter;
3243
-    			$outFile[$m] .= $data->val($m,'I').$this->csv_delimiter.$data->val($m,'J').$this->csv_delimiter.$data->val($m,'K');
3241
+    			$outFile[$m]  = $data->val($m, 'A').$this->csv_delimiter.$data->val($m, 'B').$this->csv_delimiter.$data->val($m, 'C').$this->csv_delimiter.$data->val($m, 'D').$this->csv_delimiter;
3242
+    			$outFile[$m] .= $data->val($m, 'E').$this->csv_delimiter.$mac.$this->csv_delimiter.$data->val($m, 'G').$this->csv_delimiter.$data->val($m, 'H').$this->csv_delimiter;
3243
+    			$outFile[$m] .= $data->val($m, 'I').$this->csv_delimiter.$data->val($m, 'J').$this->csv_delimiter.$data->val($m, 'K');
3244 3244
     			//add custom fields
3245
-    			if(sizeof($custom_address_fields) > 0) {
3245
+    			if (sizeof($custom_address_fields) > 0) {
3246 3246
     				$currLett = "L";
3247
-    				foreach($custom_address_fields as $field) {
3248
-    					$outFile[$m] .= $this->csv_delimiter.$data->val($m,$currLett++);
3247
+    				foreach ($custom_address_fields as $field) {
3248
+    					$outFile[$m] .= $this->csv_delimiter.$data->val($m, $currLett++);
3249 3249
     				}
3250 3250
     			}
3251 3251
     			$outFile[$m] = $this->convert_encoding_to_UTF8($outFile[$m]);
@@ -3261,9 +3261,9 @@  discard block
 block discarded – undo
3261 3261
 	 * @access private
3262 3262
 	 * @return array
3263 3263
 	 */
3264
-	private function parse_import_file_csv () {
3264
+	private function parse_import_file_csv() {
3265 3265
     	// get file to string
3266
-		$handle = fopen(dirname(__FILE__) . '/../../app/subnets/import-subnet/upload/import.csv', "r");
3266
+		$handle = fopen(dirname(__FILE__).'/../../app/subnets/import-subnet/upload/import.csv', "r");
3267 3267
 		if ($handle) {
3268 3268
 		    while (($outFile[] = fgets($handle)) !== false) {}
3269 3269
 		    fclose($handle);
@@ -3272,29 +3272,29 @@  discard block
 block discarded – undo
3272 3272
 		}
3273 3273
 
3274 3274
     	// delimiter
3275
-    	if(isset($outFile[0]))
3276
-    	$this->set_csv_delimiter ($outFile[0]);
3275
+    	if (isset($outFile[0]))
3276
+    	$this->set_csv_delimiter($outFile[0]);
3277 3277
 
3278 3278
     	/* validate IP */
3279
-    	foreach($outFile as $k=>$v) {
3279
+    	foreach ($outFile as $k=>$v) {
3280 3280
         	//put it to array
3281
-        	$field = str_getcsv ($v, $this->csv_delimiter);
3281
+        	$field = str_getcsv($v, $this->csv_delimiter);
3282 3282
 
3283
-        	if(!filter_var($field[0], FILTER_VALIDATE_IP)) {
3283
+        	if (!filter_var($field[0], FILTER_VALIDATE_IP)) {
3284 3284
             	unset($outFile[$k]);
3285 3285
             	unset($field);
3286 3286
         	}
3287 3287
         	else {
3288 3288
             	# mac
3289
-        		if ($this->settings->enableMulticast=="1") {
3290
-            		if (strlen($field[5])==0 && $this->Subnets->is_multicast($field[0]))  {
3291
-                		$field[5] = $this->Subnets->create_multicast_mac ($field[0]);
3289
+        		if ($this->settings->enableMulticast == "1") {
3290
+            		if (strlen($field[5]) == 0 && $this->Subnets->is_multicast($field[0])) {
3291
+                		$field[5] = $this->Subnets->create_multicast_mac($field[0]);
3292 3292
                     }
3293 3293
         		}
3294 3294
         	}
3295 3295
 
3296 3296
         	# save
3297
-        	if(isset($field)) {
3297
+        	if (isset($field)) {
3298 3298
 	        	$outFile[$k] = implode($this->csv_delimiter, $field);
3299 3299
     		}
3300 3300
     	}
@@ -3310,9 +3310,9 @@  discard block
 block discarded – undo
3310 3310
 	 * @param  string $outFile
3311 3311
 	 * @return string
3312 3312
 	 */
3313
-	public function set_csv_delimiter ($outFile) {
3313
+	public function set_csv_delimiter($outFile) {
3314 3314
 		// must be string
3315
-		if(is_string($outFile)) {
3315
+		if (is_string($outFile)) {
3316 3316
 			// count occurences
3317 3317
 			$cnt_coma  = substr_count($outFile, ",");
3318 3318
 			$cnt_colon = substr_count($outFile, ";");
@@ -3334,33 +3334,33 @@  discard block
 block discarded – undo
3334 3334
 	 * @param object $subnet
3335 3335
 	 * @return void
3336 3336
 	 */
3337
-	private function parse_validate_file ($outFile = array(), $subnet = object) {
3337
+	private function parse_validate_file($outFile = array(), $subnet = object) {
3338 3338
     	$result = array();
3339 3339
     	# present ?
3340
-    	if (sizeof($outFile)>0) {
3341
-            foreach($outFile as $k=>$line) {
3340
+    	if (sizeof($outFile) > 0) {
3341
+            foreach ($outFile as $k=>$line) {
3342 3342
 
3343 3343
             	//convert encoding if necessary
3344 3344
             	$line = $this->convert_encoding_to_UTF8($line);
3345 3345
 
3346 3346
             	//put it to array
3347
-            	$field = str_getcsv ($line, $this->csv_delimiter);
3347
+            	$field = str_getcsv($line, $this->csv_delimiter);
3348 3348
 
3349 3349
             	//verify IP address
3350
-            	if(!filter_var($field[0], FILTER_VALIDATE_IP)) 	{ $class = "danger";	$errors++; }
3351
-            	else											{ $class = ""; }
3350
+            	if (!filter_var($field[0], FILTER_VALIDATE_IP)) { $class = "danger"; $errors++; }
3351
+            	else { $class = ""; }
3352 3352
 
3353 3353
             	// verify that address is in subnet for subnets
3354
-            	if($subnet->isFolder!="1") {
3354
+            	if ($subnet->isFolder != "1") {
3355 3355
 					// check if IP is IPv4 or IPv6
3356 3356
 					$ipsm = "32";
3357 3357
                 	if (!filter_var($field[0], FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) === false) { $ipsm = "128"; }
3358
-                    if ($this->Subnets->is_subnet_inside_subnet ($field[0]."/" . $ipsm, $this->transform_address($subnet->subnet, "dotted")."/".$subnet->mask)==false)    { $class = "danger"; $errors++; }
3358
+                    if ($this->Subnets->is_subnet_inside_subnet($field[0]."/".$ipsm, $this->transform_address($subnet->subnet, "dotted")."/".$subnet->mask) == false) { $class = "danger"; $errors++; }
3359 3359
                 }
3360 3360
             	// make sure mac does not exist
3361
-                if ($this->settings->enableMulticast=="1" && strlen($class)==0) {
3362
-                    if (strlen($field[5])>0 && $this->Subnets->is_multicast($field[0])) {
3363
-                        if($this->Subnets->validate_multicast_mac ($field[5], $subnet->sectionId, $subnet->vlanId, MCUNIQUE)!==true) {
3361
+                if ($this->settings->enableMulticast == "1" && strlen($class) == 0) {
3362
+                    if (strlen($field[5]) > 0 && $this->Subnets->is_multicast($field[0])) {
3363
+                        if ($this->Subnets->validate_multicast_mac($field[5], $subnet->sectionId, $subnet->vlanId, MCUNIQUE) !== true) {
3364 3364
                             $errors++; $class = "danger";
3365 3365
                         }
3366 3366
                     }
@@ -3385,10 +3385,10 @@  discard block
 block discarded – undo
3385 3385
 	 * @param string $type (default: "IPv4")
3386 3386
 	 * @return int
3387 3387
 	 */
3388
-	public function count_subnets ($type="IPv4") {
3388
+	public function count_subnets($type = "IPv4") {
3389 3389
 		# set proper query
3390
-		if($type=="IPv4")		{ $query = 'select count(*) as count from `ipaddresses` where cast(`ip_addr` as UNSIGNED) <= 4294967295;'; }
3391
-		elseif($type=="IPv6")	{ $query = 'select count(*) as count from `ipaddresses` where cast(`ip_addr` as UNSIGNED) >  4294967295;'; }
3390
+		if ($type == "IPv4") { $query = 'select count(*) as count from `ipaddresses` where cast(`ip_addr` as UNSIGNED) <= 4294967295;'; }
3391
+		elseif ($type == "IPv6") { $query = 'select count(*) as count from `ipaddresses` where cast(`ip_addr` as UNSIGNED) >  4294967295;'; }
3392 3392
 
3393 3393
 		try { $count = $this->Database->getObjectQuery($query); }
3394 3394
 		catch (Exception $e) { $this->Result->show("danger", $e->getMessage(), true); }
@@ -3406,14 +3406,14 @@  discard block
 block discarded – undo
3406 3406
 	 * @param bool $perc (default: false)
3407 3407
 	 * @return array
3408 3408
 	 */
3409
-	public function fetch_top_subnets ($type, $limit = "10", $perc = false) {
3409
+	public function fetch_top_subnets($type, $limit = "10", $perc = false) {
3410 3410
 		# set limit & IPv4/IPv6 selector
3411
-		$limit = $limit<=0 ? '' : 'LIMIT '. (int) $limit;
3411
+		$limit = $limit <= 0 ? '' : 'LIMIT '.(int) $limit;
3412 3412
 		$type_operator = ($type === 'IPv6') ? '>' : '<=';
3413 3413
 		$type_max_mask = ($type === 'IPv6') ? '128' : '32';
3414 3414
 		$strict_mode   = ($type === 'IPv6') ? '0' : '2';
3415 3415
 
3416
-		if($perc) {
3416
+		if ($perc) {
3417 3417
 			$query = "SELECT SQL_CACHE s.sectionId,s.id,s.subnet,mask,IF(char_length(s.description)>0,s.description,'No description') AS description,
3418 3418
 					COUNT(*) AS `usage`,ROUND(COUNT(*)/(POW(2,$type_max_mask-`mask`)-$strict_mode)*100,2) AS `percentage` FROM `ipaddresses` AS `i`
3419 3419
 					LEFT JOIN `subnets` AS `s` ON i.subnetId = s.id
@@ -3430,7 +3430,7 @@  discard block
 block discarded – undo
3430 3430
 		}
3431 3431
 
3432 3432
 		try { $stats = $this->Database->getObjectsQuery($query); }
3433
-		catch (Exception $e) { !$this->debugging ? : $this->Result->show("danger", $e->getMessage(), true);	return false; }
3433
+		catch (Exception $e) { !$this->debugging ?: $this->Result->show("danger", $e->getMessage(), true); return false; }
3434 3434
 
3435 3435
 		# return subnets array
3436 3436
 		return (array) $stats;
@@ -3442,10 +3442,10 @@  discard block
 block discarded – undo
3442 3442
 	 * @access public
3443 3443
 	 * @return array
3444 3444
 	 */
3445
-	public function fetch_addresses_for_export () {
3445
+	public function fetch_addresses_for_export() {
3446 3446
 		# fetch
3447 3447
 	    try { $addresses = $this->Database->getObjectsQuery("select `id`,`subnetId`,`ip_addr`,`hostname` from `ipaddresses` where length(`hostname`)>1 order by `subnetId` asc;"); }
3448
-		catch (Exception $e) { $this->Result->show("danger", $e->getMessage(), false);	return false; }
3448
+		catch (Exception $e) { $this->Result->show("danger", $e->getMessage(), false); return false; }
3449 3449
 		# return result
3450 3450
 		return $addresses;
3451 3451
 	}
@@ -3457,7 +3457,7 @@  discard block
 block discarded – undo
3457 3457
 	 * @param mixed $code		//lang code
3458 3458
 	 * @return bool
3459 3459
 	 */
3460
-	public function verify_translation ($code) {
3460
+	public function verify_translation($code) {
3461 3461
 		//verify that proper files exist
3462 3462
 		return !file_exists("functions/locale/$code/LC_MESSAGES/phpipam.mo") ? false : true;
3463 3463
 	}
@@ -3469,11 +3469,11 @@  discard block
 block discarded – undo
3469 3469
 	 * @param mixed $code		//lang code
3470 3470
 	 * @return string
3471 3471
 	 */
3472
-	public function get_translation_version ($code) {
3472
+	public function get_translation_version($code) {
3473 3473
 		//check for version
3474 3474
 		$ver = shell_exec("grep 'Project-Id-Version:' ".dirname(__FILE__)."/../locale/$code/LC_MESSAGES/phpipam.po");
3475 3475
 		//parse
3476
-		$ver = str_replace(array("Project-Id-Version:", " ", '"', "#",'\n', ":"), "", $ver);
3476
+		$ver = str_replace(array("Project-Id-Version:", " ", '"', "#", '\n', ":"), "", $ver);
3477 3477
 		//return version
3478 3478
 		return $ver;
3479 3479
 	}
Please login to merge, or discard this patch.
functions/classes/class.Addresses.php 2 patches
Indentation   +1983 added lines, -1983 removed lines patch added patch discarded remove patch
@@ -7,1601 +7,1601 @@  discard block
 block discarded – undo
7 7
 class Addresses extends Common_functions {
8 8
 
9 9
 
10
-	/**
11
-	 * (array of objects) to store addresses, address ID is array index
12
-	 *
13
-	 * (default value: array)
14
-	 *
15
-	 * @var mixed
16
-	 * @access public
17
-	 */
18
-	public $addresses = array();
19
-
20
-	/**
21
-	 * Address types array
22
-	 *
23
-	 * @var mixed
24
-	 * @access public
25
-	 */
26
-	public $address_types = array();
27
-
28
-	/**
29
-	 * Mail changelog or not
30
-	 *
31
-	 * (default value: true)
32
-	 *
33
-	 * @var bool
34
-	 * @access public
35
-	 */
36
-	public $mail_changelog = true;
10
+    /**
11
+     * (array of objects) to store addresses, address ID is array index
12
+     *
13
+     * (default value: array)
14
+     *
15
+     * @var mixed
16
+     * @access public
17
+     */
18
+    public $addresses = array();
19
+
20
+    /**
21
+     * Address types array
22
+     *
23
+     * @var mixed
24
+     * @access public
25
+     */
26
+    public $address_types = array();
27
+
28
+    /**
29
+     * Mail changelog or not
30
+     *
31
+     * (default value: true)
32
+     *
33
+     * @var bool
34
+     * @access public
35
+     */
36
+    public $mail_changelog = true;
37
+
38
+    /**
39
+     * Last insert id
40
+     *
41
+     * (default value: false)
42
+     *
43
+     * @var bool
44
+     * @access public
45
+     */
46
+    public $lastId = false;
47
+
48
+    /**
49
+     * Debugging flag
50
+     *
51
+     * (default value: false)
52
+     *
53
+     * @var bool
54
+     * @access protected
55
+     */
56
+    protected $debugging = false;
57
+
58
+    /**
59
+     * PEAR NET IPv4 object
60
+     *
61
+     * @var mixed
62
+     * @access protected
63
+     */
64
+    protected $Net_IPv4;
65
+
66
+    /**
67
+     * PEAR NET IPv6 object
68
+     *
69
+     * @var mixed
70
+     * @access protected
71
+     */
72
+    protected $Net_IPv6;
73
+
74
+    /**
75
+     * Database conenction
76
+     *
77
+     * @var mixed
78
+     * @access protected
79
+     */
80
+    protected $Database;
81
+
82
+    /**
83
+     * Subnets object
84
+     *
85
+     * @var mixed
86
+     * @access protected
87
+     */
88
+    protected $Subnets;
89
+
90
+    /**
91
+     * Logging object
92
+     *
93
+     * @var mixed
94
+     * @access public
95
+     */
96
+    public $Log;
97
+
98
+    /**
99
+     * PowerDNS object
100
+     *
101
+     * @var mixed
102
+     * @access private
103
+     */
104
+    private $PowerDNS;
105
+
106
+
107
+
108
+
109
+    /**
110
+     * __construct function
111
+     *
112
+     * @access public
113
+     */
114
+    public function __construct (Database_PDO $Database) {
115
+        # Save database object
116
+        $this->Database = $Database;
117
+        # initialize Result
118
+        $this->Result = new Result ();
119
+        # debugging
120
+        $this->set_debugging();
121
+
122
+        # Log object
123
+        $this->Log = new Logging ($this->Database);
124
+    }
125
+
126
+
127
+
128
+
129
+
130
+
131
+
132
+
133
+
134
+    /**
135
+     * @address tag methods
136
+     * -------------------------------
137
+     */
138
+
139
+    /**
140
+     * Returns array of address types.
141
+     *
142
+     * @access public
143
+     * @return array of address types and parameters
144
+     */
145
+    public function addresses_types_fetch () {
146
+        # fetch
147
+        $types = $this->fetch_all_objects ("ipTags", "id");
148
+
149
+        # save to array
150
+        $types_out = array();
151
+        foreach($types as $t) {
152
+            $types_out[$t->id] = (array) $t;
153
+        }
154
+        # save
155
+        $this->address_types = $types_out;
156
+        # return
157
+        return $types_out;
158
+    }
159
+
160
+    /**
161
+     * Sets address tag
162
+     *
163
+     * @access public
164
+     * @param int $state
165
+     * @return mixed tag
166
+     */
167
+    public function address_type_format_tag ($state) {
168
+        # fetch address states
169
+        $this->addresses_types_fetch();
170
+        # result
171
+        if(!isset($this->address_types[$state]))	{
172
+            return "";
173
+        }
174
+        else {
175
+            if($this->address_types[$state]['showtag']==1) {
176
+                return "<i class='fa fa-".$this->address_types[$state]['type']." fa-tag state' rel='tooltip' style='color:".$this->address_types[$state]['bgcolor']."' title='"._($this->address_types[$state]['type'])."'></i>";
177
+            }
178
+        }
179
+    }
180
+
181
+    /**
182
+     * returns address type from index
183
+     *
184
+     *		1 > Offline
185
+     *
186
+     * @access public
187
+     * @param int $index
188
+     * @return mixed address type
189
+     */
190
+    public function address_type_index_to_type ($index) {
191
+        # fetch address states
192
+        $this->addresses_types_fetch();
193
+        # return
194
+        if(isset($this->address_types[$index])) {
195
+            return $this->address_types[$index]['type'];
196
+        }
197
+        else {
198
+            return $index;
199
+        }
200
+    }
201
+
202
+    /**
203
+     * Returns address index from type
204
+     *
205
+     *	Offline > 1
206
+     *
207
+     * @access public
208
+     * @param mixed $type
209
+     * @return void
210
+     */
211
+    public function address_type_type_to_index ($type = "Used") {
212
+        # null of no length
213
+        $type = strlen($type)==0 || is_null($type) ? "Used" : $type;
214
+        # fetch address states
215
+        $this->addresses_types_fetch();
216
+        # reindex
217
+        $states_assoc = array();
218
+        foreach($this->address_types as $s) {
219
+            $states_assoc[$s['type']] = $s;
220
+        }
221
+        # return
222
+        if(isset($states_assoc[$type])) {
223
+            return $states_assoc[$type]['id'];
224
+        }
225
+        else {
226
+            return $type;
227
+        }
228
+    }
229
+
230
+
231
+
232
+
233
+
234
+
235
+
236
+
237
+
238
+
239
+
240
+
241
+    /**
242
+     * @address methods
243
+     * -------------------------------
244
+     */
245
+
246
+    /**
247
+     * Fetches address by specified method
248
+     *
249
+     * @access public
250
+     * @param string $method (default: "id")
251
+     * @param mixed $id
252
+     * @return object address
253
+     */
254
+    public function fetch_address ($method, $id) {
255
+        # null method
256
+        $method = is_null($method) ? "id" : $method;
257
+        # check cache first
258
+        if(isset($this->addresses[$id]))	{
259
+            return $this->addresses[$id];
260
+        }
261
+        else {
262
+            try { $address = $this->Database->getObjectQuery("SELECT * FROM `ipaddresses` where `$method` = ? limit 1;", array($id)); }
263
+            catch (Exception $e) {
264
+                $this->Result->show("danger", _("Error: ").$e->getMessage());
265
+                return false;
266
+            }
267
+            # save to addresses cache
268
+            if(!is_null($address)) {
269
+                # add decimal format
270
+                $address->ip = $this->transform_to_dotted ($address->ip_addr);
271
+                # save to subnets
272
+                $this->addresses[$id] = (object) $address;
273
+            }
274
+            #result
275
+            return !is_null($address) ? $address : false;
276
+        }
277
+    }
278
+
279
+    /**
280
+     * Fetch addresses on int ip_addr and subnetId
281
+     *
282
+     * @access public
283
+     * @param mixed $ip_addr
284
+     * @param mixed $subnetId
285
+     * @return void
286
+     */
287
+    public function fetch_address_multiple_criteria ($ip_addr, $subnetId) {
288
+        try { $address = $this->Database->getObjectQuery("SELECT * FROM `ipaddresses` where `ip_addr` = ? and `subnetId` = ? limit 1;", array($ip_addr, $subnetId)); }
289
+        catch (Exception $e) {
290
+            $this->Result->show("danger", _("Error: ").$e->getMessage());
291
+            return false;
292
+        }
293
+        # save to addresses cache
294
+        if(sizeof($address)>0) {
295
+            # add decimal format
296
+            $address->ip = $this->transform_to_dotted ($address->ip_addr);
297
+            # save to subnets
298
+            $this->addresses[$address->id] = (object) $address;
299
+        }
300
+        #result
301
+        return !is_null($address) ? $address : false;
302
+    }
303
+
304
+    /**
305
+     * Searches database for similar addresses
306
+     *
307
+     * @access public
308
+     * @param mixed $linked_field
309
+     * @param mixed $value
310
+     * @param mixed $address_id
311
+     * @return void
312
+     */
313
+    public function search_similar_addresses ($linked_field, $value, $address_id) {
314
+        // checks
315
+        if(strlen($linked_field)>0 && strlen($value)>0 && is_numeric($address_id)) {
316
+            // search
317
+                try { $addresses = $this->Database->getObjectsQuery("SELECT * FROM `ipaddresses` where `$linked_field` = ? and `id` != ? and state != 4;", array($value, $address_id)); }
318
+            catch (Exception $e) {
319
+                $this->Result->show("danger", _("Error: ").$e->getMessage());
320
+                return false;
321
+            }
322
+            #result
323
+            return sizeof($addresses)>0 ? $addresses : false;
324
+        }
325
+        else {
326
+            return false;
327
+        }
328
+    }
329
+
330
+    /**
331
+     * Address modification
332
+     *
333
+     * @access public
334
+     * @param mixed $address
335
+     * @param bool $mail_changelog (default: true)
336
+     * @return void
337
+     */
338
+    public function modify_address ($address, $mail_changelog = true) {
339
+        # save changelog
340
+        $this->mail_changelog  = $mail_changelog;
341
+        # null empty values
342
+        $address = $this->reformat_empty_array_fields ($address, null);
343
+        # strip tags
344
+        $address = $this->strip_input_tags ($address);
345
+        # execute based on action
346
+        if($address['action']=="add")			{ return $this->modify_address_add ($address); }							//create new address
347
+        elseif($address['action']=="edit")		{ return $this->modify_address_edit ($address); }							//modify existing address
348
+        elseif($address['action']=="delete")	{ return $this->modify_address_delete ($address); }							//delete address
349
+        elseif($address['action']=="move")		{ return $this->modify_address_move ($address); }							//move to new subnet
350
+        else									{ return $this->Result->show("danger", _("Invalid action"), true); }
351
+    }
352
+
353
+    /**
354
+     * Inserts new IP address to table
355
+     *
356
+     * @access protected
357
+     * @param array $address
358
+     * @return boolean success/failure
359
+     */
360
+    protected function modify_address_add ($address) {
361
+        # set insert array
362
+        $insert = array(
363
+                        "ip_addr"               => $this->transform_address($address['ip_addr'],"decimal"),
364
+                        "subnetId"              => $address['subnetId'],
365
+                        "description"           => @$address['description'],
366
+                        "hostname"              => @$address['hostname'],
367
+                        "mac"                   => @$address['mac'],
368
+                        "owner"                 => @$address['owner'],
369
+                        "state"                 => @$address['state'],
370
+                        "switch"                => @$address['switch'],
371
+                        "port"                  => @$address['port'],
372
+                        "note"                  => @$address['note'],
373
+                        "is_gateway"            => @$address['is_gateway'],
374
+                        "excludePing"           => @$address['excludePing'],
375
+                        "PTRignore"             => @$address['PTRignore'],
376
+                        "firewallAddressObject" => @$address['firewallAddressObject'],
377
+                        "lastSeen"              => @$address['lastSeen']
378
+                        );
379
+        # customer
380
+        if(isset($address['customer_id'])) {
381
+            if (is_numeric($address['customer_id'])) {
382
+                if ($address['customer_id']!="0") {
383
+                    $insert['customer_id'] = $address['customer_id'];
384
+                }
385
+                else {
386
+                    $insert['customer_id'] = NULL;
387
+                }
388
+            }
389
+        }
390
+        # location
391
+        if (isset($address['location_item'])) {
392
+            if (!is_numeric($address['location_item'])) {
393
+                $this->Result->show("danger", _("Invalid location value"), true);
394
+            }
395
+            $insert['location'] = $address['location_item'];
396
+        }
397
+        # custom fields, append to array
398
+        foreach($this->set_custom_fields() as $c) {
399
+            $insert[$c['name']] = !empty($address[$c['name']]) ? $address[$c['name']] : $c['Default'];
400
+        }
401
+
402
+        # null empty values
403
+        $insert = $this->reformat_empty_array_fields ($insert, null);
404
+
405
+        # remove gateway
406
+        if($address['is_gateway']==1)	{ $this->remove_gateway ($address['subnetId']); }
407
+
408
+        # execute
409
+        try { $this->Database->insertObject("ipaddresses", $insert); }
410
+        catch (Exception $e) {
411
+            $this->Log->write( "Address create", "Failed to create new address<hr>".$e->getMessage()."<hr>".$this->array_to_log($this->reformat_empty_array_fields ($address, "NULL")), 2);
412
+            $this->Result->show("danger", _("Error: ").$e->getMessage(), false);
413
+            return false;
414
+        }
415
+        # save id
416
+        $this->lastId = $this->Database->lastInsertId();
417
+
418
+        # log and changelog
419
+        $address['id'] = $this->lastId;
420
+        $this->Log->write( "Address created", "New address created<hr>".$this->array_to_log($this->reformat_empty_array_fields ($address, "NULL")), 0);
421
+        $this->Log->write_changelog('ip_addr', "add", 'success', array(), $address, $this->mail_changelog);
422
+
423
+        # edit DNS PTR record
424
+        $this->ptr_modify ("add", $insert);
425
+
426
+        # threshold alert
427
+        $this->threshold_check($address);
428
+
429
+        # ok
430
+        return true;
431
+    }
432
+
433
+    /**
434
+     * Modifies address in table or whole range if requested
435
+     *
436
+     * @access protected
437
+     * @param array $address
438
+     * @return boolean success/failure
439
+     */
440
+    protected function modify_address_edit ($address) {
441
+        # fetch old details for logging
442
+        $address_old = $this->fetch_address (null, $address['id']);
443
+        if (isset($address['section'])) $address_old->section = $address['section'];
444
+
445
+        # set update array
446
+        $insert = array(
447
+                        "id"          =>$address['id'],
448
+                        "subnetId"    =>$address['subnetId'],
449
+                        "ip_addr"     =>$this->transform_address($address['ip_addr'], "decimal"),
450
+                        "description" =>@$address['description'],
451
+                        "hostname"    =>@$address['hostname'],
452
+                        "mac"         =>@$address['mac'],
453
+                        "owner"       =>@$address['owner'],
454
+                        "state"       =>@$address['state'],
455
+                        "switch"      =>@$address['switch'],
456
+                        "port"        =>@$address['port'],
457
+                        "note"        =>@$address['note'],
458
+                        "is_gateway"  =>@$address['is_gateway'],
459
+                        "excludePing" =>@$address['excludePing'],
460
+                        "PTRignore"   =>@$address['PTRignore']
461
+                        );
462
+            # customer
463
+        if(isset($address['customer_id'])) {
464
+            if (is_numeric($address['customer_id'])) {
465
+                if ($address['customer_id']!="0") {
466
+                    $insert['customer_id'] = $address['customer_id'];
467
+                }
468
+                else {
469
+                    $insert['customer_id'] = NULL;
470
+                }
471
+            }
472
+        }
473
+        # location
474
+        if (isset($address['location_item'])) {
475
+            if (!is_numeric($address['location_item'])) {
476
+                $this->Result->show("danger", _("Invalid location value"), true);
477
+            }
478
+            $insert['location'] = $address['location_item'];
479
+        }
480
+        # custom fields, append to array
481
+        foreach($this->set_custom_fields() as $c) {
482
+            $insert[$c['name']] = !empty($address[$c['name']]) ? $address[$c['name']] : $c['Default'];
483
+        }
484
+
485
+        # set primary key for update
486
+        if($address['type']=="series") {
487
+            $id1 = "subnetId";
488
+            $id2 = "ip_addr";
489
+            unset($insert['id']);
490
+        } else {
491
+            $id1 = "id";
492
+            $id2 = null;
493
+        }
494
+
495
+        # remove gateway
496
+        if($address['is_gateway']==1)	{ $this->remove_gateway ($address['subnetId']); }
497
+
498
+        # execute
499
+        try { $this->Database->updateObject("ipaddresses", $insert, $id1, $id2); }
500
+        catch (Exception $e) {
501
+            $this->Log->write( "Address edit", "Failed to edit address $address[ip_addr]<hr>".$e->getMessage()."<hr>".$this->array_to_log($this->reformat_empty_array_fields ($address, "NULL")), 2);
502
+            $this->Result->show("danger", _("Error: ").$e->getMessage(), false);
503
+            return false;
504
+        }
505
+
506
+        # set the firewall address object to avoid logging
507
+        $address['firewallAddressObject'] = $address_old->firewallAddressObject;
508
+
509
+            # log and changelog
510
+        $this->Log->write( "Address updated", "Address $address[ip_addr] updated<hr>".$this->array_to_log($this->reformat_empty_array_fields ($address, "NULL")), 0);
511
+        $this->Log->write_changelog('ip_addr', "edit", 'success', (array) $address_old, $address, $this->mail_changelog);
512
+
513
+        # edit DNS PTR record
514
+        $insert['PTR']=@$address['PTR'];
515
+        $this->ptr_modify ("edit", $insert);
516
+
517
+        # ok
518
+        return true;
519
+    }
520
+
521
+    /**
522
+     * Deletes address or address range.
523
+     *
524
+     * @access protected
525
+     * @param array $address
526
+     * @return boolean success/failure
527
+     */
528
+    protected function modify_address_delete ($address) {
529
+        # fetch old details for logging
530
+        $address_old = $this->fetch_address (null, $address['id']);
531
+        if (isset($address['section'])) $address_old->section = $address['section'];
532
+
533
+        # series?
534
+        if($address['type']=="series") {
535
+            $field  = "subnetId";	$value  = $address['subnetId'];
536
+            $field2 = "ip_addr";	$value2 = $this->transform_address ($address['ip_addr'], "decimal");
537
+        } else {
538
+            $field  = "id";			$value  = $address['id'];
539
+            $field2 = null;			$value2 = null;
540
+        }
541
+        # execute
542
+        try { $this->Database->deleteRow("ipaddresses", $field, $value, $field2, $value2); }
543
+        catch (Exception $e) {
544
+            $this->Log->write( "Address delete", "Failed to delete address $address[ip_addr]<hr>".$e->getMessage()."<hr>".$this->array_to_log((array) $address_old), 2);
545
+            $this->Result->show("danger", _("Error: ").$e->getMessage(), false);
546
+            return false;
547
+        }
548
+
549
+        # log and changelog
550
+        $this->Log->write( "Address deleted", "Address $address[ip_addr] deleted<hr>".$this->array_to_log((array) $address_old), 0);
551
+        $this->Log->write_changelog('ip_addr', "delete", 'success', (array) $address_old, array(), $this->mail_changelog);
552
+
553
+        # edit DNS PTR record
554
+        $this->ptr_modify ("delete", $address);
555
+
556
+        # remove all referenced records
557
+        if(@$address['remove_all_dns_records']=="1") {
558
+            $this->pdns_remove_ip_and_hostname_records ($address);
559
+        }
560
+        # remove from NAT
561
+        $this->remove_address_nat_items ($address['id'], true);
562
+        # ok
563
+        return true;
564
+    }
565
+
566
+    /**
567
+     * Moves address to new subnet
568
+     *
569
+     * @access protected
570
+     * @param array $address
571
+     * @return boolean success/failure
572
+     */
573
+    protected function modify_address_move ($address) {
574
+        # execute
575
+        try { $this->Database->updateObject("ipaddresses", array("subnetId"=>$address['newSubnet'], "id"=>$address['id'])); }
576
+        catch (Exception $e) {
577
+            $this->Result->show("danger", _("Error: ").$e->getMessage(), false);
578
+            return false;
579
+        }
580
+        # ok
581
+        return true;
582
+    }
583
+
584
+    /**
585
+     * Remove item from nat when item is removed
586
+     *
587
+     * @method remove_nat_item
588
+     *
589
+     * @param  int $obj_id
590
+     * @param  bool $print
591
+     *
592
+     * @return int
593
+     */
594
+    public function remove_address_nat_items ($obj_id = 0, $print = true) {
595
+        # set found flag for returns
596
+        $found = 0;
597
+        # fetch all nats
598
+        try { $all_nats = $this->Database->getObjectsQuery ("select * from `nat` where `src` like :id or `dst` like :id", array ("id"=>'%"'.$obj_id.'"%')); }
599
+        catch (Exception $e) {
600
+            $this->Result->show("danger", _("Error: ").$e->getMessage());
601
+            return false;
602
+        }
603
+        # loop and check for object ids
604
+        if(!empty($all_nats)) {
605
+            # init admin object
606
+            $Admin = new Admin ($this->Database, false);
607
+            # loop
608
+            foreach ($all_nats as $nat) {
609
+                # remove item from nat
610
+                $s = json_decode($nat->src, true);
611
+                $d = json_decode($nat->dst, true);
612
+
613
+                if(is_array($s['ipaddresses']))
614
+                $s['ipaddresses'] = array_diff($s['ipaddresses'], array($obj_id));
615
+                if(is_array($d['ipaddresses']))
616
+                $d['ipaddresses'] = array_diff($d['ipaddresses'], array($obj_id));
617
+
618
+                # save back and update
619
+                $src_new = json_encode(array_filter($s));
620
+                $dst_new = json_encode(array_filter($d));
621
+
622
+                # update only if diff found
623
+                if($s!=$src_new || $d!=$dst_new) {
624
+                    $found++;
625
+
626
+                    if($Admin->object_modify ("nat", "edit", "id", array("id"=>$nat->id, "src"=>$src_new, "dst"=>$dst_new))!==false) {
627
+                        if($print) {
628
+                            $this->Result->show("success", "Address removed from NAT", false);
629
+                        }
630
+                    }
631
+                }
632
+            }
633
+        }
634
+        # return
635
+        return $found;
636
+    }
637
+
638
+    /**
639
+     * Updates hostname for IP addresses
640
+     *
641
+     * @method update_address_hostname
642
+     *
643
+     * @param  mixed $ip
644
+     * @param  int $id
645
+     * @param  string $hostname
646
+     *
647
+     * @return void
648
+     */
649
+    public function update_address_hostname ($ip, $id, $hostname = "") {
650
+        if(is_numeric($id) && strlen($hostname)>0) {
651
+            try { $this->Database->updateObject("ipaddresses", array("id"=>$id, "hostname"=>$hostname)); }
652
+            catch (Exception $e) {
653
+                return false;
654
+            }
655
+            // save log
656
+            $this->Log->write( "Address DNS resolved", "Address $ip resolved<hr>".$this->array_to_log((array) $hostname), 0);
657
+            $this->Log->write_changelog('ip_addr', "edit", 'success', array ("id"=>$id, "hostname"=>""), array("id"=>$id, "hostname"=>$hostname), $this->mail_changelog);
658
+        }
659
+    }
660
+
661
+    /**
662
+     * Checks if subnet usage is over threshold and sends alert
663
+     *
664
+     * @access private
665
+     * @param mixed $address
666
+     * @return void
667
+     */
668
+    private function threshold_check ($address) {
669
+        $address = (object) $address;
670
+        $content = array();
671
+        $content_plain = array();
672
+
673
+        # fetch settings
674
+        $this->get_settings ();
675
+        # enabled ?
676
+        if ($this->settings->enableThreshold=="1") {
677
+            # object
678
+            if (!is_object($this->Subnets)) {
679
+                $this->Subnets = new Subnets ($this->Database);
680
+            }
681
+            # fetch subnet
682
+            $subnet = $this->Subnets->fetch_subnet("id", $address->subnetId);
683
+            # threshold set ?
684
+            if ($subnet->threshold>0) {
685
+                # calculate subnet usage
686
+                $subnet_usage = $this->Subnets->calculate_subnet_usage ($subnet);
687
+                # if over send mail
688
+                if (gmp_strval(gmp_sub(100,(int) round($subnet_usage['freehosts_percent'], 0))) > $subnet->threshold) {
689
+                    // fetch mail settings
690
+                    $Tools = new Tools ($this->Database);
691
+                    $admins        = $Tools->fetch_multiple_objects ("users", "role", "Administrator");
692
+                    // if some recipients
693
+                    if ($admins !== false) {
694
+                        # try to send
695
+                        try {
696
+                            // mail settings
697
+                            $mail_settings = $Tools->fetch_object ("settingsMail", "id", 1);
698
+                            // mail class
699
+                            $phpipam_mail = new phpipam_mail ($this->settings, $mail_settings);
700
+
701
+                            // set parameters
702
+                            $subject = "Subnet threshold limit reached"." (".$this->transform_address($subnet->subnet,"dotted")."/".$subnet->mask.")";
703
+                            $content[] = "<table style='margin-left:10px;margin-top:5px;width:auto;padding:0px;border-collapse:collapse;'>";
704
+                            $content[] = "<tr><td style='padding:5px;margin:0px;color:#333;font-size:16px;text-shadow:1px 1px 1px white;border-bottom:1px solid #eeeeee;' colspan='2'>$this->mail_font_style<strong>$subject</font></td></tr>";
705
+                            $content[] = '<tr><td style="padding: 0px;padding-left:10px;margin:0px;line-height:18px;text-align:left;">'.$this->mail_font_style.''._('Subnet').'</a></font></td>	<td style="padding: 0px;padding-left:15px;margin:0px;line-height:18px;text-align:left;padding-top:10px;"><a href="'.$this->createURL().''.create_link("subnets",$subnet->sectionId, $subnet->id).'">'.$this->mail_font_style_href . $this->transform_address($subnet->subnet,"dotted")."/".$subnet->mask .'</font></a></td></tr>';
706
+                            $content[] = '<tr><td style="padding: 0px;padding-left:10px;margin:0px;line-height:18px;text-align:left;">'.$this->mail_font_style.''._('Description').'</font></td>	  	<td style="padding: 0px;padding-left:15px;margin:0px;line-height:18px;text-align:left;">'.$this->mail_font_style.''. $subnet->description .'</font></td></tr>';
707
+                            $content[] = '<tr><td style="padding: 0px;padding-left:10px;margin:0px;line-height:18px;text-align:left;">'.$this->mail_font_style.''._('Usage').' (%)</font></td>	<td style="padding: 0px;padding-left:15px;margin:0px;line-height:18px;text-align:left;">'.$this->mail_font_style.''. gmp_strval(gmp_sub(100,(int) round($subnet_usage['freehosts_percent'], 0))) .'</font></td></tr>';
708
+                            $content[] = "</table>";
709
+                            // plain
710
+                            $content_plain[] = "$subject"."\r\n------------------------------\r\n";
711
+                            $content_plain[] = _("Subnet").": ".$this->transform_address($subnet->subnet,"dotted")."/".$subnet->mask;
712
+                            $content_plain[] = _("Usage")." (%) : ".gmp_strval(gmp_sub(100,(int) round($subnet_usage['freehosts_percent'], 0)));
713
+
714
+                            # set content
715
+                            $content 		= $phpipam_mail->generate_message (implode("\r\n", $content));
716
+                            $content_plain 	= implode("\r\n",$content_plain);
717
+
718
+                            $phpipam_mail->Php_mailer->setFrom($mail_settings->mAdminMail, $mail_settings->mAdminName);
719
+                            //add all admins to CC
720
+                            $recipients = $this->changelog_mail_get_recipients ($subnet->id);
721
+
722
+                            if ($recipients!==false) {
723
+                                foreach($recipients as $a) {
724
+                                    $phpipam_mail->Php_mailer->addAddress($a->email);
725
+                                }
726
+
727
+                                $phpipam_mail->Php_mailer->Subject = $subject;
728
+                                $phpipam_mail->Php_mailer->msgHTML($content);
729
+                                $phpipam_mail->Php_mailer->AltBody = $content_plain;
730
+                                //send
731
+                                $phpipam_mail->Php_mailer->send();
732
+                            }
733
+                            else {
734
+                                return true;
735
+                            }
736
+                        } catch (phpmailerException $e) {
737
+                            $this->Result->show("danger", "Mailer Error: ".$e->errorMessage(), true);
738
+                        } catch (Exception $e) {
739
+                            $this->Result->show("danger", "Mailer Error: ".$e->getMessage(), true);
740
+                        }
741
+                    }
742
+                }
743
+            }
744
+            else {
745
+                return true;
746
+            }
747
+        }
748
+        else {
749
+            return true;
750
+        }
751
+    }
752
+
753
+    /**
754
+     * Removes gateway if it exists
755
+     *
756
+     * @access public
757
+     * @param mixed $subnetId
758
+     * @return void
759
+     */
760
+    public function remove_gateway ($subnetId) {
761
+        try { $this->Database->updateObject("ipaddresses", array("subnetId"=>$subnetId, "is_gateway"=>0), "subnetId"); }
762
+        catch (Exception $e) {
763
+            $this->Result->show("danger", _("Error: ").$e->getMessage());
764
+            return false;
765
+        }
766
+    }
767
+
768
+    /**
769
+     * Fetches custom IP address fields
770
+     *
771
+     * @access public
772
+     * @return object custom address fields
773
+     */
774
+    public function set_custom_fields () {
775
+        # Tools object
776
+        $Tools = new Tools ($this->Database);
777
+        # fetch
778
+        return $Tools->fetch_custom_fields ('ipaddresses');
779
+    }
780
+
781
+    /**
782
+     * Checks if address already exists in subnet
783
+     *
784
+     *	if cnt is false we will return id if it exists and false ifnot
785
+     *
786
+     * @access public
787
+     * @param int $address
788
+     * @param int $subnetId
789
+     * @param int $subnetId
790
+     * @return boolean success/failure
791
+     */
792
+    public function address_exists ($address, $subnetId, $cnt = true) {
793
+        # make sure it is in decimal format
794
+        $address = $this->transform_address($address, "decimal");
795
+        # check
796
+        if($cnt===true) { $query = "select count(*) as `cnt` from `ipaddresses` where `subnetId`=? and `ip_addr`=?;"; }
797
+        else			{ $query = "select `id` from `ipaddresses` where `subnetId`=? and `ip_addr`=?;";  }
798
+        # fetch
799
+        try { $count = $this->Database->getObjectQuery($query, array($subnetId, $address)); }
800
+        catch (Exception $e) {
801
+            $this->Result->show("danger", _("Error: ").$e->getMessage());
802
+            return false;
803
+        }
804
+        # result
805
+        if ($cnt===true)	{ return $count->cnt==0 ? false : true; }
806
+        else				{ return is_null($count->id) ? false : $count->id; }
807
+    }
808
+
809
+    /**
810
+     * Calculates diff between two IP addresses
811
+     *
812
+     * @access public
813
+     * @param int $ip1
814
+     * @param int $ip2
815
+     * @return void
816
+     */
817
+    public function calculate_address_diff ($ip1, $ip2) {
818
+        return gmp_strval(gmp_sub($ip2, $ip1));
819
+    }
820
+
821
+
822
+    /**
823
+     * Returns first available subnet address, false if none
824
+     *
825
+     * @access public
826
+     * @param int $subnetId
827
+     * @param obj $Subnets
828
+     * @return int / false
829
+     */
830
+    public function get_first_available_address ($subnetId, $Subnets) {
831
+
832
+        # fetch all addresses in subnet and subnet
833
+        $addresses = $this->fetch_subnet_addresses ($subnetId, "ip_addr", "asc", array("ip_addr"));
834
+        $subnet = (array) $Subnets->fetch_subnet(null, $subnetId);
835
+
836
+        # if folder return false
837
+        if ($subnet['isFolder']=="1")                                                                   { return false; }
838
+
839
+        # false if slaves
840
+        $this->Subnets = new Subnets ($this->Database);
841
+        if($this->Subnets->has_slaves ($subnetId))                                                      { return false; }
842
+
843
+        # get max hosts
844
+        $max_hosts = $Subnets->get_max_hosts ($subnet['mask'], $this->identify_address($subnet['subnet']));
845
+
846
+        # full subnet?
847
+        if(sizeof($addresses)>=$max_hosts)																{ return false; } 	//full subnet
848
+
849
+        # set type
850
+        $ip_version = $this->identify_address ($subnet['subnet']);
851
+        # get first diff > 1
852
+        if(sizeof($addresses)>0) {
853
+            foreach($addresses as $k=>$ipaddress) {
854
+                # check subnet and first IP
855
+                if($k==0) {
856
+                    # /31 fix
857
+                    if($subnet['mask']==31)	{
858
+                        if(gmp_strval(gmp_sub($addresses[$k]->ip_addr, $subnet['subnet']))>0) 			{ return gmp_strval($subnet['subnet']); }
859
+                    } else {
860
+                        if(gmp_strval(gmp_sub($addresses[$k]->ip_addr, $subnet['subnet']))>1) 			{ return gmp_strval(gmp_add($subnet['subnet'], 1)); }
861
+                        elseif($ip_version=="IPv6") {
862
+                            if(sizeof($addresses)==1) {
863
+                                if(gmp_strval(gmp_sub($addresses[$k]->ip_addr, $subnet['subnet']))==0)	{ return gmp_strval(gmp_add($subnet['subnet'], 1)); }
864
+                            }
865
+                        }
866
+                    }
867
+                }
868
+                else {
869
+                    if(gmp_strval(gmp_sub($addresses[$k]->ip_addr, $addresses[$k-1]->ip_addr))>1) 		{ return gmp_strval(gmp_add($addresses[$k-1]->ip_addr, 1)); }
870
+                }
871
+            }
872
+            # all consecutive, last + 1
873
+                                                                                                        { return gmp_strval(gmp_add($addresses[$k]->ip_addr, 1)); }
874
+        }
875
+        # no addresses
876
+        else {
877
+            # /32, /31
878
+            if($subnet['mask']==32 || $subnet['mask']==31 || $ip_version=="IPv6") 						{ return $subnet['subnet']; }
879
+            else																						{ return gmp_strval(gmp_add($subnet['subnet'], 1)); }
880
+        }
881
+    }
882
+
883
+
884
+
885
+
886
+
887
+
888
+
889
+
890
+
891
+    /**
892
+     * @powerDNS
893
+     * -------------------------------
894
+     */
895
+
896
+    /**
897
+     * Modifes powerDNS PTR record
898
+     *
899
+     * @access public
900
+     * @param mixed $action
901
+     * @param mixed $address
902
+     * @param bool $print_error (default: true)
903
+     * @return void
904
+     */
905
+    public function ptr_modify ($action, $address, $print_error = true) {
906
+        // fetch settings
907
+        $this->settings ();
908
+        //check if powerdns enabled
909
+        if ($this->settings->enablePowerDNS!=1) {
910
+            return false;
911
+        }
912
+        //enabled, proceed
913
+        else {
914
+            // first check if subnet selected for PTR records
915
+            $this->initialize_subnets_object ();
916
+            $subnet = $this->Subnets->fetch_subnet ("id", $address['subnetId']);
917
+            if ($subnet->DNSrecursive!="1") { return false; }
918
+
919
+            // ignore if PTRignore set
920
+            if ($address['PTRignore']=="1")	{
921
+                // validate db
922
+                $this->pdns_validate_connection ();
923
+                // remove if it exists
924
+                if ($this->ptr_exists ($address['PTR'])) {
925
+                    $this->ptr_delete ($address, false);
926
+                                        { return false; }
927
+                }
928
+                else {
929
+                                        { return true; }
930
+                }
931
+            }
932
+            // validate db
933
+            $this->pdns_validate_connection ();
934
+
935
+            // to object
936
+            $address = (object) $address;
937
+            # execute based on action
938
+            if($action=="add")				{ return $this->ptr_add ($address, $print_error); }							//create new PTR
939
+            elseif($action=="edit")			{ return $this->ptr_edit ($address, $print_error); }						//modify existing PTR
940
+            elseif($action=="delete")		{ return $this->ptr_delete ($address, $print_error); }						//delete PTR
941
+            else							{ return $this->Result->show("danger", _("Invalid PDNS action"), true); }
942
+        }
943
+    }
944
+
945
+    /**
946
+     * This function removes all records - ip and hostname referenced by address.
947
+     *
948
+     * @access public
949
+     * @param mixed $address
950
+     * @return void
951
+     */
952
+    public function pdns_remove_ip_and_hostname_records ($address) {
953
+        // fetch settings
954
+        $this->settings ();
955
+        //check if powerdns enabled
956
+        if ($this->settings->enablePowerDNS!=1) {
957
+            return false;
958
+        }
959
+        // validate db
960
+        $this->pdns_validate_connection ();
961
+        // execute
962
+        return $this->PowerDNS->pdns_remove_ip_and_hostname_records ($address['hostname'], $address['ip_addr']);
963
+    }
964
+
965
+    /**
966
+     *  Validates pdns database connection
967
+     *
968
+     * @access public
969
+     * @param bool $die (default: false)
970
+     * @return void
971
+     */
972
+    public function pdns_validate_connection ($die = true) {
973
+        # powerDNS class
974
+        $this->PowerDNS = new PowerDNS ($this->Database);
975
+        # add API info
976
+        if(isset($this->api)) {
977
+            $this->PowerDNS->api = $this->api;
978
+        }
979
+        # check connection
980
+        if($this->PowerDNS->db_check()===false && $die) { $this->Result->show("danger", _("Cannot connect to powerDNS database"), true); }
981
+        # get settings
982
+        $this->get_settings ();
983
+    }
984
+
985
+    /**
986
+     * Set zone name and fetch domain details
987
+     *
988
+     * @access private
989
+     * @param mixed $subnet_id
990
+     * @return array|false
991
+     */
992
+    private function pdns_fetch_domain ($subnet_id) {
993
+        # initialize subnets
994
+        $this->initialize_subnets_object ();
995
+        // fetch subnet
996
+        $subnet = $this->Subnets->fetch_subnet ("id", $subnet_id);
997
+        if($subnet===false)							{  $this->Result->show("danger", _("Invalid subnet Id"), true); }
998
+
999
+        // set PTR zone name from IP/mash
1000
+        $zone = $this->PowerDNS->get_ptr_zone_name ($this->transform_address ($subnet->subnet, "dotted"), $subnet->mask);
1001
+        // try to fetch
1002
+        return  $this->PowerDNS->fetch_domain_by_name ($zone);
1003
+    }
1004
+
1005
+    /**
1006
+     * Create new PTR record when adding new IP address
1007
+     *
1008
+     * @access public
1009
+     * @param mixed $address
1010
+     * @param mixed $print_error (default: true)
1011
+     * @param mixed $id (default: NULL)
1012
+     * @return void
1013
+     */
1014
+    public function ptr_add ($address, $print_error = true, $id = null) {
1015
+        // decode values
1016
+        $values = json_decode($this->settings->powerDNS);
1017
+
1018
+        // set default hostname for PTR if set
1019
+        if (strlen($address->hostname)==0) {
1020
+            if (strlen($values->def_ptr_domain)>0) {
1021
+                $address->hostname = $values->def_ptr_domain;
1022
+            }
1023
+        }
1024
+        // validate hostname
1025
+        if ($this->validate_hostname ($address->hostname)===false)		{ return false; }
1026
+        // fetch domain
1027
+        $domain = $this->pdns_fetch_domain ($address->subnetId);
1028
+
1029
+        // formulate new record
1030
+        $record = $this->PowerDNS->formulate_new_record ($domain->id, $this->PowerDNS->get_ip_ptr_name ($this->transform_address ($address->ip_addr, "dotted")), "PTR", $address->hostname, $values->ttl);
1031
+        // insert record
1032
+        $this->PowerDNS->add_domain_record ($record, false);
1033
+        // link to address
1034
+        $id = $id===null ? $this->lastId : $id;
1035
+        $this->ptr_link ($id, $this->PowerDNS->lastId);
1036
+        // ok
1037
+        if ($print_error && php_sapi_name()!="cli")
1038
+        $this->Result->show("success", "PTR record created", false);
1039
+
1040
+        return true;
1041
+    }
1042
+
1043
+    /**
1044
+     * Edits PTR
1045
+     *
1046
+     * @access public
1047
+     * @param mixed $address
1048
+     * @param mixed $print_error (default: true)
1049
+     * @return void
1050
+     */
1051
+    public function ptr_edit ($address, $print_error = true) {
1052
+        // validate hostname
1053
+        if ($this->validate_hostname ($address->hostname)===false)	{
1054
+            // remove pointer if it exists!
1055
+            if ($this->ptr_exists ($address->PTR)===true)	{ $this->ptr_delete ($address, $print_error); }
1056
+            else											{ return false; }
1057
+        }
1058
+
1059
+        // new record
1060
+            if ($this->ptr_exists ($address->PTR)===false) {
1061
+                // fake lastid
1062
+                $this->lastId = $address->id;
1063
+                // new ptr record
1064
+                $this->ptr_add ($address, true);
1065
+            }
1066
+            // update PTR
1067
+            else {
1068
+            // fetch domain
1069
+            $domain = $this->pdns_fetch_domain ($address->subnetId);
1070
+
1071
+            // fetch old
1072
+            $old_record = $this->PowerDNS->fetch_record ($address->PTR);
1073
+
1074
+            // create insert array
1075
+            $update = $this->PowerDNS->formulate_update_record ($this->PowerDNS->get_ip_ptr_name ($this->transform_address ($address->ip_addr, "dotted")), null, $address->hostname, null, null, null, $old_record->change_date);
1076
+            $update['id'] = $address->PTR;
1077
+
1078
+            // update
1079
+            $this->PowerDNS->update_domain_record ($domain->id, $update, $print_error);
1080
+            // ok
1081
+            if ($print_error && php_sapi_name()!="cli")
1082
+            $this->Result->show("success", "PTR record updated", false);
1083
+            }
1084
+    }
1085
+
1086
+    /**
1087
+     * Remove PTR from database
1088
+     *
1089
+     * @access public
1090
+     * @param mixed $address
1091
+     * @param mixed $print_error
1092
+     * @return void
1093
+     */
1094
+    public function ptr_delete ($address, $print_error) {
1095
+        $address = (object) $address;
1096
+
1097
+        // remove link from ipaddresses
1098
+        $this->ptr_unlink ($address->id);
1099
+
1100
+        // exists
1101
+        if ($this->ptr_exists ($address->PTR)!==false)	{
1102
+            // fetch domain
1103
+            $domain = $this->pdns_fetch_domain ($address->subnetId);
1104
+            //remove
1105
+            $this->PowerDNS->remove_domain_record ($domain->id, $address->PTR);
1106
+            // ok
1107
+            if ($print_error && php_sapi_name()!="cli")
1108
+            $this->Result->show("success", "PTR record removed", false);
1109
+        }
1110
+    }
1111
+
1112
+    /**
1113
+     * Links PTR record with address record
1114
+     *
1115
+     * @access public
1116
+     * @param mixed $address_id
1117
+     * @param mixed $ptr_id
1118
+     * @return void
1119
+     */
1120
+    public function ptr_link ($address_id, $ptr_id) {
1121
+        # execute
1122
+        try { $this->Database->updateObject("ipaddresses", array("id"=>$address_id, "PTR"=>$ptr_id)); }
1123
+        catch (Exception $e) {
1124
+            $this->Result->show("danger", _("Error: ").$e->getMessage(), false);
1125
+            return false;
1126
+        }
1127
+    }
1128
+
1129
+    /**
1130
+     * Remove PTR link if it exists
1131
+     *
1132
+     * @access private
1133
+     * @param mixed $address_id
1134
+     * @return void
1135
+     */
1136
+    private function ptr_unlink ($address_id) {
1137
+        # execute
1138
+        try { $this->Database->updateObject("ipaddresses", array("id"=>$address_id, "PTR"=>0)); }
1139
+        catch (Exception $e) {
1140
+            $this->Result->show("danger", _("Error: ").$e->getMessage(), false);
1141
+            return false;
1142
+        }
1143
+    }
1144
+
1145
+    /**
1146
+     * Removes all PTR references for all hosts in subnet
1147
+     *
1148
+     * @access public
1149
+     * @param mixed $subnet_id
1150
+     * @return void
1151
+     */
1152
+    public function ptr_unlink_subnet_addresses ($subnet_id) {
1153
+        try { $this->Database->runQuery("update `ipaddresses` set `PTR` = 0 where `subnetId` = ?;", array($subnet_id)); }
1154
+        catch (Exception $e) {
1155
+            $this->Result->show("danger", _("Error: ").$e->getMessage());
1156
+            return false;
1157
+        }
1158
+        #result
1159
+        return true;
1160
+    }
1161
+
1162
+    /**
1163
+     * Checks if PTR record exists
1164
+     *
1165
+     * @access private
1166
+     * @param mixed $ptr_id (default: 0)
1167
+     * @return void
1168
+     */
1169
+    private function ptr_exists ($ptr_id = 0) {
1170
+        return $this->PowerDNS->record_id_exists ($ptr_id);
1171
+    }
1172
+
1173
+    /**
1174
+     * Returns array of all ptr indexes in surrent subnet
1175
+     *
1176
+     * @access public
1177
+     * @param mixed $subnetId
1178
+     * @return void
1179
+     */
1180
+    public function ptr_get_subnet_indexes ($subnetId) {
1181
+        try { $indexes = $this->Database->getObjectsQuery("select `PTR` from `ipaddresses` where `PTR` != 0 and `subnetId` = ?;", array($subnetId)); }
1182
+        catch (Exception $e) {
1183
+            $this->Result->show("danger", _("Error: ").$e->getMessage());
1184
+            return false;
1185
+        }
1186
+        # parse
1187
+        if (sizeof($indexes)>0) {
1188
+            $out = array();
1189
+            // loop
1190
+            foreach ($indexes as $i) {
1191
+                $out[] = $i->PTR;
1192
+            }
1193
+            return $out;
1194
+        }
1195
+        else {
1196
+            return array();
1197
+        }
1198
+    }
1199
+
1200
+
1201
+
1202
+
1203
+
1204
+
1205
+
1206
+
1207
+
1208
+
1209
+
1210
+
1211
+
1212
+
1213
+    /**
1214
+     * @import address methods
1215
+     * -------------------------------
1216
+     */
1217
+
1218
+    /**
1219
+     * Import single line from csv to database
1220
+     *
1221
+     * @access public
1222
+     * @param array $address
1223
+     * @param int $subnetId
1224
+     * @return void
1225
+     */
1226
+    public function import_address_from_csv ($address, $subnetId) {
1227
+        # Subnets object
1228
+        $this->initialize_subnets_object ();
1229
+
1230
+        # fetch subnet details
1231
+        $subnet = (array) $this->Subnets->fetch_subnet(null, $subnetId);
1232
+
1233
+        # verify address
1234
+        if($this->verify_address( $address[0], $this->transform_to_dotted($subnet['subnet'])."/".$subnet['mask'], false, false)!==false) { return false; }
1235
+        # check for duplicates
1236
+        if ($this->address_exists($address[0], $subnetId)) { return _('IP address already exists').' - '.$address[0]; }
1237
+
1238
+        # format insert array
1239
+        $address_insert = array("subnetId"=>$subnetId,
1240
+                                "ip_addr"=>$address[0],
1241
+                                "state"=>$address[1],
1242
+                                "description"=>$address[2],
1243
+                                "hostname"=>$address[3],
1244
+                                "mac"=>$address[4],
1245
+                                "owner"=>$address[5],
1246
+                                "switch"=>$address[6],
1247
+                                "port"=>$address[7],
1248
+                                "note"=>$address[8]
1249
+                                );
1250
+
1251
+        # switch to 0, state to active
1252
+        $address_insert['switch'] = strlen($address_insert['switch'])==0 ? 0 : $address_insert['switch'];
1253
+        $address_insert['state']  = strlen($address_insert['state'])==0 ?  1 : $address_insert['state'];
1254
+
1255
+        # custom fields, append to array
1256
+        $m=9;
1257
+        $custom_fields = $this->set_custom_fields();
1258
+        if(sizeof($custom_fields) > 0) {
1259
+            foreach($custom_fields as $c) {
1260
+                $address_insert[$c['name']] = $address[$m];
1261
+                $m++;
1262
+            }
1263
+        }
1264
+
1265
+        # insert
1266
+        return $this->modify_address_add ($address_insert);
1267
+    }
1268
+
1269
+
1270
+
1271
+
1272
+
1273
+
1274
+
1275
+
1276
+
1277
+
1278
+    /**
1279
+     * @address subnet methods
1280
+     * -------------------------------
1281
+     */
1282
+
1283
+    /**
1284
+     * Opens new Subnets connection if not already opened
1285
+     *
1286
+     * @access private
1287
+     * @return void
1288
+     */
1289
+    private function initialize_subnets_object () {
1290
+        if(!is_object($this->Subnets)) { $this->Subnets = new Subnets ($this->Database); }
1291
+    }
1292
+
1293
+    /**
1294
+     * Fetches all IP addresses in subnet
1295
+     *
1296
+     * @access public
1297
+     * @param mixed $subnetId
1298
+     * @param mixed $order (default: null)
1299
+     * @param mixed $order_direction (default: null)
1300
+     * @param string $fields (default: "*")
1301
+     * @return void
1302
+     */
1303
+    public function fetch_subnet_addresses ($subnetId, $order=null, $order_direction=null, $fields = "*") {
1304
+        # set order
1305
+        if(!is_null($order)) 	{ $order = array($order, $order_direction); }
1306
+        else 					{ $order = array("ip_addr", "asc"); }
1307
+
1308
+        # fields
1309
+        if($fields!="*") {
1310
+            $fields = implode(",", $fields);
1311
+        }
1312
+
1313
+        # escape ordering
1314
+        $order[0] = $this->Database->escape ($order[0]);
1315
+        $order[1] = $this->Database->escape ($order[1]);
1316
+
1317
+        try { $addresses = $this->Database->getObjectsQuery("SELECT $fields FROM `ipaddresses` where `subnetId` = ? order by `$order[0]` $order[1];", array($subnetId)); }
1318
+        catch (Exception $e) {
1319
+            $this->Result->show("danger", _("Error: ").$e->getMessage());
1320
+            return false;
1321
+        }
1322
+        # save to addresses cache
1323
+        if(sizeof($addresses)>0) {
1324
+            foreach($addresses as $k=>$address) {
1325
+                # add decimal format
1326
+                $address->ip = $this->transform_to_dotted ($address->ip_addr);
1327
+                # save to subnets
1328
+                $this->addresses[$address->id] = (object) $address;
1329
+                $addresses[$k]->ip = $address->ip;
1330
+            }
1331
+        }
1332
+        # result
1333
+        return sizeof($addresses)>0 ? $addresses : array();
1334
+    }
1335
+
1336
+    /**
1337
+     * Count number of IP addresses in subnet
1338
+     *
1339
+     * Returns number of addresses in subnet
1340
+     *
1341
+     * @access public
1342
+     * @param int $subnetId
1343
+     * @return int
1344
+     */
1345
+    public function count_subnet_addresses ($subnetId) {
1346
+        try { $count = $this->Database->numObjectsFilter("ipaddresses", "subnetId", $subnetId); }
1347
+        catch (Exception $e) {
1348
+            $this->Result->show("danger", _("Error: ").$e->getMessage());
1349
+            return false;
1350
+        }
1351
+        # result
1352
+        return (int) $count;
1353
+    }
1354
+
1355
+    /**
1356
+     * Count number of addresses in multiple subnets
1357
+     *
1358
+     *	we provide array of all subnet ids
1359
+     *
1360
+     * @access public
1361
+     * @param mixed $subnets
1362
+     * @return void
1363
+     */
1364
+    public function count_addresses_in_multiple_subnets ($subnets) {
1365
+        # empty
1366
+        if(empty($subnets)) { return 0; }
1367
+
1368
+        # create query
1369
+        $tmp = array();
1370
+        foreach($subnets as $k=>$s) {
1371
+            if (is_object($s))	{ $tmp[] = " `subnetId`=$s->id "; }
1372
+            else				{ $tmp[] = " `subnetId`=$s "; }
1373
+        }
1374
+        $query  = "select count(*) as `cnt` from `ipaddresses` where ".implode("or", $tmp).";";
1375
+
1376
+        # fetch
1377
+        try { $addresses = $this->Database->getObjectsQuery($query); }
1378
+        catch (Exception $e) {
1379
+            $this->Result->show("danger", _("Error: ").$e->getMessage());
1380
+            return false;
1381
+        }
1382
+        # return count
1383
+        return $addresses[0]->cnt;
1384
+    }
1385
+
1386
+
1387
+    /**
1388
+     * Fetch IP addresses for all recursive slaves
1389
+     *
1390
+     *	count returns count only, else whole subnets
1391
+     *
1392
+     * @access public
1393
+     * @param int $subnetId
1394
+     * @param bool $count
1395
+     * @return void
1396
+     */
1397
+    public function fetch_subnet_addresses_recursive ($subnetId, $count = false, $order=null, $order_direction=null ) {
1398
+        # initialize subnets
1399
+        $this->initialize_subnets_object ();
1400
+        $this->Subnets = new Subnets ($this->Database);
1401
+        $this->Subnets->reset_subnet_slaves_recursive();				//reset array of slaves before continuing
1402
+        $this->Subnets->fetch_subnet_slaves_recursive($subnetId);		//fetch array of slaves
1403
+        $this->Subnets->slaves = array_unique($this->Subnets->slaves);	//remove possible duplicates
1404
+
1405
+        # ip address order
1406
+        if(!is_null($order)) 	{ $order_addr = array($order, $order_direction); }
1407
+        else 					{ $order_addr = array("ip_addr", "asc"); }
1408
+
1409
+        # escape ordering
1410
+        $order_addr[0] = $this->Database->escape ($order_addr[0]);
1411
+        $order_addr[1] = $this->Database->escape ($order_addr[1]);
1412
+
1413
+        $ids = array();
1414
+        $ids[] = $subnetId;
1415
+
1416
+        # set query to fetch all ip addresses for specified subnets or just count
1417
+        if($count) 	{ $query = 'select count(*) as cnt from `ipaddresses` where `subnetId` = ? '; }
1418
+        else	 	{ $query = 'select * from `ipaddresses` where `subnetId` = ? '; }
1419
+        foreach($this->Subnets->slaves as $subnetId2) {
1420
+            # ignore orphaned
1421
+            if($subnetId2 != $subnetId) {
1422
+                $query  .= " or `subnetId` = ? ";
1423
+                $ids[] = $subnetId2;
1424
+            }
1425
+        }
1426
+
1427
+        $query      .= "order by `$order_addr[0]` $order_addr[1];";
1428
+        # fetch
1429
+        try { $addresses = $this->Database->getObjectsQuery($query, $ids); }
1430
+        catch (Exception $e) {
1431
+            $this->Result->show("danger", _("Error: ").$e->getMessage());
1432
+            return false;
1433
+        }
1434
+        # return ip address array or just count
1435
+        return $count ? (int) $addresses[0]->cnt : $addresses;
1436
+    }
37 1437
 
38 1438
     /**
39
-     * Last insert id
1439
+     * Search for unused address space between 2 IP addresses
40 1440
      *
41
-     * (default value: false)
1441
+     * possible unused addresses by type
42 1442
      *
43
-     * @var bool
44 1443
      * @access public
1444
+     * @param int $address1
1445
+     * @param int $address2
1446
+     * @param int $netmask
1447
+     * @param bool $empty (default: false)
1448
+     * @param bool $is_subnet (default: false)
1449
+     * @param bool $is_broadcast (default: false)
1450
+     * @return void
45 1451
      */
46
-    public $lastId = false;
1452
+    public function find_unused_addresses ($address1, $address2, $netmask, $empty=false, $is_subnet=false, $is_broadcast=false) {
1453
+        # make sure addresses are in decimal format
1454
+        $address1 = $this->transform_address ($address1, "decimal");
1455
+        $address2 = $this->transform_address ($address2, "decimal");
1456
+        # check for space
1457
+        return $this->identify_address($address1)=="IPv6" ? $this->find_unused_addresses_IPv6 ($address1, $address2, $netmask, $empty, $is_subnet, $is_broadcast) : $this->find_unused_addresses_IPv4 ($address1, $address2, $netmask, $empty);
1458
+    }
47 1459
 
48
-	/**
49
-	 * Debugging flag
50
-	 *
51
-	 * (default value: false)
52
-	 *
53
-	 * @var bool
54
-	 * @access protected
55
-	 */
56
-	protected $debugging = false;
57
-
58
-	/**
59
-	 * PEAR NET IPv4 object
60
-	 *
61
-	 * @var mixed
62
-	 * @access protected
63
-	 */
64
-	protected $Net_IPv4;
65
-
66
-	/**
67
-	 * PEAR NET IPv6 object
68
-	 *
69
-	 * @var mixed
70
-	 * @access protected
71
-	 */
72
-	protected $Net_IPv6;
73
-
74
-	/**
75
-	 * Database conenction
76
-	 *
77
-	 * @var mixed
78
-	 * @access protected
79
-	 */
80
-	protected $Database;
81
-
82
-	/**
83
-	 * Subnets object
84
-	 *
85
-	 * @var mixed
86
-	 * @access protected
87
-	 */
88
-	protected $Subnets;
89
-
90
-	/**
91
-	 * Logging object
92
-	 *
93
-	 * @var mixed
94
-	 * @access public
95
-	 */
96
-	public $Log;
97
-
98
-	/**
99
-	 * PowerDNS object
100
-	 *
101
-	 * @var mixed
102
-	 * @access private
103
-	 */
104
-	private $PowerDNS;
105
-
106
-
107
-
108
-
109
-	/**
110
-	 * __construct function
111
-	 *
112
-	 * @access public
113
-	 */
114
-	public function __construct (Database_PDO $Database) {
115
-		# Save database object
116
-		$this->Database = $Database;
117
-		# initialize Result
118
-		$this->Result = new Result ();
119
-		# debugging
120
-		$this->set_debugging();
121
-
122
-		# Log object
123
-		$this->Log = new Logging ($this->Database);
124
-	}
125
-
126
-
127
-
128
-
129
-
130
-
131
-
132
-
133
-
134
-	/**
135
-	* @address tag methods
136
-	* -------------------------------
137
-	*/
138
-
139
-	/**
140
-	 * Returns array of address types.
141
-	 *
142
-	 * @access public
143
-	 * @return array of address types and parameters
144
-	 */
145
-	public function addresses_types_fetch () {
146
-    	# fetch
147
-    	$types = $this->fetch_all_objects ("ipTags", "id");
148
-
149
-		# save to array
150
-		$types_out = array();
151
-		foreach($types as $t) {
152
-			$types_out[$t->id] = (array) $t;
153
-		}
154
-		# save
155
-		$this->address_types = $types_out;
156
-		# return
157
-		return $types_out;
158
-	}
159
-
160
-	/**
161
-	 * Sets address tag
162
-	 *
163
-	 * @access public
164
-	 * @param int $state
165
-	 * @return mixed tag
166
-	 */
167
-	public function address_type_format_tag ($state) {
168
-		# fetch address states
169
-		$this->addresses_types_fetch();
170
-		# result
171
-		if(!isset($this->address_types[$state]))	{
172
-			return "";
173
-		}
174
-		else {
175
-			if($this->address_types[$state]['showtag']==1) {
176
-				return "<i class='fa fa-".$this->address_types[$state]['type']." fa-tag state' rel='tooltip' style='color:".$this->address_types[$state]['bgcolor']."' title='"._($this->address_types[$state]['type'])."'></i>";
177
-			}
178
-		}
179
-	}
180
-
181
-	/**
182
-	 * returns address type from index
183
-	 *
184
-	 *		1 > Offline
185
-	 *
186
-	 * @access public
187
-	 * @param int $index
188
-	 * @return mixed address type
189
-	 */
190
-	public function address_type_index_to_type ($index) {
191
-		# fetch address states
192
-		$this->addresses_types_fetch();
193
-		# return
194
-		if(isset($this->address_types[$index])) {
195
-			return $this->address_types[$index]['type'];
196
-		}
197
-		else {
198
-			return $index;
199
-		}
200
-	}
201
-
202
-	/**
203
-	 * Returns address index from type
204
-	 *
205
-	 *	Offline > 1
206
-	 *
207
-	 * @access public
208
-	 * @param mixed $type
209
-	 * @return void
210
-	 */
211
-	public function address_type_type_to_index ($type = "Used") {
212
-		# null of no length
213
-		$type = strlen($type)==0 || is_null($type) ? "Used" : $type;
214
-		# fetch address states
215
-		$this->addresses_types_fetch();
216
-		# reindex
217
-		$states_assoc = array();
218
-		foreach($this->address_types as $s) {
219
-			$states_assoc[$s['type']] = $s;
220
-		}
221
-		# return
222
-		if(isset($states_assoc[$type])) {
223
-			return $states_assoc[$type]['id'];
224
-		}
225
-		else {
226
-			return $type;
227
-		}
228
-	}
229
-
230
-
231
-
232
-
233
-
234
-
235
-
236
-
237
-
238
-
239
-
240
-
241
-	/**
242
-	* @address methods
243
-	* -------------------------------
244
-	*/
245
-
246
-	/**
247
-	 * Fetches address by specified method
248
-	 *
249
-	 * @access public
250
-	 * @param string $method (default: "id")
251
-	 * @param mixed $id
252
-	 * @return object address
253
-	 */
254
-	public function fetch_address ($method, $id) {
255
-		# null method
256
-		$method = is_null($method) ? "id" : $method;
257
-		# check cache first
258
-		if(isset($this->addresses[$id]))	{
259
-			return $this->addresses[$id];
260
-		}
261
-		else {
262
-			try { $address = $this->Database->getObjectQuery("SELECT * FROM `ipaddresses` where `$method` = ? limit 1;", array($id)); }
263
-			catch (Exception $e) {
264
-				$this->Result->show("danger", _("Error: ").$e->getMessage());
265
-				return false;
266
-			}
267
-			# save to addresses cache
268
-			if(!is_null($address)) {
269
-				# add decimal format
270
-				$address->ip = $this->transform_to_dotted ($address->ip_addr);
271
-				# save to subnets
272
-				$this->addresses[$id] = (object) $address;
273
-			}
274
-			#result
275
-			return !is_null($address) ? $address : false;
276
-		}
277
-	}
278
-
279
-	/**
280
-	 * Fetch addresses on int ip_addr and subnetId
281
-	 *
282
-	 * @access public
283
-	 * @param mixed $ip_addr
284
-	 * @param mixed $subnetId
285
-	 * @return void
286
-	 */
287
-	public function fetch_address_multiple_criteria ($ip_addr, $subnetId) {
288
-		try { $address = $this->Database->getObjectQuery("SELECT * FROM `ipaddresses` where `ip_addr` = ? and `subnetId` = ? limit 1;", array($ip_addr, $subnetId)); }
289
-		catch (Exception $e) {
290
-			$this->Result->show("danger", _("Error: ").$e->getMessage());
291
-			return false;
292
-		}
293
-		# save to addresses cache
294
-		if(sizeof($address)>0) {
295
-			# add decimal format
296
-			$address->ip = $this->transform_to_dotted ($address->ip_addr);
297
-			# save to subnets
298
-			$this->addresses[$address->id] = (object) $address;
299
-		}
300
-		#result
301
-		return !is_null($address) ? $address : false;
302
-	}
303
-
304
-	/**
305
-	 * Searches database for similar addresses
306
-	 *
307
-	 * @access public
308
-	 * @param mixed $linked_field
309
-	 * @param mixed $value
310
-	 * @param mixed $address_id
311
-	 * @return void
312
-	 */
313
-	public function search_similar_addresses ($linked_field, $value, $address_id) {
314
-    	// checks
315
-    	if(strlen($linked_field)>0 && strlen($value)>0 && is_numeric($address_id)) {
316
-        	// search
317
-     		try { $addresses = $this->Database->getObjectsQuery("SELECT * FROM `ipaddresses` where `$linked_field` = ? and `id` != ? and state != 4;", array($value, $address_id)); }
318
-    		catch (Exception $e) {
319
-    			$this->Result->show("danger", _("Error: ").$e->getMessage());
320
-    			return false;
321
-    		}
322
-    		#result
323
-    		return sizeof($addresses)>0 ? $addresses : false;
324
-        }
325
-        else {
326
-            return false;
327
-        }
328
-	}
329
-
330
-	/**
331
-	 * Address modification
332
-	 *
333
-	 * @access public
334
-	 * @param mixed $address
335
-	 * @param bool $mail_changelog (default: true)
336
-	 * @return void
337
-	 */
338
-	public function modify_address ($address, $mail_changelog = true) {
339
-		# save changelog
340
-		$this->mail_changelog  = $mail_changelog;
341
-		# null empty values
342
-		$address = $this->reformat_empty_array_fields ($address, null);
343
-		# strip tags
344
-		$address = $this->strip_input_tags ($address);
345
-		# execute based on action
346
-		if($address['action']=="add")			{ return $this->modify_address_add ($address); }							//create new address
347
-		elseif($address['action']=="edit")		{ return $this->modify_address_edit ($address); }							//modify existing address
348
-		elseif($address['action']=="delete")	{ return $this->modify_address_delete ($address); }							//delete address
349
-		elseif($address['action']=="move")		{ return $this->modify_address_move ($address); }							//move to new subnet
350
-		else									{ return $this->Result->show("danger", _("Invalid action"), true); }
351
-	}
352
-
353
-	/**
354
-	 * Inserts new IP address to table
355
-	 *
356
-	 * @access protected
357
-	 * @param array $address
358
-	 * @return boolean success/failure
359
-	 */
360
-	protected function modify_address_add ($address) {
361
-		# set insert array
362
-		$insert = array(
363
-						"ip_addr"               => $this->transform_address($address['ip_addr'],"decimal"),
364
-						"subnetId"              => $address['subnetId'],
365
-						"description"           => @$address['description'],
366
-						"hostname"              => @$address['hostname'],
367
-						"mac"                   => @$address['mac'],
368
-						"owner"                 => @$address['owner'],
369
-						"state"                 => @$address['state'],
370
-						"switch"                => @$address['switch'],
371
-						"port"                  => @$address['port'],
372
-						"note"                  => @$address['note'],
373
-						"is_gateway"            => @$address['is_gateway'],
374
-						"excludePing"           => @$address['excludePing'],
375
-						"PTRignore"             => @$address['PTRignore'],
376
-						"firewallAddressObject" => @$address['firewallAddressObject'],
377
-						"lastSeen"              => @$address['lastSeen']
378
-						);
379
-		# customer
380
-		if(isset($address['customer_id'])) {
381
-			if (is_numeric($address['customer_id'])) {
382
-				if ($address['customer_id']!="0") {
383
-					$insert['customer_id'] = $address['customer_id'];
384
-				}
385
-				else {
386
-					$insert['customer_id'] = NULL;
387
-				}
388
-			}
389
-		}
390
-        # location
391
-        if (isset($address['location_item'])) {
392
-            if (!is_numeric($address['location_item'])) {
393
-                $this->Result->show("danger", _("Invalid location value"), true);
1460
+    /**
1461
+     * Search for unused address space between 2 IPv4 addresses.
1462
+     *
1463
+     * unused address range or false if none available
1464
+     *
1465
+     * @access protected
1466
+     * @param int $address1
1467
+     * @param int $address2
1468
+     * @param int $netmask
1469
+     * @param bool $empty
1470
+     * @return void
1471
+     */
1472
+    protected function find_unused_addresses_IPv4 ($address1, $address2, $netmask, $empty) {
1473
+        # calculate diff
1474
+        $diff = $this->calculate_address_diff ($address1, $address2);
1475
+        # 32 subnets
1476
+        if($netmask==32) {
1477
+            if($empty) {
1478
+                return array("ip"=>$this->transform_to_dotted($address1), "hosts"=>1);
1479
+            }
1480
+            else {
1481
+                return false;
394 1482
             }
395
-            $insert['location'] = $address['location_item'];
396 1483
         }
397
-		# custom fields, append to array
398
-		foreach($this->set_custom_fields() as $c) {
399
-			$insert[$c['name']] = !empty($address[$c['name']]) ? $address[$c['name']] : $c['Default'];
400
-		}
401
-
402
-		# null empty values
403
-		$insert = $this->reformat_empty_array_fields ($insert, null);
404
-
405
-		# remove gateway
406
-		if($address['is_gateway']==1)	{ $this->remove_gateway ($address['subnetId']); }
407
-
408
-		# execute
409
-		try { $this->Database->insertObject("ipaddresses", $insert); }
410
-		catch (Exception $e) {
411
-			$this->Log->write( "Address create", "Failed to create new address<hr>".$e->getMessage()."<hr>".$this->array_to_log($this->reformat_empty_array_fields ($address, "NULL")), 2);
412
-			$this->Result->show("danger", _("Error: ").$e->getMessage(), false);
413
-			return false;
414
-		}
415
-		# save id
416
-		$this->lastId = $this->Database->lastInsertId();
417
-
418
-		# log and changelog
419
-		$address['id'] = $this->lastId;
420
-		$this->Log->write( "Address created", "New address created<hr>".$this->array_to_log($this->reformat_empty_array_fields ($address, "NULL")), 0);
421
-		$this->Log->write_changelog('ip_addr', "add", 'success', array(), $address, $this->mail_changelog);
422
-
423
-		# edit DNS PTR record
424
-		$this->ptr_modify ("add", $insert);
425
-
426
-		# threshold alert
427
-		$this->threshold_check($address);
428
-
429
-		# ok
430
-		return true;
431
-	}
432
-
433
-	/**
434
-	 * Modifies address in table or whole range if requested
435
-	 *
436
-	 * @access protected
437
-	 * @param array $address
438
-	 * @return boolean success/failure
439
-	 */
440
-	protected function modify_address_edit ($address) {
441
-		# fetch old details for logging
442
-		$address_old = $this->fetch_address (null, $address['id']);
443
-		if (isset($address['section'])) $address_old->section = $address['section'];
444
-
445
-		# set update array
446
-		$insert = array(
447
-						"id"          =>$address['id'],
448
-						"subnetId"    =>$address['subnetId'],
449
-						"ip_addr"     =>$this->transform_address($address['ip_addr'], "decimal"),
450
-						"description" =>@$address['description'],
451
-						"hostname"    =>@$address['hostname'],
452
-						"mac"         =>@$address['mac'],
453
-						"owner"       =>@$address['owner'],
454
-						"state"       =>@$address['state'],
455
-						"switch"      =>@$address['switch'],
456
-						"port"        =>@$address['port'],
457
-						"note"        =>@$address['note'],
458
-						"is_gateway"  =>@$address['is_gateway'],
459
-						"excludePing" =>@$address['excludePing'],
460
-						"PTRignore"   =>@$address['PTRignore']
461
-						);
462
- 		# customer
463
-		if(isset($address['customer_id'])) {
464
-			if (is_numeric($address['customer_id'])) {
465
-				if ($address['customer_id']!="0") {
466
-					$insert['customer_id'] = $address['customer_id'];
467
-				}
468
-				else {
469
-					$insert['customer_id'] = NULL;
470
-				}
471
-			}
472
-		}
473
-        # location
474
-        if (isset($address['location_item'])) {
475
-            if (!is_numeric($address['location_item'])) {
476
-                $this->Result->show("danger", _("Invalid location value"), true);
1484
+        # 31 subnets
1485
+        elseif($netmask==31) {
1486
+
1487
+            if($empty) {
1488
+                return array("ip"=>$this->transform_to_dotted($address1), "hosts"=>2);
1489
+            }
1490
+            elseif($diff==1) {
1491
+                if($this->is_network($address1, $netmask)) {
1492
+                    return array("ip"=>$this->transform_to_dotted($address2), "hosts"=>1);
1493
+                }
1494
+                elseif($this->is_broadcast($address2, $netmask)) {
1495
+                    return array("ip"=>$this->transform_to_dotted($address1), "hosts"=>1);
1496
+                }
1497
+                else {
1498
+                    return false;
1499
+                }
1500
+            }
1501
+            else {
1502
+                return false;
477 1503
             }
478
-            $insert['location'] = $address['location_item'];
479 1504
         }
480
-		# custom fields, append to array
481
-		foreach($this->set_custom_fields() as $c) {
482
-			$insert[$c['name']] = !empty($address[$c['name']]) ? $address[$c['name']] : $c['Default'];
483
-		}
484
-
485
-		# set primary key for update
486
-		if($address['type']=="series") {
487
-			$id1 = "subnetId";
488
-			$id2 = "ip_addr";
489
-			unset($insert['id']);
490
-		} else {
491
-			$id1 = "id";
492
-			$id2 = null;
493
-		}
494
-
495
-		# remove gateway
496
-		if($address['is_gateway']==1)	{ $this->remove_gateway ($address['subnetId']); }
497
-
498
-		# execute
499
-		try { $this->Database->updateObject("ipaddresses", $insert, $id1, $id2); }
500
-		catch (Exception $e) {
501
-			$this->Log->write( "Address edit", "Failed to edit address $address[ip_addr]<hr>".$e->getMessage()."<hr>".$this->array_to_log($this->reformat_empty_array_fields ($address, "NULL")), 2);
502
-			$this->Result->show("danger", _("Error: ").$e->getMessage(), false);
503
-			return false;
504
-		}
505
-
506
-		# set the firewall address object to avoid logging
507
-		$address['firewallAddressObject'] = $address_old->firewallAddressObject;
508
-
509
- 		# log and changelog
510
-		$this->Log->write( "Address updated", "Address $address[ip_addr] updated<hr>".$this->array_to_log($this->reformat_empty_array_fields ($address, "NULL")), 0);
511
-		$this->Log->write_changelog('ip_addr', "edit", 'success', (array) $address_old, $address, $this->mail_changelog);
512
-
513
-		# edit DNS PTR record
514
-		$insert['PTR']=@$address['PTR'];
515
-		$this->ptr_modify ("edit", $insert);
516
-
517
-		# ok
518
-		return true;
519
-	}
520
-
521
-	/**
522
-	 * Deletes address or address range.
523
-	 *
524
-	 * @access protected
525
-	 * @param array $address
526
-	 * @return boolean success/failure
527
-	 */
528
-	protected function modify_address_delete ($address) {
529
-		# fetch old details for logging
530
-		$address_old = $this->fetch_address (null, $address['id']);
531
-		if (isset($address['section'])) $address_old->section = $address['section'];
532
-
533
-		# series?
534
-		if($address['type']=="series") {
535
-			$field  = "subnetId";	$value  = $address['subnetId'];
536
-			$field2 = "ip_addr";	$value2 = $this->transform_address ($address['ip_addr'], "decimal");
537
-		} else {
538
-			$field  = "id";			$value  = $address['id'];
539
-			$field2 = null;			$value2 = null;
540
-		}
541
-		# execute
542
-		try { $this->Database->deleteRow("ipaddresses", $field, $value, $field2, $value2); }
543
-		catch (Exception $e) {
544
-			$this->Log->write( "Address delete", "Failed to delete address $address[ip_addr]<hr>".$e->getMessage()."<hr>".$this->array_to_log((array) $address_old), 2);
545
-			$this->Result->show("danger", _("Error: ").$e->getMessage(), false);
546
-			return false;
547
-		}
548
-
549
-		# log and changelog
550
-		$this->Log->write( "Address deleted", "Address $address[ip_addr] deleted<hr>".$this->array_to_log((array) $address_old), 0);
551
-		$this->Log->write_changelog('ip_addr', "delete", 'success', (array) $address_old, array(), $this->mail_changelog);
552
-
553
-		# edit DNS PTR record
554
-		$this->ptr_modify ("delete", $address);
555
-
556
-		# remove all referenced records
557
-		if(@$address['remove_all_dns_records']=="1") {
558
-    		$this->pdns_remove_ip_and_hostname_records ($address);
1505
+        # if diff is less than 2 return false */
1506
+        elseif ( $diff < 2 ) {
1507
+                return false;
559 1508
         }
560
-        # remove from NAT
561
-        $this->remove_address_nat_items ($address['id'], true);
562
-		# ok
563
-		return true;
564
-	}
565
-
566
-	/**
567
-	 * Moves address to new subnet
568
-	 *
569
-	 * @access protected
570
-	 * @param array $address
571
-	 * @return boolean success/failure
572
-	 */
573
-	protected function modify_address_move ($address) {
574
-		# execute
575
-		try { $this->Database->updateObject("ipaddresses", array("subnetId"=>$address['newSubnet'], "id"=>$address['id'])); }
576
-		catch (Exception $e) {
577
-			$this->Result->show("danger", _("Error: ").$e->getMessage(), false);
578
-			return false;
579
-		}
580
-		# ok
581
-		return true;
582
-	}
583
-
584
-	/**
585
-	 * Remove item from nat when item is removed
586
-	 *
587
-	 * @method remove_nat_item
588
-	 *
589
-	 * @param  int $obj_id
590
-	 * @param  bool $print
591
-	 *
592
-	 * @return int
593
-	 */
594
-	public function remove_address_nat_items ($obj_id = 0, $print = true) {
595
-		# set found flag for returns
596
-		$found = 0;
597
-		# fetch all nats
598
-		try { $all_nats = $this->Database->getObjectsQuery ("select * from `nat` where `src` like :id or `dst` like :id", array ("id"=>'%"'.$obj_id.'"%')); }
599
-		catch (Exception $e) {
600
-			$this->Result->show("danger", _("Error: ").$e->getMessage());
601
-			return false;
602
-		}
603
-		# loop and check for object ids
604
-		if(!empty($all_nats)) {
605
-			# init admin object
606
-			$Admin = new Admin ($this->Database, false);
607
-			# loop
608
-			foreach ($all_nats as $nat) {
609
-			    # remove item from nat
610
-			    $s = json_decode($nat->src, true);
611
-			    $d = json_decode($nat->dst, true);
612
-
613
-			    if(is_array($s['ipaddresses']))
614
-			    $s['ipaddresses'] = array_diff($s['ipaddresses'], array($obj_id));
615
-			    if(is_array($d['ipaddresses']))
616
-			    $d['ipaddresses'] = array_diff($d['ipaddresses'], array($obj_id));
617
-
618
-			    # save back and update
619
-			    $src_new = json_encode(array_filter($s));
620
-			    $dst_new = json_encode(array_filter($d));
621
-
622
-			    # update only if diff found
623
-			    if($s!=$src_new || $d!=$dst_new) {
624
-			    	$found++;
625
-
626
-				    if($Admin->object_modify ("nat", "edit", "id", array("id"=>$nat->id, "src"=>$src_new, "dst"=>$dst_new))!==false) {
627
-				    	if($print) {
628
-					        $this->Result->show("success", "Address removed from NAT", false);
629
-						}
630
-				    }
631
-			    }
632
-			}
633
-		}
634
-		# return
635
-		return $found;
636
-	}
637
-
638
-	/**
639
-	 * Updates hostname for IP addresses
640
-	 *
641
-	 * @method update_address_hostname
642
-	 *
643
-	 * @param  mixed $ip
644
-	 * @param  int $id
645
-	 * @param  string $hostname
646
-	 *
647
-	 * @return void
648
-	 */
649
-	public function update_address_hostname ($ip, $id, $hostname = "") {
650
-		if(is_numeric($id) && strlen($hostname)>0) {
651
-			try { $this->Database->updateObject("ipaddresses", array("id"=>$id, "hostname"=>$hostname)); }
652
-			catch (Exception $e) {
653
-				return false;
654
-			}
655
-			// save log
656
-			$this->Log->write( "Address DNS resolved", "Address $ip resolved<hr>".$this->array_to_log((array) $hostname), 0);
657
-			$this->Log->write_changelog('ip_addr', "edit", 'success', array ("id"=>$id, "hostname"=>""), array("id"=>$id, "hostname"=>$hostname), $this->mail_changelog);
658
-		}
659
-	}
660
-
661
-	/**
662
-	 * Checks if subnet usage is over threshold and sends alert
663
-	 *
664
-	 * @access private
665
-	 * @param mixed $address
666
-	 * @return void
667
-	 */
668
-	private function threshold_check ($address) {
669
-    	$address = (object) $address;
670
-    	$content = array();
671
-    	$content_plain = array();
672
-
673
-        # fetch settings
674
-        $this->get_settings ();
675
-    	# enabled ?
676
-    	if ($this->settings->enableThreshold=="1") {
677
-        	# object
678
-        	if (!is_object($this->Subnets)) {
679
-            	$this->Subnets = new Subnets ($this->Database);
680
-        	}
681
-        	# fetch subnet
682
-        	$subnet = $this->Subnets->fetch_subnet("id", $address->subnetId);
683
-        	# threshold set ?
684
-        	if ($subnet->threshold>0) {
685
-            	# calculate subnet usage
686
-            	$subnet_usage = $this->Subnets->calculate_subnet_usage ($subnet);
687
-            	# if over send mail
688
-            	if (gmp_strval(gmp_sub(100,(int) round($subnet_usage['freehosts_percent'], 0))) > $subnet->threshold) {
689
-                	// fetch mail settings
690
-                	$Tools = new Tools ($this->Database);
691
-                	$admins        = $Tools->fetch_multiple_objects ("users", "role", "Administrator");
692
-                	// if some recipients
693
-                	if ($admins !== false) {
694
-						# try to send
695
-						try {
696
-	                    	// mail settings
697
-	                        $mail_settings = $Tools->fetch_object ("settingsMail", "id", 1);
698
-	                    	// mail class
699
-	                    	$phpipam_mail = new phpipam_mail ($this->settings, $mail_settings);
700
-
701
-	                        // set parameters
702
-	                        $subject = "Subnet threshold limit reached"." (".$this->transform_address($subnet->subnet,"dotted")."/".$subnet->mask.")";
703
-	                        $content[] = "<table style='margin-left:10px;margin-top:5px;width:auto;padding:0px;border-collapse:collapse;'>";
704
-	                        $content[] = "<tr><td style='padding:5px;margin:0px;color:#333;font-size:16px;text-shadow:1px 1px 1px white;border-bottom:1px solid #eeeeee;' colspan='2'>$this->mail_font_style<strong>$subject</font></td></tr>";
705
-	                        $content[] = '<tr><td style="padding: 0px;padding-left:10px;margin:0px;line-height:18px;text-align:left;">'.$this->mail_font_style.''._('Subnet').'</a></font></td>	<td style="padding: 0px;padding-left:15px;margin:0px;line-height:18px;text-align:left;padding-top:10px;"><a href="'.$this->createURL().''.create_link("subnets",$subnet->sectionId, $subnet->id).'">'.$this->mail_font_style_href . $this->transform_address($subnet->subnet,"dotted")."/".$subnet->mask .'</font></a></td></tr>';
706
-	                        $content[] = '<tr><td style="padding: 0px;padding-left:10px;margin:0px;line-height:18px;text-align:left;">'.$this->mail_font_style.''._('Description').'</font></td>	  	<td style="padding: 0px;padding-left:15px;margin:0px;line-height:18px;text-align:left;">'.$this->mail_font_style.''. $subnet->description .'</font></td></tr>';
707
-	                        $content[] = '<tr><td style="padding: 0px;padding-left:10px;margin:0px;line-height:18px;text-align:left;">'.$this->mail_font_style.''._('Usage').' (%)</font></td>	<td style="padding: 0px;padding-left:15px;margin:0px;line-height:18px;text-align:left;">'.$this->mail_font_style.''. gmp_strval(gmp_sub(100,(int) round($subnet_usage['freehosts_percent'], 0))) .'</font></td></tr>';
708
-	                        $content[] = "</table>";
709
-	                        // plain
710
-	                        $content_plain[] = "$subject"."\r\n------------------------------\r\n";
711
-	                        $content_plain[] = _("Subnet").": ".$this->transform_address($subnet->subnet,"dotted")."/".$subnet->mask;
712
-	                        $content_plain[] = _("Usage")." (%) : ".gmp_strval(gmp_sub(100,(int) round($subnet_usage['freehosts_percent'], 0)));
713
-
714
-	                        # set content
715
-	                        $content 		= $phpipam_mail->generate_message (implode("\r\n", $content));
716
-	                        $content_plain 	= implode("\r\n",$content_plain);
717
-
718
-                        	$phpipam_mail->Php_mailer->setFrom($mail_settings->mAdminMail, $mail_settings->mAdminName);
719
-                        	//add all admins to CC
720
-                        	$recipients = $this->changelog_mail_get_recipients ($subnet->id);
721
-
722
-                        	if ($recipients!==false) {
723
-                        		foreach($recipients as $a) {
724
-                    			    $phpipam_mail->Php_mailer->addAddress($a->email);
725
-                        		}
726
-
727
-                            	$phpipam_mail->Php_mailer->Subject = $subject;
728
-                            	$phpipam_mail->Php_mailer->msgHTML($content);
729
-                            	$phpipam_mail->Php_mailer->AltBody = $content_plain;
730
-                            	//send
731
-                            	$phpipam_mail->Php_mailer->send();
732
-                        	}
733
-                        	else {
734
-                            	return true;
735
-                        	}
736
-                        } catch (phpmailerException $e) {
737
-                        	$this->Result->show("danger", "Mailer Error: ".$e->errorMessage(), true);
738
-                        } catch (Exception $e) {
739
-                        	$this->Result->show("danger", "Mailer Error: ".$e->getMessage(), true);
740
-                        }
741
-                    }
742
-            	}
743
-        	}
744
-        	else {
745
-            	return true;
746
-        	}
747
-    	}
748
-    	else {
749
-        	return true;
750
-    	}
751
-	}
752
-
753
-	/**
754
-	 * Removes gateway if it exists
755
-	 *
756
-	 * @access public
757
-	 * @param mixed $subnetId
758
-	 * @return void
759
-	 */
760
-	public function remove_gateway ($subnetId) {
761
-		try { $this->Database->updateObject("ipaddresses", array("subnetId"=>$subnetId, "is_gateway"=>0), "subnetId"); }
762
-		catch (Exception $e) {
763
-			$this->Result->show("danger", _("Error: ").$e->getMessage());
764
-			return false;
765
-		}
766
-	}
767
-
768
-	/**
769
-	 * Fetches custom IP address fields
770
-	 *
771
-	 * @access public
772
-	 * @return object custom address fields
773
-	 */
774
-	public function set_custom_fields () {
775
-		# Tools object
776
-		$Tools = new Tools ($this->Database);
777
-		# fetch
778
-		return $Tools->fetch_custom_fields ('ipaddresses');
779
-	}
780
-
781
-	/**
782
-	 * Checks if address already exists in subnet
783
-	 *
784
-	 *	if cnt is false we will return id if it exists and false ifnot
785
-	 *
786
-	 * @access public
787
-	 * @param int $address
788
-	 * @param int $subnetId
789
-	 * @param int $subnetId
790
-	 * @return boolean success/failure
791
-	 */
792
-	public function address_exists ($address, $subnetId, $cnt = true) {
793
-		# make sure it is in decimal format
794
-		$address = $this->transform_address($address, "decimal");
795
-		# check
796
-		if($cnt===true) { $query = "select count(*) as `cnt` from `ipaddresses` where `subnetId`=? and `ip_addr`=?;"; }
797
-		else			{ $query = "select `id` from `ipaddresses` where `subnetId`=? and `ip_addr`=?;";  }
798
-		# fetch
799
-		try { $count = $this->Database->getObjectQuery($query, array($subnetId, $address)); }
800
-		catch (Exception $e) {
801
-			$this->Result->show("danger", _("Error: ").$e->getMessage());
802
-			return false;
803
-		}
804
-		# result
805
-		if ($cnt===true)	{ return $count->cnt==0 ? false : true; }
806
-		else				{ return is_null($count->id) ? false : $count->id; }
807
-	}
808
-
809
-	/**
810
-	 * Calculates diff between two IP addresses
811
-	 *
812
-	 * @access public
813
-	 * @param int $ip1
814
-	 * @param int $ip2
815
-	 * @return void
816
-	 */
817
-	public function calculate_address_diff ($ip1, $ip2) {
818
-		return gmp_strval(gmp_sub($ip2, $ip1));
819
-	}
820
-
821
-
822
-	/**
823
-	 * Returns first available subnet address, false if none
824
-	 *
825
-	 * @access public
826
-	 * @param int $subnetId
827
-	 * @param obj $Subnets
828
-	 * @return int / false
829
-	 */
830
-	public function get_first_available_address ($subnetId, $Subnets) {
831
-
832
-		# fetch all addresses in subnet and subnet
833
-		$addresses = $this->fetch_subnet_addresses ($subnetId, "ip_addr", "asc", array("ip_addr"));
834
-		$subnet = (array) $Subnets->fetch_subnet(null, $subnetId);
835
-
836
-		# if folder return false
837
-		if ($subnet['isFolder']=="1")                                                                   { return false; }
838
-
839
-		# false if slaves
840
-		$this->Subnets = new Subnets ($this->Database);
841
-		if($this->Subnets->has_slaves ($subnetId))                                                      { return false; }
842
-
843
-	    # get max hosts
844
-	    $max_hosts = $Subnets->get_max_hosts ($subnet['mask'], $this->identify_address($subnet['subnet']));
845
-
846
-		# full subnet?
847
-		if(sizeof($addresses)>=$max_hosts)																{ return false; } 	//full subnet
848
-
849
-		# set type
850
-		$ip_version = $this->identify_address ($subnet['subnet']);
851
-	    # get first diff > 1
852
-	    if(sizeof($addresses)>0) {
853
-		    foreach($addresses as $k=>$ipaddress) {
854
-			    # check subnet and first IP
855
-			    if($k==0) {
856
-				    # /31 fix
857
-				    if($subnet['mask']==31)	{
858
-					    if(gmp_strval(gmp_sub($addresses[$k]->ip_addr, $subnet['subnet']))>0) 			{ return gmp_strval($subnet['subnet']); }
859
-				    } else {
860
-					    if(gmp_strval(gmp_sub($addresses[$k]->ip_addr, $subnet['subnet']))>1) 			{ return gmp_strval(gmp_add($subnet['subnet'], 1)); }
861
-					    elseif($ip_version=="IPv6") {
862
-						    if(sizeof($addresses)==1) {
863
-							    if(gmp_strval(gmp_sub($addresses[$k]->ip_addr, $subnet['subnet']))==0)	{ return gmp_strval(gmp_add($subnet['subnet'], 1)); }
864
-						    }
865
-					    }
866
-				    }
867
-			    }
868
-			    else {
869
-				    if(gmp_strval(gmp_sub($addresses[$k]->ip_addr, $addresses[$k-1]->ip_addr))>1) 		{ return gmp_strval(gmp_add($addresses[$k-1]->ip_addr, 1)); }
870
-			    }
871
-		    }
872
-		    # all consecutive, last + 1
873
-		    																							{ return gmp_strval(gmp_add($addresses[$k]->ip_addr, 1)); }
874
-	    }
875
-	    # no addresses
876
-	    else {
877
-		    # /32, /31
878
-		    if($subnet['mask']==32 || $subnet['mask']==31 || $ip_version=="IPv6") 						{ return $subnet['subnet']; }
879
-		    else																						{ return gmp_strval(gmp_add($subnet['subnet'], 1)); }
880
-	    }
881
-	}
882
-
883
-
884
-
885
-
886
-
887
-
888
-
889
-
890
-
891
-	/**
892
-	 * @powerDNS
893
-	 * -------------------------------
894
-	 */
895
-
896
-	/**
897
-	 * Modifes powerDNS PTR record
898
-	 *
899
-	 * @access public
900
-	 * @param mixed $action
901
-	 * @param mixed $address
902
-	 * @param bool $print_error (default: true)
903
-	 * @return void
904
-	 */
905
-	public function ptr_modify ($action, $address, $print_error = true) {
906
-        // fetch settings
907
-        $this->settings ();
908
-        //check if powerdns enabled
909
-        if ($this->settings->enablePowerDNS!=1) {
910
-            return false;
1509
+        # if diff is 2 return 1 IP address in the middle */
1510
+        elseif ( $diff == 2 ) {
1511
+                return array("ip"=>$this->transform_to_dotted($address1+1), "hosts"=>1);
911 1512
         }
912
-        //enabled, proceed
1513
+        # if diff is more than 2 return pool */
913 1514
         else {
914
-    		// first check if subnet selected for PTR records
915
-    		$this->initialize_subnets_object ();
916
-    		$subnet = $this->Subnets->fetch_subnet ("id", $address['subnetId']);
917
-    		if ($subnet->DNSrecursive!="1") { return false; }
918
-
919
-    		// ignore if PTRignore set
920
-    		if ($address['PTRignore']=="1")	{
921
-				// validate db
922
-				$this->pdns_validate_connection ();
923
-				// remove if it exists
924
-				if ($this->ptr_exists ($address['PTR'])) {
925
-					$this->ptr_delete ($address, false);
926
-										{ return false; }
927
-				}
928
-				else {
929
-										{ return true; }
930
-				}
931
-    		}
932
-    		// validate db
933
-    		$this->pdns_validate_connection ();
934
-
935
-    		// to object
936
-    		$address = (object) $address;
937
-    		# execute based on action
938
-    		if($action=="add")				{ return $this->ptr_add ($address, $print_error); }							//create new PTR
939
-    		elseif($action=="edit")			{ return $this->ptr_edit ($address, $print_error); }						//modify existing PTR
940
-    		elseif($action=="delete")		{ return $this->ptr_delete ($address, $print_error); }						//delete PTR
941
-    		else							{ return $this->Result->show("danger", _("Invalid PDNS action"), true); }
942
-        }
943
-	}
944
-
945
-	/**
946
-	 * This function removes all records - ip and hostname referenced by address.
947
-	 *
948
-	 * @access public
949
-	 * @param mixed $address
950
-	 * @return void
951
-	 */
952
-	public function pdns_remove_ip_and_hostname_records ($address) {
953
-        // fetch settings
954
-        $this->settings ();
955
-        //check if powerdns enabled
956
-        if ($this->settings->enablePowerDNS!=1) {
957
-            return false;
1515
+                return array("ip"=>$this->transform_to_dotted($address1+1)." - ".$this->transform_to_dotted(($address2-1)), "hosts"=>gmp_strval(gmp_sub($diff, 1)));
1516
+        }
1517
+        # default false
1518
+        return false;
1519
+    }
1520
+
1521
+    /**
1522
+     * Search for unused address space between 2 IPv6 addresses
1523
+     *
1524
+     * Return unused address range or false if none available
1525
+     *
1526
+     * @access protected
1527
+     * @param int $address1
1528
+     * @param int $address2
1529
+     * @param int $netmask
1530
+     * @param bool $empty (default: false)
1531
+     * @param bool $is_subnet (default: false)
1532
+     * @param bool $is_broadcast (default: false)
1533
+     * @return void
1534
+     */
1535
+    protected function find_unused_addresses_IPv6 ($address1, $address2, $netmask, $empty = false, $is_subnet = false, $is_broadcast = false) {
1536
+        # Initialize PEAR NET object
1537
+        $this->initialize_pear_net_IPv6 ();
1538
+
1539
+        if($empty) {
1540
+            $Subnets = new Subnets ($this->Database);
1541
+            return array("ip"=>$this->transform_to_dotted(gmp_strval($address1))." - ".$this->transform_to_dotted(gmp_strval($address2)), "hosts"=>$Subnets->get_max_hosts ($netmask, "IPv6"));
958 1542
         }
959
-		// validate db
960
-		$this->pdns_validate_connection ();
961
-		// execute
962
-		return $this->PowerDNS->pdns_remove_ip_and_hostname_records ($address['hostname'], $address['ip_addr']);
963
-	}
964
-
965
-	/**
966
-	 *  Validates pdns database connection
967
-	 *
968
-	 * @access public
969
-	 * @param bool $die (default: false)
970
-	 * @return void
971
-	 */
972
-	public function pdns_validate_connection ($die = true) {
973
-		# powerDNS class
974
-		$this->PowerDNS = new PowerDNS ($this->Database);
975
-		# add API info
976
-		if(isset($this->api)) {
977
-			$this->PowerDNS->api = $this->api;
978
-		}
979
-		# check connection
980
-		if($this->PowerDNS->db_check()===false && $die) { $this->Result->show("danger", _("Cannot connect to powerDNS database"), true); }
981
-		# get settings
982
-		$this->get_settings ();
983
-	}
984
-
985
-	/**
986
-	 * Set zone name and fetch domain details
987
-	 *
988
-	 * @access private
989
-	 * @param mixed $subnet_id
990
-	 * @return array|false
991
-	 */
992
-	private function pdns_fetch_domain ($subnet_id) {
993
-		# initialize subnets
994
-		$this->initialize_subnets_object ();
995
-		// fetch subnet
996
-		$subnet = $this->Subnets->fetch_subnet ("id", $subnet_id);
997
-		if($subnet===false)							{  $this->Result->show("danger", _("Invalid subnet Id"), true); }
998
-
999
-		// set PTR zone name from IP/mash
1000
-		$zone = $this->PowerDNS->get_ptr_zone_name ($this->transform_address ($subnet->subnet, "dotted"), $subnet->mask);
1001
-		// try to fetch
1002
-		return  $this->PowerDNS->fetch_domain_by_name ($zone);
1003
-	}
1004
-
1005
-	/**
1006
-	 * Create new PTR record when adding new IP address
1007
-	 *
1008
-	 * @access public
1009
-	 * @param mixed $address
1010
-	 * @param mixed $print_error (default: true)
1011
-	 * @param mixed $id (default: NULL)
1012
-	 * @return void
1013
-	 */
1014
-	public function ptr_add ($address, $print_error = true, $id = null) {
1015
-		// decode values
1016
-		$values = json_decode($this->settings->powerDNS);
1017
-
1018
-    	// set default hostname for PTR if set
1019
-    	if (strlen($address->hostname)==0) {
1020
-        	if (strlen($values->def_ptr_domain)>0) {
1021
-            	$address->hostname = $values->def_ptr_domain;
1022
-        	}
1023
-    	}
1024
-		// validate hostname
1025
-		if ($this->validate_hostname ($address->hostname)===false)		{ return false; }
1026
-		// fetch domain
1027
-		$domain = $this->pdns_fetch_domain ($address->subnetId);
1028
-
1029
-		// formulate new record
1030
-		$record = $this->PowerDNS->formulate_new_record ($domain->id, $this->PowerDNS->get_ip_ptr_name ($this->transform_address ($address->ip_addr, "dotted")), "PTR", $address->hostname, $values->ttl);
1031
-		// insert record
1032
-		$this->PowerDNS->add_domain_record ($record, false);
1033
-		// link to address
1034
-		$id = $id===null ? $this->lastId : $id;
1035
-		$this->ptr_link ($id, $this->PowerDNS->lastId);
1036
-		// ok
1037
-		if ($print_error && php_sapi_name()!="cli")
1038
-		$this->Result->show("success", "PTR record created", false);
1039
-
1040
-		return true;
1041
-	}
1042
-
1043
-	/**
1044
-	 * Edits PTR
1045
-	 *
1046
-	 * @access public
1047
-	 * @param mixed $address
1048
-	 * @param mixed $print_error (default: true)
1049
-	 * @return void
1050
-	 */
1051
-	public function ptr_edit ($address, $print_error = true) {
1052
-		// validate hostname
1053
-		if ($this->validate_hostname ($address->hostname)===false)	{
1054
-			// remove pointer if it exists!
1055
-			if ($this->ptr_exists ($address->PTR)===true)	{ $this->ptr_delete ($address, $print_error); }
1056
-			else											{ return false; }
1057
-		}
1058
-
1059
-		// new record
1060
- 		if ($this->ptr_exists ($address->PTR)===false) {
1061
-	 		// fake lastid
1062
-	 		$this->lastId = $address->id;
1063
-	 		// new ptr record
1064
-	 		$this->ptr_add ($address, true);
1065
- 		}
1066
- 		// update PTR
1067
- 		else {
1068
-			// fetch domain
1069
-			$domain = $this->pdns_fetch_domain ($address->subnetId);
1070
-
1071
-			// fetch old
1072
-			$old_record = $this->PowerDNS->fetch_record ($address->PTR);
1073
-
1074
-			// create insert array
1075
-			$update = $this->PowerDNS->formulate_update_record ($this->PowerDNS->get_ip_ptr_name ($this->transform_address ($address->ip_addr, "dotted")), null, $address->hostname, null, null, null, $old_record->change_date);
1076
-			$update['id'] = $address->PTR;
1077
-
1078
-			// update
1079
-			$this->PowerDNS->update_domain_record ($domain->id, $update, $print_error);
1080
-			// ok
1081
-			if ($print_error && php_sapi_name()!="cli")
1082
-			$this->Result->show("success", "PTR record updated", false);
1083
- 		}
1084
-	}
1085
-
1086
-	/**
1087
-	 * Remove PTR from database
1088
-	 *
1089
-	 * @access public
1090
-	 * @param mixed $address
1091
-	 * @param mixed $print_error
1092
-	 * @return void
1093
-	 */
1094
-	public function ptr_delete ($address, $print_error) {
1095
-		$address = (object) $address;
1096
-
1097
-		// remove link from ipaddresses
1098
-		$this->ptr_unlink ($address->id);
1099
-
1100
-		// exists
1101
-		if ($this->ptr_exists ($address->PTR)!==false)	{
1102
-			// fetch domain
1103
-			$domain = $this->pdns_fetch_domain ($address->subnetId);
1104
-			//remove
1105
-			$this->PowerDNS->remove_domain_record ($domain->id, $address->PTR);
1106
-    		// ok
1107
-    		if ($print_error && php_sapi_name()!="cli")
1108
-    		$this->Result->show("success", "PTR record removed", false);
1109
-		}
1110
-	}
1111
-
1112
-	/**
1113
-	 * Links PTR record with address record
1114
-	 *
1115
-	 * @access public
1116
-	 * @param mixed $address_id
1117
-	 * @param mixed $ptr_id
1118
-	 * @return void
1119
-	 */
1120
-	public function ptr_link ($address_id, $ptr_id) {
1121
-		# execute
1122
-		try { $this->Database->updateObject("ipaddresses", array("id"=>$address_id, "PTR"=>$ptr_id)); }
1123
-		catch (Exception $e) {
1124
-			$this->Result->show("danger", _("Error: ").$e->getMessage(), false);
1125
-			return false;
1126
-		}
1127
-	}
1128
-
1129
-	/**
1130
-	 * Remove PTR link if it exists
1131
-	 *
1132
-	 * @access private
1133
-	 * @param mixed $address_id
1134
-	 * @return void
1135
-	 */
1136
-	private function ptr_unlink ($address_id) {
1137
-		# execute
1138
-		try { $this->Database->updateObject("ipaddresses", array("id"=>$address_id, "PTR"=>0)); }
1139
-		catch (Exception $e) {
1140
-			$this->Result->show("danger", _("Error: ").$e->getMessage(), false);
1141
-			return false;
1142
-		}
1143
-	}
1144
-
1145
-	/**
1146
-	 * Removes all PTR references for all hosts in subnet
1147
-	 *
1148
-	 * @access public
1149
-	 * @param mixed $subnet_id
1150
-	 * @return void
1151
-	 */
1152
-	public function ptr_unlink_subnet_addresses ($subnet_id) {
1153
-		try { $this->Database->runQuery("update `ipaddresses` set `PTR` = 0 where `subnetId` = ?;", array($subnet_id)); }
1154
-		catch (Exception $e) {
1155
-			$this->Result->show("danger", _("Error: ").$e->getMessage());
1156
-			return false;
1157
-		}
1158
-		#result
1159
-		return true;
1160
-	}
1161
-
1162
-	/**
1163
-	 * Checks if PTR record exists
1164
-	 *
1165
-	 * @access private
1166
-	 * @param mixed $ptr_id (default: 0)
1167
-	 * @return void
1168
-	 */
1169
-	private function ptr_exists ($ptr_id = 0) {
1170
-		return $this->PowerDNS->record_id_exists ($ptr_id);
1171
-	}
1172
-
1173
-	/**
1174
-	 * Returns array of all ptr indexes in surrent subnet
1175
-	 *
1176
-	 * @access public
1177
-	 * @param mixed $subnetId
1178
-	 * @return void
1179
-	 */
1180
-	public function ptr_get_subnet_indexes ($subnetId) {
1181
-		try { $indexes = $this->Database->getObjectsQuery("select `PTR` from `ipaddresses` where `PTR` != 0 and `subnetId` = ?;", array($subnetId)); }
1182
-		catch (Exception $e) {
1183
-			$this->Result->show("danger", _("Error: ").$e->getMessage());
1184
-			return false;
1185
-		}
1186
-		# parse
1187
-		if (sizeof($indexes)>0) {
1188
-    		$out = array();
1189
-    		// loop
1190
-    		foreach ($indexes as $i) {
1191
-        		$out[] = $i->PTR;
1192
-    		}
1193
-    		return $out;
1194
-		}
1195
-		else {
1196
-    		return array();
1197
-		}
1198
-	}
1199
-
1200
-
1201
-
1202
-
1203
-
1204
-
1205
-
1206
-
1207
-
1208
-
1209
-
1210
-
1211
-
1212
-
1213
-	/**
1214
-	* @import address methods
1215
-	* -------------------------------
1216
-	*/
1217
-
1218
-	/**
1219
-	 * Import single line from csv to database
1220
-	 *
1221
-	 * @access public
1222
-	 * @param array $address
1223
-	 * @param int $subnetId
1224
-	 * @return void
1225
-	 */
1226
-	public function import_address_from_csv ($address, $subnetId) {
1227
-		# Subnets object
1228
-		$this->initialize_subnets_object ();
1229
-
1230
-	    # fetch subnet details
1231
-	    $subnet = (array) $this->Subnets->fetch_subnet(null, $subnetId);
1232
-
1233
-	    # verify address
1234
-	    if($this->verify_address( $address[0], $this->transform_to_dotted($subnet['subnet'])."/".$subnet['mask'], false, false)!==false) { return false; }
1235
-	    # check for duplicates
1236
-	    if ($this->address_exists($address[0], $subnetId)) { return _('IP address already exists').' - '.$address[0]; }
1237
-
1238
-		# format insert array
1239
-		$address_insert = array("subnetId"=>$subnetId,
1240
-								"ip_addr"=>$address[0],
1241
-								"state"=>$address[1],
1242
-								"description"=>$address[2],
1243
-								"hostname"=>$address[3],
1244
-								"mac"=>$address[4],
1245
-								"owner"=>$address[5],
1246
-								"switch"=>$address[6],
1247
-								"port"=>$address[7],
1248
-								"note"=>$address[8]
1249
-								);
1250
-
1251
-		# switch to 0, state to active
1252
-		$address_insert['switch'] = strlen($address_insert['switch'])==0 ? 0 : $address_insert['switch'];
1253
-		$address_insert['state']  = strlen($address_insert['state'])==0 ?  1 : $address_insert['state'];
1254
-
1255
-		# custom fields, append to array
1256
-		$m=9;
1257
-		$custom_fields = $this->set_custom_fields();
1258
-		if(sizeof($custom_fields) > 0) {
1259
-			foreach($custom_fields as $c) {
1260
-				$address_insert[$c['name']] = $address[$m];
1261
-				$m++;
1262
-			}
1263
-		}
1264
-
1265
-		# insert
1266
-		return $this->modify_address_add ($address_insert);
1267
-	}
1268
-
1269
-
1270
-
1271
-
1272
-
1273
-
1274
-
1275
-
1276
-
1277
-
1278
-	/**
1279
-	* @address subnet methods
1280
-	* -------------------------------
1281
-	*/
1282
-
1283
-	/**
1284
-	 * Opens new Subnets connection if not already opened
1285
-	 *
1286
-	 * @access private
1287
-	 * @return void
1288
-	 */
1289
-	private function initialize_subnets_object () {
1290
-		if(!is_object($this->Subnets)) { $this->Subnets = new Subnets ($this->Database); }
1291
-	}
1292
-
1293
-	/**
1294
-	 * Fetches all IP addresses in subnet
1295
-	 *
1296
-	 * @access public
1297
-	 * @param mixed $subnetId
1298
-	 * @param mixed $order (default: null)
1299
-	 * @param mixed $order_direction (default: null)
1300
-	 * @param string $fields (default: "*")
1301
-	 * @return void
1302
-	 */
1303
-	public function fetch_subnet_addresses ($subnetId, $order=null, $order_direction=null, $fields = "*") {
1304
-		# set order
1305
-		if(!is_null($order)) 	{ $order = array($order, $order_direction); }
1306
-		else 					{ $order = array("ip_addr", "asc"); }
1307
-
1308
-		# fields
1309
-		if($fields!="*") {
1310
-    		$fields = implode(",", $fields);
1311
-		}
1312
-
1313
-		# escape ordering
1314
-		$order[0] = $this->Database->escape ($order[0]);
1315
-		$order[1] = $this->Database->escape ($order[1]);
1316
-
1317
-		try { $addresses = $this->Database->getObjectsQuery("SELECT $fields FROM `ipaddresses` where `subnetId` = ? order by `$order[0]` $order[1];", array($subnetId)); }
1318
-		catch (Exception $e) {
1319
-			$this->Result->show("danger", _("Error: ").$e->getMessage());
1320
-			return false;
1321
-		}
1322
-		# save to addresses cache
1323
-		if(sizeof($addresses)>0) {
1324
-			foreach($addresses as $k=>$address) {
1325
-				# add decimal format
1326
-				$address->ip = $this->transform_to_dotted ($address->ip_addr);
1327
-				# save to subnets
1328
-				$this->addresses[$address->id] = (object) $address;
1329
-				$addresses[$k]->ip = $address->ip;
1330
-			}
1331
-		}
1332
-		# result
1333
-		return sizeof($addresses)>0 ? $addresses : array();
1334
-	}
1335
-
1336
-	/**
1337
-	 * Count number of IP addresses in subnet
1338
-	 *
1339
-	 * Returns number of addresses in subnet
1340
-	 *
1341
-	 * @access public
1342
-	 * @param int $subnetId
1343
-	 * @return int
1344
-	 */
1345
-	public function count_subnet_addresses ($subnetId) {
1346
-		try { $count = $this->Database->numObjectsFilter("ipaddresses", "subnetId", $subnetId); }
1347
-		catch (Exception $e) {
1348
-			$this->Result->show("danger", _("Error: ").$e->getMessage());
1349
-			return false;
1350
-		}
1351
-		# result
1352
-		return (int) $count;
1353
-	}
1354
-
1355
-	/**
1356
-	 * Count number of addresses in multiple subnets
1357
-	 *
1358
-	 *	we provide array of all subnet ids
1359
-	 *
1360
-	 * @access public
1361
-	 * @param mixed $subnets
1362
-	 * @return void
1363
-	 */
1364
-	public function count_addresses_in_multiple_subnets ($subnets) {
1365
-		# empty
1366
-		if(empty($subnets)) { return 0; }
1367
-
1368
-		# create query
1369
-		$tmp = array();
1370
-		foreach($subnets as $k=>$s) {
1371
-			if (is_object($s))	{ $tmp[] = " `subnetId`=$s->id "; }
1372
-			else				{ $tmp[] = " `subnetId`=$s "; }
1373
-		}
1374
-		$query  = "select count(*) as `cnt` from `ipaddresses` where ".implode("or", $tmp).";";
1375
-
1376
-		# fetch
1377
-		try { $addresses = $this->Database->getObjectsQuery($query); }
1378
-		catch (Exception $e) {
1379
-			$this->Result->show("danger", _("Error: ").$e->getMessage());
1380
-			return false;
1381
-		}
1382
-		# return count
1383
-	    return $addresses[0]->cnt;
1384
-	}
1385
-
1386
-
1387
-	/**
1388
-	 * Fetch IP addresses for all recursive slaves
1389
-	 *
1390
-	 *	count returns count only, else whole subnets
1391
-	 *
1392
-	 * @access public
1393
-	 * @param int $subnetId
1394
-	 * @param bool $count
1395
-	 * @return void
1396
-	 */
1397
-	public function fetch_subnet_addresses_recursive ($subnetId, $count = false, $order=null, $order_direction=null ) {
1398
-		# initialize subnets
1399
-		$this->initialize_subnets_object ();
1400
-		$this->Subnets = new Subnets ($this->Database);
1401
-		$this->Subnets->reset_subnet_slaves_recursive();				//reset array of slaves before continuing
1402
-	    $this->Subnets->fetch_subnet_slaves_recursive($subnetId);		//fetch array of slaves
1403
-	    $this->Subnets->slaves = array_unique($this->Subnets->slaves);	//remove possible duplicates
1404
-
1405
-		# ip address order
1406
-		if(!is_null($order)) 	{ $order_addr = array($order, $order_direction); }
1407
-		else 					{ $order_addr = array("ip_addr", "asc"); }
1408
-
1409
-		# escape ordering
1410
-		$order_addr[0] = $this->Database->escape ($order_addr[0]);
1411
-		$order_addr[1] = $this->Database->escape ($order_addr[1]);
1412
-
1413
-		$ids = array();
1414
-		$ids[] = $subnetId;
1415
-
1416
-	    # set query to fetch all ip addresses for specified subnets or just count
1417
-		if($count) 	{ $query = 'select count(*) as cnt from `ipaddresses` where `subnetId` = ? '; }
1418
-		else	 	{ $query = 'select * from `ipaddresses` where `subnetId` = ? '; }
1419
-	    foreach($this->Subnets->slaves as $subnetId2) {
1420
-		    # ignore orphaned
1421
-	    	if($subnetId2 != $subnetId) {
1422
-				$query  .= " or `subnetId` = ? ";
1423
-		    	$ids[] = $subnetId2;
1424
-			}
1425
-		}
1426
-
1427
-	    $query      .= "order by `$order_addr[0]` $order_addr[1];";
1428
-		# fetch
1429
-		try { $addresses = $this->Database->getObjectsQuery($query, $ids); }
1430
-		catch (Exception $e) {
1431
-			$this->Result->show("danger", _("Error: ").$e->getMessage());
1432
-			return false;
1433
-		}
1434
-	    # return ip address array or just count
1435
-	    return $count ? (int) $addresses[0]->cnt : $addresses;
1436
-	}
1437
-
1438
-	/**
1439
-	 * Search for unused address space between 2 IP addresses
1440
-	 *
1441
-	 * possible unused addresses by type
1442
-	 *
1443
-	 * @access public
1444
-	 * @param int $address1
1445
-	 * @param int $address2
1446
-	 * @param int $netmask
1447
-	 * @param bool $empty (default: false)
1448
-	 * @param bool $is_subnet (default: false)
1449
-	 * @param bool $is_broadcast (default: false)
1450
-	 * @return void
1451
-	 */
1452
-	public function find_unused_addresses ($address1, $address2, $netmask, $empty=false, $is_subnet=false, $is_broadcast=false) {
1453
-		# make sure addresses are in decimal format
1454
-		$address1 = $this->transform_address ($address1, "decimal");
1455
-		$address2 = $this->transform_address ($address2, "decimal");
1456
-		# check for space
1457
-		return $this->identify_address($address1)=="IPv6" ? $this->find_unused_addresses_IPv6 ($address1, $address2, $netmask, $empty, $is_subnet, $is_broadcast) : $this->find_unused_addresses_IPv4 ($address1, $address2, $netmask, $empty);
1458
-	}
1459
-
1460
-	/**
1461
-	 * Search for unused address space between 2 IPv4 addresses.
1462
-	 *
1463
-	 * unused address range or false if none available
1464
-	 *
1465
-	 * @access protected
1466
-	 * @param int $address1
1467
-	 * @param int $address2
1468
-	 * @param int $netmask
1469
-	 * @param bool $empty
1470
-	 * @return void
1471
-	 */
1472
-	protected function find_unused_addresses_IPv4 ($address1, $address2, $netmask, $empty) {
1473
-		# calculate diff
1474
-		$diff = $this->calculate_address_diff ($address1, $address2);
1475
-		# 32 subnets
1476
-		if($netmask==32) {
1477
-			if($empty) {
1478
-				return array("ip"=>$this->transform_to_dotted($address1), "hosts"=>1);
1479
-			}
1480
-			else {
1481
-				return false;
1482
-			}
1483
-		}
1484
-		# 31 subnets
1485
-		elseif($netmask==31) {
1486
-
1487
-			if($empty) {
1488
-				return array("ip"=>$this->transform_to_dotted($address1), "hosts"=>2);
1489
-			}
1490
-			elseif($diff==1) {
1491
-				if($this->is_network($address1, $netmask)) {
1492
-					return array("ip"=>$this->transform_to_dotted($address2), "hosts"=>1);
1493
-				}
1494
-				elseif($this->is_broadcast($address2, $netmask)) {
1495
-					return array("ip"=>$this->transform_to_dotted($address1), "hosts"=>1);
1496
-				}
1497
-				else {
1498
-					return false;
1499
-				}
1500
-			}
1501
-			else {
1502
-				return false;
1503
-			}
1504
-		}
1505
-		# if diff is less than 2 return false */
1506
-		elseif ( $diff < 2 ) {
1507
-        		return false;
1508
-    	}
1509
-		# if diff is 2 return 1 IP address in the middle */
1510
-		elseif ( $diff == 2 ) {
1511
-				return array("ip"=>$this->transform_to_dotted($address1+1), "hosts"=>1);
1512
-    	}
1513
-		# if diff is more than 2 return pool */
1514
-		else {
1515
-            	return array("ip"=>$this->transform_to_dotted($address1+1)." - ".$this->transform_to_dotted(($address2-1)), "hosts"=>gmp_strval(gmp_sub($diff, 1)));
1516
-    	}
1517
-    	# default false
1518
-    	return false;
1519
-	}
1520
-
1521
-	/**
1522
-	 * Search for unused address space between 2 IPv6 addresses
1523
-	 *
1524
-	 * Return unused address range or false if none available
1525
-	 *
1526
-	 * @access protected
1527
-	 * @param int $address1
1528
-	 * @param int $address2
1529
-	 * @param int $netmask
1530
-	 * @param bool $empty (default: false)
1531
-	 * @param bool $is_subnet (default: false)
1532
-	 * @param bool $is_broadcast (default: false)
1533
-	 * @return void
1534
-	 */
1535
-	protected function find_unused_addresses_IPv6 ($address1, $address2, $netmask, $empty = false, $is_subnet = false, $is_broadcast = false) {
1536
-		# Initialize PEAR NET object
1537
-		$this->initialize_pear_net_IPv6 ();
1538
-
1539
-		if($empty) {
1540
-    		$Subnets = new Subnets ($this->Database);
1541
-    		return array("ip"=>$this->transform_to_dotted(gmp_strval($address1))." - ".$this->transform_to_dotted(gmp_strval($address2)), "hosts"=>$Subnets->get_max_hosts ($netmask, "IPv6"));
1542
-		}
1543 1543
         else {
1544
-    		# calculate diff
1545
-    		$diff = $this->calculate_address_diff ($address1, $address2);
1544
+            # calculate diff
1545
+            $diff = $this->calculate_address_diff ($address1, $address2);
1546 1546
 
1547
-    		# /128
1548
-    		if($netmask == 128) {
1549
-        		if($diff>1) {
1547
+            # /128
1548
+            if($netmask == 128) {
1549
+                if($diff>1) {
1550 1550
                     return array("ip"=>$this->transform_to_dotted(gmp_strval($address1)), "hosts"=>1);
1551 1551
                 }
1552
-        	}
1553
-    		# /127
1554
-    	    elseif($netmask == 127) {
1555
-        	    if($diff==1 && $this->is_network($address1, $netmask)) {
1556
-    				return array("ip"=>$this->transform_to_dotted($address2), "hosts"=>1);
1557
-    			}
1558
-    			elseif($diff==1 && $this->is_broadcast($address2, $netmask)) {
1559
-    				return array("ip"=>$this->transform_to_dotted($address1), "hosts"=>1);
1560
-    			}
1561
-    			elseif($diff==0) {
1562
-        			return false;
1563
-    			}
1564
-    			else {
1565
-    				return array("ip"=>$this->transform_to_dotted($address1), "hosts"=>2);
1566
-    			}
1567
-    	    }
1568
-    	    # null
1569
-    	    elseif ($diff==0) {
1570
-        	    return false;
1571
-    	    }
1572
-    	    # diff 1
1573
-    	    elseif ($diff==1) {
1574
-         		if($is_subnet) {
1552
+            }
1553
+            # /127
1554
+            elseif($netmask == 127) {
1555
+                if($diff==1 && $this->is_network($address1, $netmask)) {
1556
+                    return array("ip"=>$this->transform_to_dotted($address2), "hosts"=>1);
1557
+                }
1558
+                elseif($diff==1 && $this->is_broadcast($address2, $netmask)) {
1559
+                    return array("ip"=>$this->transform_to_dotted($address1), "hosts"=>1);
1560
+                }
1561
+                elseif($diff==0) {
1562
+                    return false;
1563
+                }
1564
+                else {
1565
+                    return array("ip"=>$this->transform_to_dotted($address1), "hosts"=>2);
1566
+                }
1567
+            }
1568
+            # null
1569
+            elseif ($diff==0) {
1570
+                return false;
1571
+            }
1572
+            # diff 1
1573
+            elseif ($diff==1) {
1574
+                    if($is_subnet) {
1575 1575
                     return array("ip"=>$this->transform_to_dotted(gmp_strval($address1)), "hosts"=>1);
1576
-        		}
1577
-        		elseif($is_broadcast) {
1576
+                }
1577
+                elseif($is_broadcast) {
1578 1578
                     return array("ip"=>$this->transform_to_dotted(gmp_strval($address2)), "hosts"=>1);
1579
-        		}
1580
-        		else {
1581
-            		return false;
1582 1579
                 }
1583
-    	    }
1584
-    	    # diff 2
1585
-    	    elseif ($diff==2 && !$is_subnet && !$is_broadcast) {
1580
+                else {
1581
+                    return false;
1582
+                }
1583
+            }
1584
+            # diff 2
1585
+            elseif ($diff==2 && !$is_subnet && !$is_broadcast) {
1586 1586
                 return array("ip"=>$this->transform_to_dotted(gmp_strval(gmp_add($address1,1))), "hosts"=>1);
1587
-    	    }
1588
-    	    # default
1589
-    	    else {
1590
-        		if($is_subnet) {
1587
+            }
1588
+            # default
1589
+            else {
1590
+                if($is_subnet) {
1591 1591
                     return array("ip"=>$this->transform_to_dotted(gmp_strval($address1))." - ".$this->transform_to_dotted(gmp_strval(gmp_sub($address2,1))), "hosts"=>$this->reformat_number(gmp_strval(gmp_sub($diff,0))));
1592
-        		}
1593
-        		elseif($is_broadcast) {
1592
+                }
1593
+                elseif($is_broadcast) {
1594 1594
                     return array("ip"=>$this->transform_to_dotted(gmp_strval(gmp_add($address1,1)))." - ".$this->transform_to_dotted(gmp_strval($address2)), "hosts"=>$this->reformat_number(gmp_strval(gmp_sub($diff,0))));
1595
-        		}
1596
-        		else {
1595
+                }
1596
+                else {
1597 1597
                     return array("ip"=>$this->transform_to_dotted(gmp_strval(gmp_add($address1,1)))." - ".$this->transform_to_dotted(gmp_strval(gmp_sub($address2,1))), "hosts"=>$this->reformat_number(gmp_strval(gmp_strval(gmp_sub($diff,1)))));
1598 1598
                 }
1599
-        	}
1599
+            }
1600 1600
 
1601
-        	# default false
1602
-        	return false;
1603
-    	}
1604
-	}
1601
+            # default false
1602
+            return false;
1603
+        }
1604
+    }
1605 1605
 
1606 1606
 
1607 1607
 
@@ -1613,390 +1613,390 @@  discard block
 block discarded – undo
1613 1613
 
1614 1614
 
1615 1615
 
1616
-	/**
1617
-	* @address verification methods
1618
-	* -------------------------------
1619
-	*/
1616
+    /**
1617
+     * @address verification methods
1618
+     * -------------------------------
1619
+     */
1620 1620
 
1621
-	/**
1622
-	 * Verify IP address
1623
-	 *
1624
-	 * @access public
1625
-	 * @param int $address
1626
-	 * @param mixed $subnet (CIDR)
1627
-	 * @param bool $no_strict (default: false)
1628
-	 * @param bool $die (default: false)
1629
-	 * @return boolean
1630
-	 */
1631
-	public function verify_address( $address, $subnet, $no_strict = false, $die=true ) {
1632
-		# subnet should be in CIDR format
1633
-		$this->initialize_subnets_object ();
1634
-		if(strlen($error = $this->Subnets->verify_cidr ($subnet))>1)				{ $this->Result->show("danger", $error, $die); return true; }
1621
+    /**
1622
+     * Verify IP address
1623
+     *
1624
+     * @access public
1625
+     * @param int $address
1626
+     * @param mixed $subnet (CIDR)
1627
+     * @param bool $no_strict (default: false)
1628
+     * @param bool $die (default: false)
1629
+     * @return boolean
1630
+     */
1631
+    public function verify_address( $address, $subnet, $no_strict = false, $die=true ) {
1632
+        # subnet should be in CIDR format
1633
+        $this->initialize_subnets_object ();
1634
+        if(strlen($error = $this->Subnets->verify_cidr ($subnet))>1)				{ $this->Result->show("danger", $error, $die); return true; }
1635 1635
 
1636
-		# make checks
1637
-		return $this->identify_address ($address)=="IPv6" ? $this->verify_address_IPv6 ($address, $subnet, $die) : $this->verify_address_IPv4 ($address, $subnet, $no_strict, $die);
1638
-	}
1636
+        # make checks
1637
+        return $this->identify_address ($address)=="IPv6" ? $this->verify_address_IPv6 ($address, $subnet, $die) : $this->verify_address_IPv4 ($address, $subnet, $no_strict, $die);
1638
+    }
1639 1639
 
1640
-	/**
1641
-	 * Verify IPv4 address
1642
-	 *
1643
-	 * @access public
1644
-	 * @param int $address
1645
-	 * @param mixed $subnet (CIDR)
1646
-	 * @param bool $no_strict
1647
-	 * @param bool $die
1648
-	 * @return boolean
1649
-	 */
1650
-	public function verify_address_IPv4 ($address, $subnet, $no_strict, $die) {
1651
-		# Initialize PEAR NET object
1652
-		$this->initialize_pear_net_IPv4 ();
1640
+    /**
1641
+     * Verify IPv4 address
1642
+     *
1643
+     * @access public
1644
+     * @param int $address
1645
+     * @param mixed $subnet (CIDR)
1646
+     * @param bool $no_strict
1647
+     * @param bool $die
1648
+     * @return boolean
1649
+     */
1650
+    public function verify_address_IPv4 ($address, $subnet, $no_strict, $die) {
1651
+        # Initialize PEAR NET object
1652
+        $this->initialize_pear_net_IPv4 ();
1653 1653
         # fetch mask part
1654 1654
         $mask = explode("/", $subnet);
1655 1655
 
1656
-		# is address valid?
1657
-		if (!$this->Net_IPv4->validateIP($address)) 						{ $this->Result->show("danger", _("IP address not valid")."! ($address)", $die); return true; }
1658
-		# is address in provided subnet
1659
-		elseif (!$this->Net_IPv4->ipInNetwork($address, $subnet)) 			{ $this->Result->show("danger", _("IP address not in selected subnet")."! ($address)", $die); return true; }
1660
-		# ignore  /31 and /32 subnet broadcast and subnet checks!
1661
-		elseif ($mask[1] == 31 || $mask[1] == 32 || $no_strict == true) 	{ }
1662
-		# It cannot be subnet or broadcast
1663
-		else {
1656
+        # is address valid?
1657
+        if (!$this->Net_IPv4->validateIP($address)) 						{ $this->Result->show("danger", _("IP address not valid")."! ($address)", $die); return true; }
1658
+        # is address in provided subnet
1659
+        elseif (!$this->Net_IPv4->ipInNetwork($address, $subnet)) 			{ $this->Result->show("danger", _("IP address not in selected subnet")."! ($address)", $die); return true; }
1660
+        # ignore  /31 and /32 subnet broadcast and subnet checks!
1661
+        elseif ($mask[1] == 31 || $mask[1] == 32 || $no_strict == true) 	{ }
1662
+        # It cannot be subnet or broadcast
1663
+        else {
1664 1664
             $net = $this->Net_IPv4->parseAddress($subnet);
1665 1665
 
1666 1666
             if ($net->network == $address) 									{ $this->Result->show("danger", _("Cannot add subnet as IP address!"), $die); return true; }
1667 1667
             elseif ($net->broadcast == $address)							{ $this->Result->show("danger", _("Cannot add broadcast as IP address!"), $die); return true; }
1668
-		}
1669
-		# default
1670
-		return false;
1671
-	}
1672
-
1673
-	/**
1674
-	 * Verify IPv6 address
1675
-	 *
1676
-	 * @access public
1677
-	 * @param int $address
1678
-	 * @param mixed $subnet (CIDR)
1679
-	 * @param bool $die
1680
-	 * @return boolean
1681
-	 */
1682
-	public function verify_address_IPv6 ($address, $subnet, $die) {
1683
-		# Initialize PEAR NET object
1684
-		$this->initialize_pear_net_IPv6 ();
1685
-
1686
-		# is it valid?
1687
-		if (!$this->Net_IPv6->checkIPv6($address)) 							{ $this->Result->show("danger", _("IP address not valid")."! ($address)", $die); return true; }
1688
-		# it must be in provided subnet
1689
-		elseif (!$this->Net_IPv6->isInNetmask($address, $subnet)) 			{ $this->Result->show("danger", _("IP address not in selected subnet")."! ($address)", $die); return true; }
1690
-		# default
1691
-		return false;
1692
-	}
1693
-
1694
-	/**
1695
-	 * Validates IP address
1696
-	 *
1697
-	 * @access public
1698
-	 * @param mixed $address
1699
-	 * @return void
1700
-	 */
1701
-	public function validate_address ($address) {
1702
-		# Initialize PEAR NET object
1703
-		$this->initialize_pear_net_IPv4 ();
1704
-		$this->initialize_pear_net_IPv6 ();
1705
-
1706
-		// no null
1707
-		if($this->transform_address ($address, "decimal")==0) {
1708
-			return false;
1709
-		}
1710
-		// transform
1711
-		$address = $this->transform_address ($address, "dotted");
1712
-		// ipv6
1713
-		if($this->identify_address ($address)=="IPv6") {
1714
-			return $this->Net_IPv6->checkIPv6($address) ?  true : false;
1715
-		}
1716
-		// ipv4
1717
-		else {
1718
-			return $this->Net_IPv4->validateIP($address) ? true : false;
1719
-		}
1720
-	}
1721
-
1722
-	/**
1723
-	 * Checks if address is subnet for IPv4 addresses
1724
-	 *
1725
-	 * @access public
1726
-	 * @param mixed $address
1727
-	 * @param int $netmask
1728
-	 * @return boolean
1729
-	 */
1730
-	public function is_network ($address, $netmask) {
1731
-		$this->initialize_subnets_object ();
1732
-		$boundaries = $this->Subnets->get_network_boundaries ($address, $netmask);
1733
-		return $this->transform_address($address,"dotted")==$boundaries['network'] ? true : false;
1734
-	}
1735
-
1736
-	/**
1737
-	 * Checks if address is broadcast for IPv4 addresses
1738
-	 *
1739
-	 * @access public
1740
-	 * @param mixed $address
1741
-	 * @param int $netmask
1742
-	 * @return boolean
1743
-	 */
1744
-	public function is_broadcast ($address, $netmask) {
1745
-		$this->initialize_subnets_object ();
1746
-		$boundaries = $this->Subnets->get_network_boundaries ($address, $netmask);
1747
-		return $this->transform_address($address,"dotted")==$boundaries['broadcast'] ? true : false;
1748
-	}
1749
-
1750
-	/**
1751
-	 * Checks if hostname in database is unique
1752
-	 *
1753
-	 * @access public
1754
-	 * @param mixed $hostname
1755
-	 * @return boolean
1756
-	 */
1757
-	public function is_hostname_unique ($hostname) {
1758
-		try { $cnt = $this->Database->numObjectsFilter("ipaddresses", "hostname", $hostname); }
1759
-		catch (Exception $e) {
1760
-			$this->Result->show("danger", _("Error: ").$e->getMessage());
1761
-			return false;
1762
-		}
1763
-		return $cnt==0 ? true : false;
1764
-	}
1765
-
1766
-
1767
-
1768
-
1769
-
1770
-
1771
-
1772
-
1773
-
1774
-
1775
-
1776
-
1777
-
1778
-	/**
1779
-	* @transform address methods
1780
-	* -------------------------------
1781
-	*/
1782
-
1783
-	/**
1784
-	 * This function compresses all ranges
1785
-	 *
1786
-	 *	input is array of ip addresses
1787
-	 *	output compresses address range
1788
-	 *
1789
-	 * @access public
1790
-	 * @param array $addresses
1791
-	 * @return void
1792
-	 */
1793
-	public function compress_address_ranges ($addresses, $state=4) {
1794
-    	# set size
1795
-    	$size = sizeof($addresses);
1796
-    	// vars
1797
-    	$addresses_formatted = array();
1798
-
1799
-		# loop through IP addresses
1800
-		for($c=0; $c<$size; $c++) {
1801
-			# ignore already comressed range
1802
-			if($addresses[$c]->class!="compressed-range") {
1803
-				# gap between this and previous
1804
-				if(gmp_strval( @gmp_sub($addresses[$c]->ip_addr, $addresses[$c-1]->ip_addr)) != 1) {
1805
-					# remove index flag
1806
-					unset($fIndex);
1807
-					# save IP address
1808
-					$addresses_formatted[$c] = $addresses[$c];
1809
-					$addresses_formatted[$c]->class = "ip";
1810
-
1811
-					# no gap this -> next
1812
-					if(gmp_strval( @gmp_sub($addresses[$c]->ip_addr, $addresses[$c+1]->ip_addr)) == -1 && $addresses[$c]->state==$state) {
1813
-						//is state the same?
1814
-						if($addresses[$c]->state==$addresses[$c+1]->state) {
1815
-							$fIndex = $c;
1816
-							$addresses_formatted[$fIndex]->startIP = $addresses[$c]->ip_addr;
1817
-							$addresses_formatted[$c]->class = "compressed-range";
1818
-						}
1819
-					}
1820
-				}
1821
-				# no gap between this and previous
1822
-				else {
1823
-					# is state same as previous?
1824
-					if($addresses[$c]->state==$addresses[$c-1]->state && $addresses[$c]->state==$state) {
1825
-						$addresses_formatted[$fIndex]->stopIP = $addresses[$c]->ip_addr;	//adds dhcp state
1826
-						$addresses_formatted[$fIndex]->numHosts = gmp_strval( gmp_add(@gmp_sub($addresses[$c]->ip_addr, $addresses_formatted[$fIndex]->ip_addr),1));	//add number of hosts
1827
-					}
1828
-					# different state
1829
-					else {
1830
-						# remove index flag
1831
-						unset($fIndex);
1832
-						# save IP address
1833
-						$addresses_formatted[$c] = $addresses[$c];
1834
-						$addresses_formatted[$c]->class = "ip";
1835
-						# check if state is same as next to start range
1836
-						if($addresses[$c]->state==@$addresses[$c+1]->state &&  gmp_strval( @gmp_sub($addresses[$c]->ip_addr, $addresses[$c+1]->ip_addr)) == -1 && $addresses[$c]->state==$state) {
1837
-							$fIndex = $c;
1838
-							$addresses_formatted[$fIndex]->startIP = $addresses[$c]->ip_addr;
1839
-							$addresses_formatted[$c]->class = "compressed-range";
1840
-						}
1841
-					}
1842
-				}
1843
-			}
1844
-			else {
1845
-				# save already compressed
1846
-				$addresses_formatted[$c] = $addresses[$c];
1847
-			}
1848
-		}
1849
-		# overrwrite ipaddresses and rekey
1850
-		$addresses = @array_values($addresses_formatted);
1851
-		# return
1852
-		return $addresses;
1853
-	}
1854
-
1855
-	/**
1856
-	 * Finds invalid addresses - that have subnetId that does not exist
1857
-	 *
1858
-	 * @access public
1859
-	 * @return void
1860
-	 */
1861
-	public function find_invalid_addresses () {
1862
-    	// init
1863
-    	$false = array();
1864
-		// find unique ids
1865
-		$ids = $this->find_unique_subnetids ();
1866
-		if ($ids===false)										{ return false; }
1867
-
1868
-		// validate
1869
-		foreach ($ids as $id) {
1870
-			if ($this->verify_subnet_id ($id->subnetId)===false) {
1871
-				$false[] = $this->fetch_subnet_addresses ($id->subnetId);
1872
-			}
1873
-		}
1874
-		// filter
1875
-		$false = array_filter($false);
1876
-		// return
1877
-		return sizeof($false)>0 ? $false : false;
1878
-	}
1879
-
1880
-	/**
1881
-	 * Finds all unique master subnet ids
1882
-	 *
1883
-	 * @access private
1884
-	 * @return void
1885
-	 */
1886
-	private function find_unique_subnetids () {
1887
-		try { $res = $this->Database->getObjectsQuery("select distinct(`subnetId`) from `ipaddresses` order by `subnetId` asc;"); }
1888
-		catch (Exception $e) {
1889
-			$this->Result->show("danger", _("Error: ").$e->getMessage());
1890
-			return false;
1891
-		}
1892
-		# return
1893
-		return sizeof($res)>0 ? $res : false;
1894
-	}
1895
-
1896
-	/**
1897
-	 * Verifies that subnetid exists
1898
-	 *
1899
-	 * @access private
1900
-	 * @param mixed $id
1901
-	 * @return void
1902
-	 */
1903
-	private function verify_subnet_id ($id) {
1904
-		try { $res = $this->Database->numObjectsFilter("subnets", "id", $id ); }
1905
-		catch (Exception $e) {
1906
-			$this->Result->show("danger", _("Error: ").$e->getMessage());
1907
-			return false;
1908
-		}
1909
-		# return
1910
-		return $res==0 ? false : true;
1911
-	}
1912
-
1913
-
1914
-
1915
-
1916
-
1917
-
1918
-
1919
-
1920
-
1921
-
1922
-
1923
-	/**
1924
-	* @permission address methods
1925
-	* -------------------------------
1926
-	*/
1927
-
1928
-	/**
1929
-	 * Checks permission for specified subnet
1930
-	 *
1931
-	 *	we provide user details and subnetId
1932
-	 *
1933
-	 * @access public
1934
-	 * @param object $user
1935
-	 * @param int $subnetId
1936
-	 * @return int permission level
1937
-	 */
1938
-	public function check_permission ($user, $subnetId) {
1939
-
1940
-		# get all user groups
1941
-		$groups = json_decode($user->groups);
1942
-
1943
-		# if user is admin then return 3, otherwise check
1944
-		if($user->role == "Administrator")	{ return 3; }
1945
-
1946
-    	# object
1947
-    	if (!is_object($this->Subnets)) {
1948
-        	$this->Subnets = new Subnets ($this->Database);
1949
-    	}
1950
-        # fetch subnet
1951
-        $subnet = $this->Subnets->fetch_subnet("id", $subnetId);
1952
-		# set subnet permissions
1953
-		$subnetP = json_decode($subnet->permissions);
1668
+        }
1669
+        # default
1670
+        return false;
1671
+    }
1672
+
1673
+    /**
1674
+     * Verify IPv6 address
1675
+     *
1676
+     * @access public
1677
+     * @param int $address
1678
+     * @param mixed $subnet (CIDR)
1679
+     * @param bool $die
1680
+     * @return boolean
1681
+     */
1682
+    public function verify_address_IPv6 ($address, $subnet, $die) {
1683
+        # Initialize PEAR NET object
1684
+        $this->initialize_pear_net_IPv6 ();
1685
+
1686
+        # is it valid?
1687
+        if (!$this->Net_IPv6->checkIPv6($address)) 							{ $this->Result->show("danger", _("IP address not valid")."! ($address)", $die); return true; }
1688
+        # it must be in provided subnet
1689
+        elseif (!$this->Net_IPv6->isInNetmask($address, $subnet)) 			{ $this->Result->show("danger", _("IP address not in selected subnet")."! ($address)", $die); return true; }
1690
+        # default
1691
+        return false;
1692
+    }
1693
+
1694
+    /**
1695
+     * Validates IP address
1696
+     *
1697
+     * @access public
1698
+     * @param mixed $address
1699
+     * @return void
1700
+     */
1701
+    public function validate_address ($address) {
1702
+        # Initialize PEAR NET object
1703
+        $this->initialize_pear_net_IPv4 ();
1704
+        $this->initialize_pear_net_IPv6 ();
1705
+
1706
+        // no null
1707
+        if($this->transform_address ($address, "decimal")==0) {
1708
+            return false;
1709
+        }
1710
+        // transform
1711
+        $address = $this->transform_address ($address, "dotted");
1712
+        // ipv6
1713
+        if($this->identify_address ($address)=="IPv6") {
1714
+            return $this->Net_IPv6->checkIPv6($address) ?  true : false;
1715
+        }
1716
+        // ipv4
1717
+        else {
1718
+            return $this->Net_IPv4->validateIP($address) ? true : false;
1719
+        }
1720
+    }
1721
+
1722
+    /**
1723
+     * Checks if address is subnet for IPv4 addresses
1724
+     *
1725
+     * @access public
1726
+     * @param mixed $address
1727
+     * @param int $netmask
1728
+     * @return boolean
1729
+     */
1730
+    public function is_network ($address, $netmask) {
1731
+        $this->initialize_subnets_object ();
1732
+        $boundaries = $this->Subnets->get_network_boundaries ($address, $netmask);
1733
+        return $this->transform_address($address,"dotted")==$boundaries['network'] ? true : false;
1734
+    }
1735
+
1736
+    /**
1737
+     * Checks if address is broadcast for IPv4 addresses
1738
+     *
1739
+     * @access public
1740
+     * @param mixed $address
1741
+     * @param int $netmask
1742
+     * @return boolean
1743
+     */
1744
+    public function is_broadcast ($address, $netmask) {
1745
+        $this->initialize_subnets_object ();
1746
+        $boundaries = $this->Subnets->get_network_boundaries ($address, $netmask);
1747
+        return $this->transform_address($address,"dotted")==$boundaries['broadcast'] ? true : false;
1748
+    }
1749
+
1750
+    /**
1751
+     * Checks if hostname in database is unique
1752
+     *
1753
+     * @access public
1754
+     * @param mixed $hostname
1755
+     * @return boolean
1756
+     */
1757
+    public function is_hostname_unique ($hostname) {
1758
+        try { $cnt = $this->Database->numObjectsFilter("ipaddresses", "hostname", $hostname); }
1759
+        catch (Exception $e) {
1760
+            $this->Result->show("danger", _("Error: ").$e->getMessage());
1761
+            return false;
1762
+        }
1763
+        return $cnt==0 ? true : false;
1764
+    }
1765
+
1766
+
1767
+
1768
+
1769
+
1770
+
1771
+
1772
+
1773
+
1774
+
1775
+
1776
+
1777
+
1778
+    /**
1779
+     * @transform address methods
1780
+     * -------------------------------
1781
+     */
1782
+
1783
+    /**
1784
+     * This function compresses all ranges
1785
+     *
1786
+     *	input is array of ip addresses
1787
+     *	output compresses address range
1788
+     *
1789
+     * @access public
1790
+     * @param array $addresses
1791
+     * @return void
1792
+     */
1793
+    public function compress_address_ranges ($addresses, $state=4) {
1794
+        # set size
1795
+        $size = sizeof($addresses);
1796
+        // vars
1797
+        $addresses_formatted = array();
1798
+
1799
+        # loop through IP addresses
1800
+        for($c=0; $c<$size; $c++) {
1801
+            # ignore already comressed range
1802
+            if($addresses[$c]->class!="compressed-range") {
1803
+                # gap between this and previous
1804
+                if(gmp_strval( @gmp_sub($addresses[$c]->ip_addr, $addresses[$c-1]->ip_addr)) != 1) {
1805
+                    # remove index flag
1806
+                    unset($fIndex);
1807
+                    # save IP address
1808
+                    $addresses_formatted[$c] = $addresses[$c];
1809
+                    $addresses_formatted[$c]->class = "ip";
1810
+
1811
+                    # no gap this -> next
1812
+                    if(gmp_strval( @gmp_sub($addresses[$c]->ip_addr, $addresses[$c+1]->ip_addr)) == -1 && $addresses[$c]->state==$state) {
1813
+                        //is state the same?
1814
+                        if($addresses[$c]->state==$addresses[$c+1]->state) {
1815
+                            $fIndex = $c;
1816
+                            $addresses_formatted[$fIndex]->startIP = $addresses[$c]->ip_addr;
1817
+                            $addresses_formatted[$c]->class = "compressed-range";
1818
+                        }
1819
+                    }
1820
+                }
1821
+                # no gap between this and previous
1822
+                else {
1823
+                    # is state same as previous?
1824
+                    if($addresses[$c]->state==$addresses[$c-1]->state && $addresses[$c]->state==$state) {
1825
+                        $addresses_formatted[$fIndex]->stopIP = $addresses[$c]->ip_addr;	//adds dhcp state
1826
+                        $addresses_formatted[$fIndex]->numHosts = gmp_strval( gmp_add(@gmp_sub($addresses[$c]->ip_addr, $addresses_formatted[$fIndex]->ip_addr),1));	//add number of hosts
1827
+                    }
1828
+                    # different state
1829
+                    else {
1830
+                        # remove index flag
1831
+                        unset($fIndex);
1832
+                        # save IP address
1833
+                        $addresses_formatted[$c] = $addresses[$c];
1834
+                        $addresses_formatted[$c]->class = "ip";
1835
+                        # check if state is same as next to start range
1836
+                        if($addresses[$c]->state==@$addresses[$c+1]->state &&  gmp_strval( @gmp_sub($addresses[$c]->ip_addr, $addresses[$c+1]->ip_addr)) == -1 && $addresses[$c]->state==$state) {
1837
+                            $fIndex = $c;
1838
+                            $addresses_formatted[$fIndex]->startIP = $addresses[$c]->ip_addr;
1839
+                            $addresses_formatted[$c]->class = "compressed-range";
1840
+                        }
1841
+                    }
1842
+                }
1843
+            }
1844
+            else {
1845
+                # save already compressed
1846
+                $addresses_formatted[$c] = $addresses[$c];
1847
+            }
1848
+        }
1849
+        # overrwrite ipaddresses and rekey
1850
+        $addresses = @array_values($addresses_formatted);
1851
+        # return
1852
+        return $addresses;
1853
+    }
1854
+
1855
+    /**
1856
+     * Finds invalid addresses - that have subnetId that does not exist
1857
+     *
1858
+     * @access public
1859
+     * @return void
1860
+     */
1861
+    public function find_invalid_addresses () {
1862
+        // init
1863
+        $false = array();
1864
+        // find unique ids
1865
+        $ids = $this->find_unique_subnetids ();
1866
+        if ($ids===false)										{ return false; }
1867
+
1868
+        // validate
1869
+        foreach ($ids as $id) {
1870
+            if ($this->verify_subnet_id ($id->subnetId)===false) {
1871
+                $false[] = $this->fetch_subnet_addresses ($id->subnetId);
1872
+            }
1873
+        }
1874
+        // filter
1875
+        $false = array_filter($false);
1876
+        // return
1877
+        return sizeof($false)>0 ? $false : false;
1878
+    }
1879
+
1880
+    /**
1881
+     * Finds all unique master subnet ids
1882
+     *
1883
+     * @access private
1884
+     * @return void
1885
+     */
1886
+    private function find_unique_subnetids () {
1887
+        try { $res = $this->Database->getObjectsQuery("select distinct(`subnetId`) from `ipaddresses` order by `subnetId` asc;"); }
1888
+        catch (Exception $e) {
1889
+            $this->Result->show("danger", _("Error: ").$e->getMessage());
1890
+            return false;
1891
+        }
1892
+        # return
1893
+        return sizeof($res)>0 ? $res : false;
1894
+    }
1895
+
1896
+    /**
1897
+     * Verifies that subnetid exists
1898
+     *
1899
+     * @access private
1900
+     * @param mixed $id
1901
+     * @return void
1902
+     */
1903
+    private function verify_subnet_id ($id) {
1904
+        try { $res = $this->Database->numObjectsFilter("subnets", "id", $id ); }
1905
+        catch (Exception $e) {
1906
+            $this->Result->show("danger", _("Error: ").$e->getMessage());
1907
+            return false;
1908
+        }
1909
+        # return
1910
+        return $res==0 ? false : true;
1911
+    }
1912
+
1913
+
1914
+
1915
+
1916
+
1917
+
1918
+
1954 1919
 
1955
-		# set section permissions
1956
-		$Section = new Section ($this->Database);
1957
-		$section = $Section->fetch_section ("id", $subnet->sectionId);
1958
-		$sectionP = json_decode($section->permissions);
1959 1920
 
1960
-		# default permission
1961
-		$out = 0;
1962 1921
 
1963
-		# for each group check permissions, save highest to $out
1964
-		if(sizeof($sectionP) > 0) {
1965
-			foreach($sectionP as $sk=>$sp) {
1966
-				# check each group if user is in it and if so check for permissions for that group
1967
-				foreach($groups as $uk=>$up) {
1968
-					if($uk == $sk) {
1969
-						if($sp > $out) { $out = $sp; }
1970
-					}
1971
-				}
1972
-			}
1973
-		}
1974
-		else {
1975
-			return 0;
1976
-		}
1977 1922
 
1978
-		# if section permission == 0 then return 0
1979
-		if($out == 0) {
1980
-			return 0;
1981
-		}
1982
-		else {
1983
-			$out = 0;
1984
-			# ok, user has section access, check also for any higher access from subnet
1985
-			if(sizeof($subnetP) > 0) {
1986
-				foreach($subnetP as $sk=>$sp) {
1987
-					# check each group if user is in it and if so check for permissions for that group
1988
-					foreach($groups as $uk=>$up) {
1989
-						if($uk == $sk) {
1990
-							if($sp > $out) { $out = $sp; }
1991
-						}
1992
-					}
1993
-				}
1994
-			}
1995
-		}
1923
+    /**
1924
+     * @permission address methods
1925
+     * -------------------------------
1926
+     */
1927
+
1928
+    /**
1929
+     * Checks permission for specified subnet
1930
+     *
1931
+     *	we provide user details and subnetId
1932
+     *
1933
+     * @access public
1934
+     * @param object $user
1935
+     * @param int $subnetId
1936
+     * @return int permission level
1937
+     */
1938
+    public function check_permission ($user, $subnetId) {
1939
+
1940
+        # get all user groups
1941
+        $groups = json_decode($user->groups);
1942
+
1943
+        # if user is admin then return 3, otherwise check
1944
+        if($user->role == "Administrator")	{ return 3; }
1945
+
1946
+        # object
1947
+        if (!is_object($this->Subnets)) {
1948
+            $this->Subnets = new Subnets ($this->Database);
1949
+        }
1950
+        # fetch subnet
1951
+        $subnet = $this->Subnets->fetch_subnet("id", $subnetId);
1952
+        # set subnet permissions
1953
+        $subnetP = json_decode($subnet->permissions);
1954
+
1955
+        # set section permissions
1956
+        $Section = new Section ($this->Database);
1957
+        $section = $Section->fetch_section ("id", $subnet->sectionId);
1958
+        $sectionP = json_decode($section->permissions);
1959
+
1960
+        # default permission
1961
+        $out = 0;
1962
+
1963
+        # for each group check permissions, save highest to $out
1964
+        if(sizeof($sectionP) > 0) {
1965
+            foreach($sectionP as $sk=>$sp) {
1966
+                # check each group if user is in it and if so check for permissions for that group
1967
+                foreach($groups as $uk=>$up) {
1968
+                    if($uk == $sk) {
1969
+                        if($sp > $out) { $out = $sp; }
1970
+                    }
1971
+                }
1972
+            }
1973
+        }
1974
+        else {
1975
+            return 0;
1976
+        }
1977
+
1978
+        # if section permission == 0 then return 0
1979
+        if($out == 0) {
1980
+            return 0;
1981
+        }
1982
+        else {
1983
+            $out = 0;
1984
+            # ok, user has section access, check also for any higher access from subnet
1985
+            if(sizeof($subnetP) > 0) {
1986
+                foreach($subnetP as $sk=>$sp) {
1987
+                    # check each group if user is in it and if so check for permissions for that group
1988
+                    foreach($groups as $uk=>$up) {
1989
+                        if($uk == $sk) {
1990
+                            if($sp > $out) { $out = $sp; }
1991
+                        }
1992
+                    }
1993
+                }
1994
+            }
1995
+        }
1996 1996
 
1997
-		# return result
1998
-		return $out;
1999
-	}
1997
+        # return result
1998
+        return $out;
1999
+    }
2000 2000
 
2001 2001
 
2002 2002
 
@@ -2007,27 +2007,27 @@  discard block
 block discarded – undo
2007 2007
 
2008 2008
 
2009 2009
 
2010
-	/**
2011
-	* @misc address methods
2012
-	* -------------------------------
2013
-	*/
2010
+    /**
2011
+     * @misc address methods
2012
+     * -------------------------------
2013
+     */
2014 2014
 
2015
-	/**
2016
-	 * Present numbers in pow 10, only for IPv6
2017
-	 *
2018
-	 * @access public
2019
-	 * @param mixed $number
2020
-	 * @return void
2021
-	 */
2022
-	public function reformat_number ($number) {
2023
-		$length = strlen($number);
2024
-		$pos	= $length - 3;
2015
+    /**
2016
+     * Present numbers in pow 10, only for IPv6
2017
+     *
2018
+     * @access public
2019
+     * @param mixed $number
2020
+     * @return void
2021
+     */
2022
+    public function reformat_number ($number) {
2023
+        $length = strlen($number);
2024
+        $pos	= $length - 3;
2025 2025
 
2026
-		if ($length > 8) {
2027
-			$number = "~". substr($number, 0, $length - $pos) . "&middot;10^<sup>". $pos ."</sup>";
2028
-		}
2029
-		return $number;
2030
-	}
2026
+        if ($length > 8) {
2027
+            $number = "~". substr($number, 0, $length - $pos) . "&middot;10^<sup>". $pos ."</sup>";
2028
+        }
2029
+        return $number;
2030
+    }
2031 2031
 
2032 2032
 
2033 2033
 
@@ -2038,33 +2038,33 @@  discard block
 block discarded – undo
2038 2038
 
2039 2039
 
2040 2040
 
2041
-	/**
2042
-	* @nat methods
2043
-	* -------------------------------
2044
-	*/
2045
-	/**
2046
-	 * Prints nat link
2047
-	 *
2048
-	 * @access public
2049
-	 * @param array $all_nats
2050
-	 * @param array $all_nats_per_object
2051
-	 * @param object $subnet
2052
-	 * @param object $address
2053
-	 * @param mixed $address
2054
-	 * @return void
2055
-	 */
2056
-	public function print_nat_link ($all_nats, $all_nats_per_object, $subnet, $address, $type="ipaddress") {
2057
-    	// cast
2058
-    	$subnet = (object) $subnet;
2059
-    	$address = (object) $address;
2041
+    /**
2042
+     * @nat methods
2043
+     * -------------------------------
2044
+     */
2045
+    /**
2046
+     * Prints nat link
2047
+     *
2048
+     * @access public
2049
+     * @param array $all_nats
2050
+     * @param array $all_nats_per_object
2051
+     * @param object $subnet
2052
+     * @param object $address
2053
+     * @param mixed $address
2054
+     * @return void
2055
+     */
2056
+    public function print_nat_link ($all_nats, $all_nats_per_object, $subnet, $address, $type="ipaddress") {
2057
+        // cast
2058
+        $subnet = (object) $subnet;
2059
+        $address = (object) $address;
2060 2060
 
2061
-    	// cnt
2062
-    	$html = array();
2063
-    	$html[] = '<table class="popover_table">';
2061
+        // cnt
2062
+        $html = array();
2063
+        $html[] = '<table class="popover_table">';
2064 2064
 
2065
-    	$cnt = 0;
2065
+        $cnt = 0;
2066 2066
 
2067
-    	// subnets
2067
+        // subnets
2068 2068
         if(isset($all_nats_per_object['subnets'][$subnet->id])) {
2069 2069
             foreach ($all_nats_per_object['subnets'][$subnet->id] as $nat) {
2070 2070
                 // set object
@@ -2075,8 +2075,8 @@  discard block
 block discarded – undo
2075 2075
             $cnt++;
2076 2076
         }
2077 2077
 
2078
-    	// addresses
2079
-    	if(isset($all_nats_per_object['ipaddresses'][$address->id])) {
2078
+        // addresses
2079
+        if(isset($all_nats_per_object['ipaddresses'][$address->id])) {
2080 2080
             foreach ($all_nats_per_object['ipaddresses'][$address->id] as $nat) {
2081 2081
                 // set object
2082 2082
                 $n = $all_nats[$nat];
@@ -2084,7 +2084,7 @@  discard block
 block discarded – undo
2084 2084
                 $html[] = str_replace("'", "\"", $this->print_nat_link_line ($n, false, "ipaddresses", $address->id));
2085 2085
                 $cnt++;
2086 2086
             }
2087
-    	}
2087
+        }
2088 2088
 
2089 2089
         // print if some
2090 2090
         if ($cnt>0) {
@@ -2096,7 +2096,7 @@  discard block
 block discarded – undo
2096 2096
                 print  " <a href='".create_link("subnets",$subnet->sectionId, $subnet->id, "address-details", $address->id, "nat")."' class='btn btn-xs btn-default show_popover fa fa-exchange' style='font-size:11px;margin-top:-3px;padding:1px 3px;' data-toggle='popover' title='"._('Object is Natted')."' data-trigger='hover' data-html='true' data-content='".implode("\n", $html)."'></a>";
2097 2097
             }
2098 2098
         }
2099
-	}
2099
+    }
2100 2100
 
2101 2101
     /**
2102 2102
      * Prints single NAT for display in devices, subnets, addresses.
Please login to merge, or discard this patch.
Spacing   +378 added lines, -378 removed lines patch added patch discarded remove patch
@@ -111,16 +111,16 @@  discard block
 block discarded – undo
111 111
 	 *
112 112
 	 * @access public
113 113
 	 */
114
-	public function __construct (Database_PDO $Database) {
114
+	public function __construct(Database_PDO $Database) {
115 115
 		# Save database object
116 116
 		$this->Database = $Database;
117 117
 		# initialize Result
118
-		$this->Result = new Result ();
118
+		$this->Result = new Result();
119 119
 		# debugging
120 120
 		$this->set_debugging();
121 121
 
122 122
 		# Log object
123
-		$this->Log = new Logging ($this->Database);
123
+		$this->Log = new Logging($this->Database);
124 124
 	}
125 125
 
126 126
 
@@ -142,13 +142,13 @@  discard block
 block discarded – undo
142 142
 	 * @access public
143 143
 	 * @return array of address types and parameters
144 144
 	 */
145
-	public function addresses_types_fetch () {
145
+	public function addresses_types_fetch() {
146 146
     	# fetch
147
-    	$types = $this->fetch_all_objects ("ipTags", "id");
147
+    	$types = $this->fetch_all_objects("ipTags", "id");
148 148
 
149 149
 		# save to array
150 150
 		$types_out = array();
151
-		foreach($types as $t) {
151
+		foreach ($types as $t) {
152 152
 			$types_out[$t->id] = (array) $t;
153 153
 		}
154 154
 		# save
@@ -164,15 +164,15 @@  discard block
 block discarded – undo
164 164
 	 * @param int $state
165 165
 	 * @return mixed tag
166 166
 	 */
167
-	public function address_type_format_tag ($state) {
167
+	public function address_type_format_tag($state) {
168 168
 		# fetch address states
169 169
 		$this->addresses_types_fetch();
170 170
 		# result
171
-		if(!isset($this->address_types[$state]))	{
171
+		if (!isset($this->address_types[$state])) {
172 172
 			return "";
173 173
 		}
174 174
 		else {
175
-			if($this->address_types[$state]['showtag']==1) {
175
+			if ($this->address_types[$state]['showtag'] == 1) {
176 176
 				return "<i class='fa fa-".$this->address_types[$state]['type']." fa-tag state' rel='tooltip' style='color:".$this->address_types[$state]['bgcolor']."' title='"._($this->address_types[$state]['type'])."'></i>";
177 177
 			}
178 178
 		}
@@ -187,11 +187,11 @@  discard block
 block discarded – undo
187 187
 	 * @param int $index
188 188
 	 * @return mixed address type
189 189
 	 */
190
-	public function address_type_index_to_type ($index) {
190
+	public function address_type_index_to_type($index) {
191 191
 		# fetch address states
192 192
 		$this->addresses_types_fetch();
193 193
 		# return
194
-		if(isset($this->address_types[$index])) {
194
+		if (isset($this->address_types[$index])) {
195 195
 			return $this->address_types[$index]['type'];
196 196
 		}
197 197
 		else {
@@ -208,18 +208,18 @@  discard block
 block discarded – undo
208 208
 	 * @param mixed $type
209 209
 	 * @return void
210 210
 	 */
211
-	public function address_type_type_to_index ($type = "Used") {
211
+	public function address_type_type_to_index($type = "Used") {
212 212
 		# null of no length
213
-		$type = strlen($type)==0 || is_null($type) ? "Used" : $type;
213
+		$type = strlen($type) == 0 || is_null($type) ? "Used" : $type;
214 214
 		# fetch address states
215 215
 		$this->addresses_types_fetch();
216 216
 		# reindex
217 217
 		$states_assoc = array();
218
-		foreach($this->address_types as $s) {
218
+		foreach ($this->address_types as $s) {
219 219
 			$states_assoc[$s['type']] = $s;
220 220
 		}
221 221
 		# return
222
-		if(isset($states_assoc[$type])) {
222
+		if (isset($states_assoc[$type])) {
223 223
 			return $states_assoc[$type]['id'];
224 224
 		}
225 225
 		else {
@@ -251,11 +251,11 @@  discard block
 block discarded – undo
251 251
 	 * @param mixed $id
252 252
 	 * @return object address
253 253
 	 */
254
-	public function fetch_address ($method, $id) {
254
+	public function fetch_address($method, $id) {
255 255
 		# null method
256 256
 		$method = is_null($method) ? "id" : $method;
257 257
 		# check cache first
258
-		if(isset($this->addresses[$id]))	{
258
+		if (isset($this->addresses[$id])) {
259 259
 			return $this->addresses[$id];
260 260
 		}
261 261
 		else {
@@ -265,9 +265,9 @@  discard block
 block discarded – undo
265 265
 				return false;
266 266
 			}
267 267
 			# save to addresses cache
268
-			if(!is_null($address)) {
268
+			if (!is_null($address)) {
269 269
 				# add decimal format
270
-				$address->ip = $this->transform_to_dotted ($address->ip_addr);
270
+				$address->ip = $this->transform_to_dotted($address->ip_addr);
271 271
 				# save to subnets
272 272
 				$this->addresses[$id] = (object) $address;
273 273
 			}
@@ -284,16 +284,16 @@  discard block
 block discarded – undo
284 284
 	 * @param mixed $subnetId
285 285
 	 * @return void
286 286
 	 */
287
-	public function fetch_address_multiple_criteria ($ip_addr, $subnetId) {
287
+	public function fetch_address_multiple_criteria($ip_addr, $subnetId) {
288 288
 		try { $address = $this->Database->getObjectQuery("SELECT * FROM `ipaddresses` where `ip_addr` = ? and `subnetId` = ? limit 1;", array($ip_addr, $subnetId)); }
289 289
 		catch (Exception $e) {
290 290
 			$this->Result->show("danger", _("Error: ").$e->getMessage());
291 291
 			return false;
292 292
 		}
293 293
 		# save to addresses cache
294
-		if(sizeof($address)>0) {
294
+		if (sizeof($address) > 0) {
295 295
 			# add decimal format
296
-			$address->ip = $this->transform_to_dotted ($address->ip_addr);
296
+			$address->ip = $this->transform_to_dotted($address->ip_addr);
297 297
 			# save to subnets
298 298
 			$this->addresses[$address->id] = (object) $address;
299 299
 		}
@@ -310,9 +310,9 @@  discard block
 block discarded – undo
310 310
 	 * @param mixed $address_id
311 311
 	 * @return void
312 312
 	 */
313
-	public function search_similar_addresses ($linked_field, $value, $address_id) {
313
+	public function search_similar_addresses($linked_field, $value, $address_id) {
314 314
     	// checks
315
-    	if(strlen($linked_field)>0 && strlen($value)>0 && is_numeric($address_id)) {
315
+    	if (strlen($linked_field) > 0 && strlen($value) > 0 && is_numeric($address_id)) {
316 316
         	// search
317 317
      		try { $addresses = $this->Database->getObjectsQuery("SELECT * FROM `ipaddresses` where `$linked_field` = ? and `id` != ? and state != 4;", array($value, $address_id)); }
318 318
     		catch (Exception $e) {
@@ -320,7 +320,7 @@  discard block
 block discarded – undo
320 320
     			return false;
321 321
     		}
322 322
     		#result
323
-    		return sizeof($addresses)>0 ? $addresses : false;
323
+    		return sizeof($addresses) > 0 ? $addresses : false;
324 324
         }
325 325
         else {
326 326
             return false;
@@ -335,19 +335,19 @@  discard block
 block discarded – undo
335 335
 	 * @param bool $mail_changelog (default: true)
336 336
 	 * @return void
337 337
 	 */
338
-	public function modify_address ($address, $mail_changelog = true) {
338
+	public function modify_address($address, $mail_changelog = true) {
339 339
 		# save changelog
340
-		$this->mail_changelog  = $mail_changelog;
340
+		$this->mail_changelog = $mail_changelog;
341 341
 		# null empty values
342
-		$address = $this->reformat_empty_array_fields ($address, null);
342
+		$address = $this->reformat_empty_array_fields($address, null);
343 343
 		# strip tags
344
-		$address = $this->strip_input_tags ($address);
344
+		$address = $this->strip_input_tags($address);
345 345
 		# execute based on action
346
-		if($address['action']=="add")			{ return $this->modify_address_add ($address); }							//create new address
347
-		elseif($address['action']=="edit")		{ return $this->modify_address_edit ($address); }							//modify existing address
348
-		elseif($address['action']=="delete")	{ return $this->modify_address_delete ($address); }							//delete address
349
-		elseif($address['action']=="move")		{ return $this->modify_address_move ($address); }							//move to new subnet
350
-		else									{ return $this->Result->show("danger", _("Invalid action"), true); }
346
+		if ($address['action'] == "add") { return $this->modify_address_add($address); }							//create new address
347
+		elseif ($address['action'] == "edit") { return $this->modify_address_edit($address); }							//modify existing address
348
+		elseif ($address['action'] == "delete") { return $this->modify_address_delete($address); }							//delete address
349
+		elseif ($address['action'] == "move") { return $this->modify_address_move($address); }							//move to new subnet
350
+		else { return $this->Result->show("danger", _("Invalid action"), true); }
351 351
 	}
352 352
 
353 353
 	/**
@@ -357,10 +357,10 @@  discard block
 block discarded – undo
357 357
 	 * @param array $address
358 358
 	 * @return boolean success/failure
359 359
 	 */
360
-	protected function modify_address_add ($address) {
360
+	protected function modify_address_add($address) {
361 361
 		# set insert array
362 362
 		$insert = array(
363
-						"ip_addr"               => $this->transform_address($address['ip_addr'],"decimal"),
363
+						"ip_addr"               => $this->transform_address($address['ip_addr'], "decimal"),
364 364
 						"subnetId"              => $address['subnetId'],
365 365
 						"description"           => @$address['description'],
366 366
 						"hostname"              => @$address['hostname'],
@@ -377,9 +377,9 @@  discard block
 block discarded – undo
377 377
 						"lastSeen"              => @$address['lastSeen']
378 378
 						);
379 379
 		# customer
380
-		if(isset($address['customer_id'])) {
380
+		if (isset($address['customer_id'])) {
381 381
 			if (is_numeric($address['customer_id'])) {
382
-				if ($address['customer_id']!="0") {
382
+				if ($address['customer_id'] != "0") {
383 383
 					$insert['customer_id'] = $address['customer_id'];
384 384
 				}
385 385
 				else {
@@ -395,20 +395,20 @@  discard block
 block discarded – undo
395 395
             $insert['location'] = $address['location_item'];
396 396
         }
397 397
 		# custom fields, append to array
398
-		foreach($this->set_custom_fields() as $c) {
398
+		foreach ($this->set_custom_fields() as $c) {
399 399
 			$insert[$c['name']] = !empty($address[$c['name']]) ? $address[$c['name']] : $c['Default'];
400 400
 		}
401 401
 
402 402
 		# null empty values
403
-		$insert = $this->reformat_empty_array_fields ($insert, null);
403
+		$insert = $this->reformat_empty_array_fields($insert, null);
404 404
 
405 405
 		# remove gateway
406
-		if($address['is_gateway']==1)	{ $this->remove_gateway ($address['subnetId']); }
406
+		if ($address['is_gateway'] == 1) { $this->remove_gateway($address['subnetId']); }
407 407
 
408 408
 		# execute
409 409
 		try { $this->Database->insertObject("ipaddresses", $insert); }
410 410
 		catch (Exception $e) {
411
-			$this->Log->write( "Address create", "Failed to create new address<hr>".$e->getMessage()."<hr>".$this->array_to_log($this->reformat_empty_array_fields ($address, "NULL")), 2);
411
+			$this->Log->write("Address create", "Failed to create new address<hr>".$e->getMessage()."<hr>".$this->array_to_log($this->reformat_empty_array_fields($address, "NULL")), 2);
412 412
 			$this->Result->show("danger", _("Error: ").$e->getMessage(), false);
413 413
 			return false;
414 414
 		}
@@ -417,11 +417,11 @@  discard block
 block discarded – undo
417 417
 
418 418
 		# log and changelog
419 419
 		$address['id'] = $this->lastId;
420
-		$this->Log->write( "Address created", "New address created<hr>".$this->array_to_log($this->reformat_empty_array_fields ($address, "NULL")), 0);
420
+		$this->Log->write("Address created", "New address created<hr>".$this->array_to_log($this->reformat_empty_array_fields($address, "NULL")), 0);
421 421
 		$this->Log->write_changelog('ip_addr', "add", 'success', array(), $address, $this->mail_changelog);
422 422
 
423 423
 		# edit DNS PTR record
424
-		$this->ptr_modify ("add", $insert);
424
+		$this->ptr_modify("add", $insert);
425 425
 
426 426
 		# threshold alert
427 427
 		$this->threshold_check($address);
@@ -437,9 +437,9 @@  discard block
 block discarded – undo
437 437
 	 * @param array $address
438 438
 	 * @return boolean success/failure
439 439
 	 */
440
-	protected function modify_address_edit ($address) {
440
+	protected function modify_address_edit($address) {
441 441
 		# fetch old details for logging
442
-		$address_old = $this->fetch_address (null, $address['id']);
442
+		$address_old = $this->fetch_address(null, $address['id']);
443 443
 		if (isset($address['section'])) $address_old->section = $address['section'];
444 444
 
445 445
 		# set update array
@@ -460,9 +460,9 @@  discard block
 block discarded – undo
460 460
 						"PTRignore"   =>@$address['PTRignore']
461 461
 						);
462 462
  		# customer
463
-		if(isset($address['customer_id'])) {
463
+		if (isset($address['customer_id'])) {
464 464
 			if (is_numeric($address['customer_id'])) {
465
-				if ($address['customer_id']!="0") {
465
+				if ($address['customer_id'] != "0") {
466 466
 					$insert['customer_id'] = $address['customer_id'];
467 467
 				}
468 468
 				else {
@@ -478,12 +478,12 @@  discard block
 block discarded – undo
478 478
             $insert['location'] = $address['location_item'];
479 479
         }
480 480
 		# custom fields, append to array
481
-		foreach($this->set_custom_fields() as $c) {
481
+		foreach ($this->set_custom_fields() as $c) {
482 482
 			$insert[$c['name']] = !empty($address[$c['name']]) ? $address[$c['name']] : $c['Default'];
483 483
 		}
484 484
 
485 485
 		# set primary key for update
486
-		if($address['type']=="series") {
486
+		if ($address['type'] == "series") {
487 487
 			$id1 = "subnetId";
488 488
 			$id2 = "ip_addr";
489 489
 			unset($insert['id']);
@@ -493,12 +493,12 @@  discard block
 block discarded – undo
493 493
 		}
494 494
 
495 495
 		# remove gateway
496
-		if($address['is_gateway']==1)	{ $this->remove_gateway ($address['subnetId']); }
496
+		if ($address['is_gateway'] == 1) { $this->remove_gateway($address['subnetId']); }
497 497
 
498 498
 		# execute
499 499
 		try { $this->Database->updateObject("ipaddresses", $insert, $id1, $id2); }
500 500
 		catch (Exception $e) {
501
-			$this->Log->write( "Address edit", "Failed to edit address $address[ip_addr]<hr>".$e->getMessage()."<hr>".$this->array_to_log($this->reformat_empty_array_fields ($address, "NULL")), 2);
501
+			$this->Log->write("Address edit", "Failed to edit address $address[ip_addr]<hr>".$e->getMessage()."<hr>".$this->array_to_log($this->reformat_empty_array_fields($address, "NULL")), 2);
502 502
 			$this->Result->show("danger", _("Error: ").$e->getMessage(), false);
503 503
 			return false;
504 504
 		}
@@ -507,12 +507,12 @@  discard block
 block discarded – undo
507 507
 		$address['firewallAddressObject'] = $address_old->firewallAddressObject;
508 508
 
509 509
  		# log and changelog
510
-		$this->Log->write( "Address updated", "Address $address[ip_addr] updated<hr>".$this->array_to_log($this->reformat_empty_array_fields ($address, "NULL")), 0);
510
+		$this->Log->write("Address updated", "Address $address[ip_addr] updated<hr>".$this->array_to_log($this->reformat_empty_array_fields($address, "NULL")), 0);
511 511
 		$this->Log->write_changelog('ip_addr', "edit", 'success', (array) $address_old, $address, $this->mail_changelog);
512 512
 
513 513
 		# edit DNS PTR record
514
-		$insert['PTR']=@$address['PTR'];
515
-		$this->ptr_modify ("edit", $insert);
514
+		$insert['PTR'] = @$address['PTR'];
515
+		$this->ptr_modify("edit", $insert);
516 516
 
517 517
 		# ok
518 518
 		return true;
@@ -525,40 +525,40 @@  discard block
 block discarded – undo
525 525
 	 * @param array $address
526 526
 	 * @return boolean success/failure
527 527
 	 */
528
-	protected function modify_address_delete ($address) {
528
+	protected function modify_address_delete($address) {
529 529
 		# fetch old details for logging
530
-		$address_old = $this->fetch_address (null, $address['id']);
530
+		$address_old = $this->fetch_address(null, $address['id']);
531 531
 		if (isset($address['section'])) $address_old->section = $address['section'];
532 532
 
533 533
 		# series?
534
-		if($address['type']=="series") {
535
-			$field  = "subnetId";	$value  = $address['subnetId'];
536
-			$field2 = "ip_addr";	$value2 = $this->transform_address ($address['ip_addr'], "decimal");
534
+		if ($address['type'] == "series") {
535
+			$field  = "subnetId"; $value = $address['subnetId'];
536
+			$field2 = "ip_addr"; $value2 = $this->transform_address($address['ip_addr'], "decimal");
537 537
 		} else {
538
-			$field  = "id";			$value  = $address['id'];
539
-			$field2 = null;			$value2 = null;
538
+			$field  = "id"; $value  = $address['id'];
539
+			$field2 = null; $value2 = null;
540 540
 		}
541 541
 		# execute
542 542
 		try { $this->Database->deleteRow("ipaddresses", $field, $value, $field2, $value2); }
543 543
 		catch (Exception $e) {
544
-			$this->Log->write( "Address delete", "Failed to delete address $address[ip_addr]<hr>".$e->getMessage()."<hr>".$this->array_to_log((array) $address_old), 2);
544
+			$this->Log->write("Address delete", "Failed to delete address $address[ip_addr]<hr>".$e->getMessage()."<hr>".$this->array_to_log((array) $address_old), 2);
545 545
 			$this->Result->show("danger", _("Error: ").$e->getMessage(), false);
546 546
 			return false;
547 547
 		}
548 548
 
549 549
 		# log and changelog
550
-		$this->Log->write( "Address deleted", "Address $address[ip_addr] deleted<hr>".$this->array_to_log((array) $address_old), 0);
550
+		$this->Log->write("Address deleted", "Address $address[ip_addr] deleted<hr>".$this->array_to_log((array) $address_old), 0);
551 551
 		$this->Log->write_changelog('ip_addr', "delete", 'success', (array) $address_old, array(), $this->mail_changelog);
552 552
 
553 553
 		# edit DNS PTR record
554
-		$this->ptr_modify ("delete", $address);
554
+		$this->ptr_modify("delete", $address);
555 555
 
556 556
 		# remove all referenced records
557
-		if(@$address['remove_all_dns_records']=="1") {
558
-    		$this->pdns_remove_ip_and_hostname_records ($address);
557
+		if (@$address['remove_all_dns_records'] == "1") {
558
+    		$this->pdns_remove_ip_and_hostname_records($address);
559 559
         }
560 560
         # remove from NAT
561
-        $this->remove_address_nat_items ($address['id'], true);
561
+        $this->remove_address_nat_items($address['id'], true);
562 562
 		# ok
563 563
 		return true;
564 564
 	}
@@ -570,7 +570,7 @@  discard block
 block discarded – undo
570 570
 	 * @param array $address
571 571
 	 * @return boolean success/failure
572 572
 	 */
573
-	protected function modify_address_move ($address) {
573
+	protected function modify_address_move($address) {
574 574
 		# execute
575 575
 		try { $this->Database->updateObject("ipaddresses", array("subnetId"=>$address['newSubnet'], "id"=>$address['id'])); }
576 576
 		catch (Exception $e) {
@@ -591,28 +591,28 @@  discard block
 block discarded – undo
591 591
 	 *
592 592
 	 * @return int
593 593
 	 */
594
-	public function remove_address_nat_items ($obj_id = 0, $print = true) {
594
+	public function remove_address_nat_items($obj_id = 0, $print = true) {
595 595
 		# set found flag for returns
596 596
 		$found = 0;
597 597
 		# fetch all nats
598
-		try { $all_nats = $this->Database->getObjectsQuery ("select * from `nat` where `src` like :id or `dst` like :id", array ("id"=>'%"'.$obj_id.'"%')); }
598
+		try { $all_nats = $this->Database->getObjectsQuery("select * from `nat` where `src` like :id or `dst` like :id", array("id"=>'%"'.$obj_id.'"%')); }
599 599
 		catch (Exception $e) {
600 600
 			$this->Result->show("danger", _("Error: ").$e->getMessage());
601 601
 			return false;
602 602
 		}
603 603
 		# loop and check for object ids
604
-		if(!empty($all_nats)) {
604
+		if (!empty($all_nats)) {
605 605
 			# init admin object
606
-			$Admin = new Admin ($this->Database, false);
606
+			$Admin = new Admin($this->Database, false);
607 607
 			# loop
608 608
 			foreach ($all_nats as $nat) {
609 609
 			    # remove item from nat
610 610
 			    $s = json_decode($nat->src, true);
611 611
 			    $d = json_decode($nat->dst, true);
612 612
 
613
-			    if(is_array($s['ipaddresses']))
613
+			    if (is_array($s['ipaddresses']))
614 614
 			    $s['ipaddresses'] = array_diff($s['ipaddresses'], array($obj_id));
615
-			    if(is_array($d['ipaddresses']))
615
+			    if (is_array($d['ipaddresses']))
616 616
 			    $d['ipaddresses'] = array_diff($d['ipaddresses'], array($obj_id));
617 617
 
618 618
 			    # save back and update
@@ -620,11 +620,11 @@  discard block
 block discarded – undo
620 620
 			    $dst_new = json_encode(array_filter($d));
621 621
 
622 622
 			    # update only if diff found
623
-			    if($s!=$src_new || $d!=$dst_new) {
623
+			    if ($s != $src_new || $d != $dst_new) {
624 624
 			    	$found++;
625 625
 
626
-				    if($Admin->object_modify ("nat", "edit", "id", array("id"=>$nat->id, "src"=>$src_new, "dst"=>$dst_new))!==false) {
627
-				    	if($print) {
626
+				    if ($Admin->object_modify("nat", "edit", "id", array("id"=>$nat->id, "src"=>$src_new, "dst"=>$dst_new)) !== false) {
627
+				    	if ($print) {
628 628
 					        $this->Result->show("success", "Address removed from NAT", false);
629 629
 						}
630 630
 				    }
@@ -646,15 +646,15 @@  discard block
 block discarded – undo
646 646
 	 *
647 647
 	 * @return void
648 648
 	 */
649
-	public function update_address_hostname ($ip, $id, $hostname = "") {
650
-		if(is_numeric($id) && strlen($hostname)>0) {
649
+	public function update_address_hostname($ip, $id, $hostname = "") {
650
+		if (is_numeric($id) && strlen($hostname) > 0) {
651 651
 			try { $this->Database->updateObject("ipaddresses", array("id"=>$id, "hostname"=>$hostname)); }
652 652
 			catch (Exception $e) {
653 653
 				return false;
654 654
 			}
655 655
 			// save log
656
-			$this->Log->write( "Address DNS resolved", "Address $ip resolved<hr>".$this->array_to_log((array) $hostname), 0);
657
-			$this->Log->write_changelog('ip_addr', "edit", 'success', array ("id"=>$id, "hostname"=>""), array("id"=>$id, "hostname"=>$hostname), $this->mail_changelog);
656
+			$this->Log->write("Address DNS resolved", "Address $ip resolved<hr>".$this->array_to_log((array) $hostname), 0);
657
+			$this->Log->write_changelog('ip_addr', "edit", 'success', array("id"=>$id, "hostname"=>""), array("id"=>$id, "hostname"=>$hostname), $this->mail_changelog);
658 658
 		}
659 659
 	}
660 660
 
@@ -665,62 +665,62 @@  discard block
 block discarded – undo
665 665
 	 * @param mixed $address
666 666
 	 * @return void
667 667
 	 */
668
-	private function threshold_check ($address) {
668
+	private function threshold_check($address) {
669 669
     	$address = (object) $address;
670 670
     	$content = array();
671 671
     	$content_plain = array();
672 672
 
673 673
         # fetch settings
674
-        $this->get_settings ();
674
+        $this->get_settings();
675 675
     	# enabled ?
676
-    	if ($this->settings->enableThreshold=="1") {
676
+    	if ($this->settings->enableThreshold == "1") {
677 677
         	# object
678 678
         	if (!is_object($this->Subnets)) {
679
-            	$this->Subnets = new Subnets ($this->Database);
679
+            	$this->Subnets = new Subnets($this->Database);
680 680
         	}
681 681
         	# fetch subnet
682 682
         	$subnet = $this->Subnets->fetch_subnet("id", $address->subnetId);
683 683
         	# threshold set ?
684
-        	if ($subnet->threshold>0) {
684
+        	if ($subnet->threshold > 0) {
685 685
             	# calculate subnet usage
686
-            	$subnet_usage = $this->Subnets->calculate_subnet_usage ($subnet);
686
+            	$subnet_usage = $this->Subnets->calculate_subnet_usage($subnet);
687 687
             	# if over send mail
688
-            	if (gmp_strval(gmp_sub(100,(int) round($subnet_usage['freehosts_percent'], 0))) > $subnet->threshold) {
688
+            	if (gmp_strval(gmp_sub(100, (int) round($subnet_usage['freehosts_percent'], 0))) > $subnet->threshold) {
689 689
                 	// fetch mail settings
690
-                	$Tools = new Tools ($this->Database);
691
-                	$admins        = $Tools->fetch_multiple_objects ("users", "role", "Administrator");
690
+                	$Tools = new Tools($this->Database);
691
+                	$admins = $Tools->fetch_multiple_objects("users", "role", "Administrator");
692 692
                 	// if some recipients
693 693
                 	if ($admins !== false) {
694 694
 						# try to send
695 695
 						try {
696 696
 	                    	// mail settings
697
-	                        $mail_settings = $Tools->fetch_object ("settingsMail", "id", 1);
697
+	                        $mail_settings = $Tools->fetch_object("settingsMail", "id", 1);
698 698
 	                    	// mail class
699
-	                    	$phpipam_mail = new phpipam_mail ($this->settings, $mail_settings);
699
+	                    	$phpipam_mail = new phpipam_mail($this->settings, $mail_settings);
700 700
 
701 701
 	                        // set parameters
702
-	                        $subject = "Subnet threshold limit reached"." (".$this->transform_address($subnet->subnet,"dotted")."/".$subnet->mask.")";
702
+	                        $subject = "Subnet threshold limit reached"." (".$this->transform_address($subnet->subnet, "dotted")."/".$subnet->mask.")";
703 703
 	                        $content[] = "<table style='margin-left:10px;margin-top:5px;width:auto;padding:0px;border-collapse:collapse;'>";
704 704
 	                        $content[] = "<tr><td style='padding:5px;margin:0px;color:#333;font-size:16px;text-shadow:1px 1px 1px white;border-bottom:1px solid #eeeeee;' colspan='2'>$this->mail_font_style<strong>$subject</font></td></tr>";
705
-	                        $content[] = '<tr><td style="padding: 0px;padding-left:10px;margin:0px;line-height:18px;text-align:left;">'.$this->mail_font_style.''._('Subnet').'</a></font></td>	<td style="padding: 0px;padding-left:15px;margin:0px;line-height:18px;text-align:left;padding-top:10px;"><a href="'.$this->createURL().''.create_link("subnets",$subnet->sectionId, $subnet->id).'">'.$this->mail_font_style_href . $this->transform_address($subnet->subnet,"dotted")."/".$subnet->mask .'</font></a></td></tr>';
706
-	                        $content[] = '<tr><td style="padding: 0px;padding-left:10px;margin:0px;line-height:18px;text-align:left;">'.$this->mail_font_style.''._('Description').'</font></td>	  	<td style="padding: 0px;padding-left:15px;margin:0px;line-height:18px;text-align:left;">'.$this->mail_font_style.''. $subnet->description .'</font></td></tr>';
707
-	                        $content[] = '<tr><td style="padding: 0px;padding-left:10px;margin:0px;line-height:18px;text-align:left;">'.$this->mail_font_style.''._('Usage').' (%)</font></td>	<td style="padding: 0px;padding-left:15px;margin:0px;line-height:18px;text-align:left;">'.$this->mail_font_style.''. gmp_strval(gmp_sub(100,(int) round($subnet_usage['freehosts_percent'], 0))) .'</font></td></tr>';
705
+	                        $content[] = '<tr><td style="padding: 0px;padding-left:10px;margin:0px;line-height:18px;text-align:left;">'.$this->mail_font_style.''._('Subnet').'</a></font></td>	<td style="padding: 0px;padding-left:15px;margin:0px;line-height:18px;text-align:left;padding-top:10px;"><a href="'.$this->createURL().''.create_link("subnets", $subnet->sectionId, $subnet->id).'">'.$this->mail_font_style_href.$this->transform_address($subnet->subnet, "dotted")."/".$subnet->mask.'</font></a></td></tr>';
706
+	                        $content[] = '<tr><td style="padding: 0px;padding-left:10px;margin:0px;line-height:18px;text-align:left;">'.$this->mail_font_style.''._('Description').'</font></td>	  	<td style="padding: 0px;padding-left:15px;margin:0px;line-height:18px;text-align:left;">'.$this->mail_font_style.''.$subnet->description.'</font></td></tr>';
707
+	                        $content[] = '<tr><td style="padding: 0px;padding-left:10px;margin:0px;line-height:18px;text-align:left;">'.$this->mail_font_style.''._('Usage').' (%)</font></td>	<td style="padding: 0px;padding-left:15px;margin:0px;line-height:18px;text-align:left;">'.$this->mail_font_style.''.gmp_strval(gmp_sub(100, (int) round($subnet_usage['freehosts_percent'], 0))).'</font></td></tr>';
708 708
 	                        $content[] = "</table>";
709 709
 	                        // plain
710 710
 	                        $content_plain[] = "$subject"."\r\n------------------------------\r\n";
711
-	                        $content_plain[] = _("Subnet").": ".$this->transform_address($subnet->subnet,"dotted")."/".$subnet->mask;
712
-	                        $content_plain[] = _("Usage")." (%) : ".gmp_strval(gmp_sub(100,(int) round($subnet_usage['freehosts_percent'], 0)));
711
+	                        $content_plain[] = _("Subnet").": ".$this->transform_address($subnet->subnet, "dotted")."/".$subnet->mask;
712
+	                        $content_plain[] = _("Usage")." (%) : ".gmp_strval(gmp_sub(100, (int) round($subnet_usage['freehosts_percent'], 0)));
713 713
 
714 714
 	                        # set content
715
-	                        $content 		= $phpipam_mail->generate_message (implode("\r\n", $content));
716
-	                        $content_plain 	= implode("\r\n",$content_plain);
715
+	                        $content = $phpipam_mail->generate_message(implode("\r\n", $content));
716
+	                        $content_plain = implode("\r\n", $content_plain);
717 717
 
718 718
                         	$phpipam_mail->Php_mailer->setFrom($mail_settings->mAdminMail, $mail_settings->mAdminName);
719 719
                         	//add all admins to CC
720
-                        	$recipients = $this->changelog_mail_get_recipients ($subnet->id);
720
+                        	$recipients = $this->changelog_mail_get_recipients($subnet->id);
721 721
 
722
-                        	if ($recipients!==false) {
723
-                        		foreach($recipients as $a) {
722
+                        	if ($recipients !== false) {
723
+                        		foreach ($recipients as $a) {
724 724
                     			    $phpipam_mail->Php_mailer->addAddress($a->email);
725 725
                         		}
726 726
 
@@ -757,7 +757,7 @@  discard block
 block discarded – undo
757 757
 	 * @param mixed $subnetId
758 758
 	 * @return void
759 759
 	 */
760
-	public function remove_gateway ($subnetId) {
760
+	public function remove_gateway($subnetId) {
761 761
 		try { $this->Database->updateObject("ipaddresses", array("subnetId"=>$subnetId, "is_gateway"=>0), "subnetId"); }
762 762
 		catch (Exception $e) {
763 763
 			$this->Result->show("danger", _("Error: ").$e->getMessage());
@@ -771,11 +771,11 @@  discard block
 block discarded – undo
771 771
 	 * @access public
772 772
 	 * @return object custom address fields
773 773
 	 */
774
-	public function set_custom_fields () {
774
+	public function set_custom_fields() {
775 775
 		# Tools object
776
-		$Tools = new Tools ($this->Database);
776
+		$Tools = new Tools($this->Database);
777 777
 		# fetch
778
-		return $Tools->fetch_custom_fields ('ipaddresses');
778
+		return $Tools->fetch_custom_fields('ipaddresses');
779 779
 	}
780 780
 
781 781
 	/**
@@ -789,12 +789,12 @@  discard block
 block discarded – undo
789 789
 	 * @param int $subnetId
790 790
 	 * @return boolean success/failure
791 791
 	 */
792
-	public function address_exists ($address, $subnetId, $cnt = true) {
792
+	public function address_exists($address, $subnetId, $cnt = true) {
793 793
 		# make sure it is in decimal format
794 794
 		$address = $this->transform_address($address, "decimal");
795 795
 		# check
796
-		if($cnt===true) { $query = "select count(*) as `cnt` from `ipaddresses` where `subnetId`=? and `ip_addr`=?;"; }
797
-		else			{ $query = "select `id` from `ipaddresses` where `subnetId`=? and `ip_addr`=?;";  }
796
+		if ($cnt === true) { $query = "select count(*) as `cnt` from `ipaddresses` where `subnetId`=? and `ip_addr`=?;"; }
797
+		else { $query = "select `id` from `ipaddresses` where `subnetId`=? and `ip_addr`=?;"; }
798 798
 		# fetch
799 799
 		try { $count = $this->Database->getObjectQuery($query, array($subnetId, $address)); }
800 800
 		catch (Exception $e) {
@@ -802,8 +802,8 @@  discard block
 block discarded – undo
802 802
 			return false;
803 803
 		}
804 804
 		# result
805
-		if ($cnt===true)	{ return $count->cnt==0 ? false : true; }
806
-		else				{ return is_null($count->id) ? false : $count->id; }
805
+		if ($cnt === true) { return $count->cnt == 0 ? false : true; }
806
+		else { return is_null($count->id) ? false : $count->id; }
807 807
 	}
808 808
 
809 809
 	/**
@@ -814,7 +814,7 @@  discard block
 block discarded – undo
814 814
 	 * @param int $ip2
815 815
 	 * @return void
816 816
 	 */
817
-	public function calculate_address_diff ($ip1, $ip2) {
817
+	public function calculate_address_diff($ip1, $ip2) {
818 818
 		return gmp_strval(gmp_sub($ip2, $ip1));
819 819
 	}
820 820
 
@@ -827,46 +827,46 @@  discard block
 block discarded – undo
827 827
 	 * @param obj $Subnets
828 828
 	 * @return int / false
829 829
 	 */
830
-	public function get_first_available_address ($subnetId, $Subnets) {
830
+	public function get_first_available_address($subnetId, $Subnets) {
831 831
 
832 832
 		# fetch all addresses in subnet and subnet
833
-		$addresses = $this->fetch_subnet_addresses ($subnetId, "ip_addr", "asc", array("ip_addr"));
833
+		$addresses = $this->fetch_subnet_addresses($subnetId, "ip_addr", "asc", array("ip_addr"));
834 834
 		$subnet = (array) $Subnets->fetch_subnet(null, $subnetId);
835 835
 
836 836
 		# if folder return false
837
-		if ($subnet['isFolder']=="1")                                                                   { return false; }
837
+		if ($subnet['isFolder'] == "1") { return false; }
838 838
 
839 839
 		# false if slaves
840
-		$this->Subnets = new Subnets ($this->Database);
841
-		if($this->Subnets->has_slaves ($subnetId))                                                      { return false; }
840
+		$this->Subnets = new Subnets($this->Database);
841
+		if ($this->Subnets->has_slaves($subnetId)) { return false; }
842 842
 
843 843
 	    # get max hosts
844
-	    $max_hosts = $Subnets->get_max_hosts ($subnet['mask'], $this->identify_address($subnet['subnet']));
844
+	    $max_hosts = $Subnets->get_max_hosts($subnet['mask'], $this->identify_address($subnet['subnet']));
845 845
 
846 846
 		# full subnet?
847
-		if(sizeof($addresses)>=$max_hosts)																{ return false; } 	//full subnet
847
+		if (sizeof($addresses) >= $max_hosts) { return false; } 	//full subnet
848 848
 
849 849
 		# set type
850
-		$ip_version = $this->identify_address ($subnet['subnet']);
850
+		$ip_version = $this->identify_address($subnet['subnet']);
851 851
 	    # get first diff > 1
852
-	    if(sizeof($addresses)>0) {
853
-		    foreach($addresses as $k=>$ipaddress) {
852
+	    if (sizeof($addresses) > 0) {
853
+		    foreach ($addresses as $k=>$ipaddress) {
854 854
 			    # check subnet and first IP
855
-			    if($k==0) {
855
+			    if ($k == 0) {
856 856
 				    # /31 fix
857
-				    if($subnet['mask']==31)	{
858
-					    if(gmp_strval(gmp_sub($addresses[$k]->ip_addr, $subnet['subnet']))>0) 			{ return gmp_strval($subnet['subnet']); }
857
+				    if ($subnet['mask'] == 31) {
858
+					    if (gmp_strval(gmp_sub($addresses[$k]->ip_addr, $subnet['subnet'])) > 0) { return gmp_strval($subnet['subnet']); }
859 859
 				    } else {
860
-					    if(gmp_strval(gmp_sub($addresses[$k]->ip_addr, $subnet['subnet']))>1) 			{ return gmp_strval(gmp_add($subnet['subnet'], 1)); }
861
-					    elseif($ip_version=="IPv6") {
862
-						    if(sizeof($addresses)==1) {
863
-							    if(gmp_strval(gmp_sub($addresses[$k]->ip_addr, $subnet['subnet']))==0)	{ return gmp_strval(gmp_add($subnet['subnet'], 1)); }
860
+					    if (gmp_strval(gmp_sub($addresses[$k]->ip_addr, $subnet['subnet'])) > 1) { return gmp_strval(gmp_add($subnet['subnet'], 1)); }
861
+					    elseif ($ip_version == "IPv6") {
862
+						    if (sizeof($addresses) == 1) {
863
+							    if (gmp_strval(gmp_sub($addresses[$k]->ip_addr, $subnet['subnet'])) == 0) { return gmp_strval(gmp_add($subnet['subnet'], 1)); }
864 864
 						    }
865 865
 					    }
866 866
 				    }
867 867
 			    }
868 868
 			    else {
869
-				    if(gmp_strval(gmp_sub($addresses[$k]->ip_addr, $addresses[$k-1]->ip_addr))>1) 		{ return gmp_strval(gmp_add($addresses[$k-1]->ip_addr, 1)); }
869
+				    if (gmp_strval(gmp_sub($addresses[$k]->ip_addr, $addresses[$k - 1]->ip_addr)) > 1) { return gmp_strval(gmp_add($addresses[$k - 1]->ip_addr, 1)); }
870 870
 			    }
871 871
 		    }
872 872
 		    # all consecutive, last + 1
@@ -875,8 +875,8 @@  discard block
 block discarded – undo
875 875
 	    # no addresses
876 876
 	    else {
877 877
 		    # /32, /31
878
-		    if($subnet['mask']==32 || $subnet['mask']==31 || $ip_version=="IPv6") 						{ return $subnet['subnet']; }
879
-		    else																						{ return gmp_strval(gmp_add($subnet['subnet'], 1)); }
878
+		    if ($subnet['mask'] == 32 || $subnet['mask'] == 31 || $ip_version == "IPv6") { return $subnet['subnet']; }
879
+		    else { return gmp_strval(gmp_add($subnet['subnet'], 1)); }
880 880
 	    }
881 881
 	}
882 882
 
@@ -902,27 +902,27 @@  discard block
 block discarded – undo
902 902
 	 * @param bool $print_error (default: true)
903 903
 	 * @return void
904 904
 	 */
905
-	public function ptr_modify ($action, $address, $print_error = true) {
905
+	public function ptr_modify($action, $address, $print_error = true) {
906 906
         // fetch settings
907
-        $this->settings ();
907
+        $this->settings();
908 908
         //check if powerdns enabled
909
-        if ($this->settings->enablePowerDNS!=1) {
909
+        if ($this->settings->enablePowerDNS != 1) {
910 910
             return false;
911 911
         }
912 912
         //enabled, proceed
913 913
         else {
914 914
     		// first check if subnet selected for PTR records
915
-    		$this->initialize_subnets_object ();
916
-    		$subnet = $this->Subnets->fetch_subnet ("id", $address['subnetId']);
917
-    		if ($subnet->DNSrecursive!="1") { return false; }
915
+    		$this->initialize_subnets_object();
916
+    		$subnet = $this->Subnets->fetch_subnet("id", $address['subnetId']);
917
+    		if ($subnet->DNSrecursive != "1") { return false; }
918 918
 
919 919
     		// ignore if PTRignore set
920
-    		if ($address['PTRignore']=="1")	{
920
+    		if ($address['PTRignore'] == "1") {
921 921
 				// validate db
922
-				$this->pdns_validate_connection ();
922
+				$this->pdns_validate_connection();
923 923
 				// remove if it exists
924
-				if ($this->ptr_exists ($address['PTR'])) {
925
-					$this->ptr_delete ($address, false);
924
+				if ($this->ptr_exists($address['PTR'])) {
925
+					$this->ptr_delete($address, false);
926 926
 										{ return false; }
927 927
 				}
928 928
 				else {
@@ -930,15 +930,15 @@  discard block
 block discarded – undo
930 930
 				}
931 931
     		}
932 932
     		// validate db
933
-    		$this->pdns_validate_connection ();
933
+    		$this->pdns_validate_connection();
934 934
 
935 935
     		// to object
936 936
     		$address = (object) $address;
937 937
     		# execute based on action
938
-    		if($action=="add")				{ return $this->ptr_add ($address, $print_error); }							//create new PTR
939
-    		elseif($action=="edit")			{ return $this->ptr_edit ($address, $print_error); }						//modify existing PTR
940
-    		elseif($action=="delete")		{ return $this->ptr_delete ($address, $print_error); }						//delete PTR
941
-    		else							{ return $this->Result->show("danger", _("Invalid PDNS action"), true); }
938
+    		if ($action == "add") { return $this->ptr_add($address, $print_error); }							//create new PTR
939
+    		elseif ($action == "edit") { return $this->ptr_edit($address, $print_error); }						//modify existing PTR
940
+    		elseif ($action == "delete") { return $this->ptr_delete($address, $print_error); }						//delete PTR
941
+    		else { return $this->Result->show("danger", _("Invalid PDNS action"), true); }
942 942
         }
943 943
 	}
944 944
 
@@ -949,17 +949,17 @@  discard block
 block discarded – undo
949 949
 	 * @param mixed $address
950 950
 	 * @return void
951 951
 	 */
952
-	public function pdns_remove_ip_and_hostname_records ($address) {
952
+	public function pdns_remove_ip_and_hostname_records($address) {
953 953
         // fetch settings
954
-        $this->settings ();
954
+        $this->settings();
955 955
         //check if powerdns enabled
956
-        if ($this->settings->enablePowerDNS!=1) {
956
+        if ($this->settings->enablePowerDNS != 1) {
957 957
             return false;
958 958
         }
959 959
 		// validate db
960
-		$this->pdns_validate_connection ();
960
+		$this->pdns_validate_connection();
961 961
 		// execute
962
-		return $this->PowerDNS->pdns_remove_ip_and_hostname_records ($address['hostname'], $address['ip_addr']);
962
+		return $this->PowerDNS->pdns_remove_ip_and_hostname_records($address['hostname'], $address['ip_addr']);
963 963
 	}
964 964
 
965 965
 	/**
@@ -969,17 +969,17 @@  discard block
 block discarded – undo
969 969
 	 * @param bool $die (default: false)
970 970
 	 * @return void
971 971
 	 */
972
-	public function pdns_validate_connection ($die = true) {
972
+	public function pdns_validate_connection($die = true) {
973 973
 		# powerDNS class
974
-		$this->PowerDNS = new PowerDNS ($this->Database);
974
+		$this->PowerDNS = new PowerDNS($this->Database);
975 975
 		# add API info
976
-		if(isset($this->api)) {
976
+		if (isset($this->api)) {
977 977
 			$this->PowerDNS->api = $this->api;
978 978
 		}
979 979
 		# check connection
980
-		if($this->PowerDNS->db_check()===false && $die) { $this->Result->show("danger", _("Cannot connect to powerDNS database"), true); }
980
+		if ($this->PowerDNS->db_check() === false && $die) { $this->Result->show("danger", _("Cannot connect to powerDNS database"), true); }
981 981
 		# get settings
982
-		$this->get_settings ();
982
+		$this->get_settings();
983 983
 	}
984 984
 
985 985
 	/**
@@ -989,17 +989,17 @@  discard block
 block discarded – undo
989 989
 	 * @param mixed $subnet_id
990 990
 	 * @return array|false
991 991
 	 */
992
-	private function pdns_fetch_domain ($subnet_id) {
992
+	private function pdns_fetch_domain($subnet_id) {
993 993
 		# initialize subnets
994
-		$this->initialize_subnets_object ();
994
+		$this->initialize_subnets_object();
995 995
 		// fetch subnet
996
-		$subnet = $this->Subnets->fetch_subnet ("id", $subnet_id);
997
-		if($subnet===false)							{  $this->Result->show("danger", _("Invalid subnet Id"), true); }
996
+		$subnet = $this->Subnets->fetch_subnet("id", $subnet_id);
997
+		if ($subnet === false) {  $this->Result->show("danger", _("Invalid subnet Id"), true); }
998 998
 
999 999
 		// set PTR zone name from IP/mash
1000
-		$zone = $this->PowerDNS->get_ptr_zone_name ($this->transform_address ($subnet->subnet, "dotted"), $subnet->mask);
1000
+		$zone = $this->PowerDNS->get_ptr_zone_name($this->transform_address($subnet->subnet, "dotted"), $subnet->mask);
1001 1001
 		// try to fetch
1002
-		return  $this->PowerDNS->fetch_domain_by_name ($zone);
1002
+		return  $this->PowerDNS->fetch_domain_by_name($zone);
1003 1003
 	}
1004 1004
 
1005 1005
 	/**
@@ -1011,30 +1011,30 @@  discard block
 block discarded – undo
1011 1011
 	 * @param mixed $id (default: NULL)
1012 1012
 	 * @return void
1013 1013
 	 */
1014
-	public function ptr_add ($address, $print_error = true, $id = null) {
1014
+	public function ptr_add($address, $print_error = true, $id = null) {
1015 1015
 		// decode values
1016 1016
 		$values = json_decode($this->settings->powerDNS);
1017 1017
 
1018 1018
     	// set default hostname for PTR if set
1019
-    	if (strlen($address->hostname)==0) {
1020
-        	if (strlen($values->def_ptr_domain)>0) {
1019
+    	if (strlen($address->hostname) == 0) {
1020
+        	if (strlen($values->def_ptr_domain) > 0) {
1021 1021
             	$address->hostname = $values->def_ptr_domain;
1022 1022
         	}
1023 1023
     	}
1024 1024
 		// validate hostname
1025
-		if ($this->validate_hostname ($address->hostname)===false)		{ return false; }
1025
+		if ($this->validate_hostname($address->hostname) === false) { return false; }
1026 1026
 		// fetch domain
1027
-		$domain = $this->pdns_fetch_domain ($address->subnetId);
1027
+		$domain = $this->pdns_fetch_domain($address->subnetId);
1028 1028
 
1029 1029
 		// formulate new record
1030
-		$record = $this->PowerDNS->formulate_new_record ($domain->id, $this->PowerDNS->get_ip_ptr_name ($this->transform_address ($address->ip_addr, "dotted")), "PTR", $address->hostname, $values->ttl);
1030
+		$record = $this->PowerDNS->formulate_new_record($domain->id, $this->PowerDNS->get_ip_ptr_name($this->transform_address($address->ip_addr, "dotted")), "PTR", $address->hostname, $values->ttl);
1031 1031
 		// insert record
1032
-		$this->PowerDNS->add_domain_record ($record, false);
1032
+		$this->PowerDNS->add_domain_record($record, false);
1033 1033
 		// link to address
1034
-		$id = $id===null ? $this->lastId : $id;
1035
-		$this->ptr_link ($id, $this->PowerDNS->lastId);
1034
+		$id = $id === null ? $this->lastId : $id;
1035
+		$this->ptr_link($id, $this->PowerDNS->lastId);
1036 1036
 		// ok
1037
-		if ($print_error && php_sapi_name()!="cli")
1037
+		if ($print_error && php_sapi_name() != "cli")
1038 1038
 		$this->Result->show("success", "PTR record created", false);
1039 1039
 
1040 1040
 		return true;
@@ -1048,37 +1048,37 @@  discard block
 block discarded – undo
1048 1048
 	 * @param mixed $print_error (default: true)
1049 1049
 	 * @return void
1050 1050
 	 */
1051
-	public function ptr_edit ($address, $print_error = true) {
1051
+	public function ptr_edit($address, $print_error = true) {
1052 1052
 		// validate hostname
1053
-		if ($this->validate_hostname ($address->hostname)===false)	{
1053
+		if ($this->validate_hostname($address->hostname) === false) {
1054 1054
 			// remove pointer if it exists!
1055
-			if ($this->ptr_exists ($address->PTR)===true)	{ $this->ptr_delete ($address, $print_error); }
1056
-			else											{ return false; }
1055
+			if ($this->ptr_exists($address->PTR) === true) { $this->ptr_delete($address, $print_error); }
1056
+			else { return false; }
1057 1057
 		}
1058 1058
 
1059 1059
 		// new record
1060
- 		if ($this->ptr_exists ($address->PTR)===false) {
1060
+ 		if ($this->ptr_exists($address->PTR) === false) {
1061 1061
 	 		// fake lastid
1062 1062
 	 		$this->lastId = $address->id;
1063 1063
 	 		// new ptr record
1064
-	 		$this->ptr_add ($address, true);
1064
+	 		$this->ptr_add($address, true);
1065 1065
  		}
1066 1066
  		// update PTR
1067 1067
  		else {
1068 1068
 			// fetch domain
1069
-			$domain = $this->pdns_fetch_domain ($address->subnetId);
1069
+			$domain = $this->pdns_fetch_domain($address->subnetId);
1070 1070
 
1071 1071
 			// fetch old
1072
-			$old_record = $this->PowerDNS->fetch_record ($address->PTR);
1072
+			$old_record = $this->PowerDNS->fetch_record($address->PTR);
1073 1073
 
1074 1074
 			// create insert array
1075
-			$update = $this->PowerDNS->formulate_update_record ($this->PowerDNS->get_ip_ptr_name ($this->transform_address ($address->ip_addr, "dotted")), null, $address->hostname, null, null, null, $old_record->change_date);
1075
+			$update = $this->PowerDNS->formulate_update_record($this->PowerDNS->get_ip_ptr_name($this->transform_address($address->ip_addr, "dotted")), null, $address->hostname, null, null, null, $old_record->change_date);
1076 1076
 			$update['id'] = $address->PTR;
1077 1077
 
1078 1078
 			// update
1079
-			$this->PowerDNS->update_domain_record ($domain->id, $update, $print_error);
1079
+			$this->PowerDNS->update_domain_record($domain->id, $update, $print_error);
1080 1080
 			// ok
1081
-			if ($print_error && php_sapi_name()!="cli")
1081
+			if ($print_error && php_sapi_name() != "cli")
1082 1082
 			$this->Result->show("success", "PTR record updated", false);
1083 1083
  		}
1084 1084
 	}
@@ -1091,20 +1091,20 @@  discard block
 block discarded – undo
1091 1091
 	 * @param mixed $print_error
1092 1092
 	 * @return void
1093 1093
 	 */
1094
-	public function ptr_delete ($address, $print_error) {
1094
+	public function ptr_delete($address, $print_error) {
1095 1095
 		$address = (object) $address;
1096 1096
 
1097 1097
 		// remove link from ipaddresses
1098
-		$this->ptr_unlink ($address->id);
1098
+		$this->ptr_unlink($address->id);
1099 1099
 
1100 1100
 		// exists
1101
-		if ($this->ptr_exists ($address->PTR)!==false)	{
1101
+		if ($this->ptr_exists($address->PTR) !== false) {
1102 1102
 			// fetch domain
1103
-			$domain = $this->pdns_fetch_domain ($address->subnetId);
1103
+			$domain = $this->pdns_fetch_domain($address->subnetId);
1104 1104
 			//remove
1105
-			$this->PowerDNS->remove_domain_record ($domain->id, $address->PTR);
1105
+			$this->PowerDNS->remove_domain_record($domain->id, $address->PTR);
1106 1106
     		// ok
1107
-    		if ($print_error && php_sapi_name()!="cli")
1107
+    		if ($print_error && php_sapi_name() != "cli")
1108 1108
     		$this->Result->show("success", "PTR record removed", false);
1109 1109
 		}
1110 1110
 	}
@@ -1117,7 +1117,7 @@  discard block
 block discarded – undo
1117 1117
 	 * @param mixed $ptr_id
1118 1118
 	 * @return void
1119 1119
 	 */
1120
-	public function ptr_link ($address_id, $ptr_id) {
1120
+	public function ptr_link($address_id, $ptr_id) {
1121 1121
 		# execute
1122 1122
 		try { $this->Database->updateObject("ipaddresses", array("id"=>$address_id, "PTR"=>$ptr_id)); }
1123 1123
 		catch (Exception $e) {
@@ -1133,7 +1133,7 @@  discard block
 block discarded – undo
1133 1133
 	 * @param mixed $address_id
1134 1134
 	 * @return void
1135 1135
 	 */
1136
-	private function ptr_unlink ($address_id) {
1136
+	private function ptr_unlink($address_id) {
1137 1137
 		# execute
1138 1138
 		try { $this->Database->updateObject("ipaddresses", array("id"=>$address_id, "PTR"=>0)); }
1139 1139
 		catch (Exception $e) {
@@ -1149,7 +1149,7 @@  discard block
 block discarded – undo
1149 1149
 	 * @param mixed $subnet_id
1150 1150
 	 * @return void
1151 1151
 	 */
1152
-	public function ptr_unlink_subnet_addresses ($subnet_id) {
1152
+	public function ptr_unlink_subnet_addresses($subnet_id) {
1153 1153
 		try { $this->Database->runQuery("update `ipaddresses` set `PTR` = 0 where `subnetId` = ?;", array($subnet_id)); }
1154 1154
 		catch (Exception $e) {
1155 1155
 			$this->Result->show("danger", _("Error: ").$e->getMessage());
@@ -1166,8 +1166,8 @@  discard block
 block discarded – undo
1166 1166
 	 * @param mixed $ptr_id (default: 0)
1167 1167
 	 * @return void
1168 1168
 	 */
1169
-	private function ptr_exists ($ptr_id = 0) {
1170
-		return $this->PowerDNS->record_id_exists ($ptr_id);
1169
+	private function ptr_exists($ptr_id = 0) {
1170
+		return $this->PowerDNS->record_id_exists($ptr_id);
1171 1171
 	}
1172 1172
 
1173 1173
 	/**
@@ -1177,14 +1177,14 @@  discard block
 block discarded – undo
1177 1177
 	 * @param mixed $subnetId
1178 1178
 	 * @return void
1179 1179
 	 */
1180
-	public function ptr_get_subnet_indexes ($subnetId) {
1180
+	public function ptr_get_subnet_indexes($subnetId) {
1181 1181
 		try { $indexes = $this->Database->getObjectsQuery("select `PTR` from `ipaddresses` where `PTR` != 0 and `subnetId` = ?;", array($subnetId)); }
1182 1182
 		catch (Exception $e) {
1183 1183
 			$this->Result->show("danger", _("Error: ").$e->getMessage());
1184 1184
 			return false;
1185 1185
 		}
1186 1186
 		# parse
1187
-		if (sizeof($indexes)>0) {
1187
+		if (sizeof($indexes) > 0) {
1188 1188
     		$out = array();
1189 1189
     		// loop
1190 1190
     		foreach ($indexes as $i) {
@@ -1223,15 +1223,15 @@  discard block
 block discarded – undo
1223 1223
 	 * @param int $subnetId
1224 1224
 	 * @return void
1225 1225
 	 */
1226
-	public function import_address_from_csv ($address, $subnetId) {
1226
+	public function import_address_from_csv($address, $subnetId) {
1227 1227
 		# Subnets object
1228
-		$this->initialize_subnets_object ();
1228
+		$this->initialize_subnets_object();
1229 1229
 
1230 1230
 	    # fetch subnet details
1231 1231
 	    $subnet = (array) $this->Subnets->fetch_subnet(null, $subnetId);
1232 1232
 
1233 1233
 	    # verify address
1234
-	    if($this->verify_address( $address[0], $this->transform_to_dotted($subnet['subnet'])."/".$subnet['mask'], false, false)!==false) { return false; }
1234
+	    if ($this->verify_address($address[0], $this->transform_to_dotted($subnet['subnet'])."/".$subnet['mask'], false, false) !== false) { return false; }
1235 1235
 	    # check for duplicates
1236 1236
 	    if ($this->address_exists($address[0], $subnetId)) { return _('IP address already exists').' - '.$address[0]; }
1237 1237
 
@@ -1249,21 +1249,21 @@  discard block
 block discarded – undo
1249 1249
 								);
1250 1250
 
1251 1251
 		# switch to 0, state to active
1252
-		$address_insert['switch'] = strlen($address_insert['switch'])==0 ? 0 : $address_insert['switch'];
1253
-		$address_insert['state']  = strlen($address_insert['state'])==0 ?  1 : $address_insert['state'];
1252
+		$address_insert['switch'] = strlen($address_insert['switch']) == 0 ? 0 : $address_insert['switch'];
1253
+		$address_insert['state']  = strlen($address_insert['state']) == 0 ? 1 : $address_insert['state'];
1254 1254
 
1255 1255
 		# custom fields, append to array
1256
-		$m=9;
1256
+		$m = 9;
1257 1257
 		$custom_fields = $this->set_custom_fields();
1258
-		if(sizeof($custom_fields) > 0) {
1259
-			foreach($custom_fields as $c) {
1258
+		if (sizeof($custom_fields) > 0) {
1259
+			foreach ($custom_fields as $c) {
1260 1260
 				$address_insert[$c['name']] = $address[$m];
1261 1261
 				$m++;
1262 1262
 			}
1263 1263
 		}
1264 1264
 
1265 1265
 		# insert
1266
-		return $this->modify_address_add ($address_insert);
1266
+		return $this->modify_address_add($address_insert);
1267 1267
 	}
1268 1268
 
1269 1269
 
@@ -1286,8 +1286,8 @@  discard block
 block discarded – undo
1286 1286
 	 * @access private
1287 1287
 	 * @return void
1288 1288
 	 */
1289
-	private function initialize_subnets_object () {
1290
-		if(!is_object($this->Subnets)) { $this->Subnets = new Subnets ($this->Database); }
1289
+	private function initialize_subnets_object() {
1290
+		if (!is_object($this->Subnets)) { $this->Subnets = new Subnets($this->Database); }
1291 1291
 	}
1292 1292
 
1293 1293
 	/**
@@ -1300,19 +1300,19 @@  discard block
 block discarded – undo
1300 1300
 	 * @param string $fields (default: "*")
1301 1301
 	 * @return void
1302 1302
 	 */
1303
-	public function fetch_subnet_addresses ($subnetId, $order=null, $order_direction=null, $fields = "*") {
1303
+	public function fetch_subnet_addresses($subnetId, $order = null, $order_direction = null, $fields = "*") {
1304 1304
 		# set order
1305
-		if(!is_null($order)) 	{ $order = array($order, $order_direction); }
1306
-		else 					{ $order = array("ip_addr", "asc"); }
1305
+		if (!is_null($order)) { $order = array($order, $order_direction); }
1306
+		else { $order = array("ip_addr", "asc"); }
1307 1307
 
1308 1308
 		# fields
1309
-		if($fields!="*") {
1309
+		if ($fields != "*") {
1310 1310
     		$fields = implode(",", $fields);
1311 1311
 		}
1312 1312
 
1313 1313
 		# escape ordering
1314
-		$order[0] = $this->Database->escape ($order[0]);
1315
-		$order[1] = $this->Database->escape ($order[1]);
1314
+		$order[0] = $this->Database->escape($order[0]);
1315
+		$order[1] = $this->Database->escape($order[1]);
1316 1316
 
1317 1317
 		try { $addresses = $this->Database->getObjectsQuery("SELECT $fields FROM `ipaddresses` where `subnetId` = ? order by `$order[0]` $order[1];", array($subnetId)); }
1318 1318
 		catch (Exception $e) {
@@ -1320,17 +1320,17 @@  discard block
 block discarded – undo
1320 1320
 			return false;
1321 1321
 		}
1322 1322
 		# save to addresses cache
1323
-		if(sizeof($addresses)>0) {
1324
-			foreach($addresses as $k=>$address) {
1323
+		if (sizeof($addresses) > 0) {
1324
+			foreach ($addresses as $k=>$address) {
1325 1325
 				# add decimal format
1326
-				$address->ip = $this->transform_to_dotted ($address->ip_addr);
1326
+				$address->ip = $this->transform_to_dotted($address->ip_addr);
1327 1327
 				# save to subnets
1328 1328
 				$this->addresses[$address->id] = (object) $address;
1329 1329
 				$addresses[$k]->ip = $address->ip;
1330 1330
 			}
1331 1331
 		}
1332 1332
 		# result
1333
-		return sizeof($addresses)>0 ? $addresses : array();
1333
+		return sizeof($addresses) > 0 ? $addresses : array();
1334 1334
 	}
1335 1335
 
1336 1336
 	/**
@@ -1342,7 +1342,7 @@  discard block
 block discarded – undo
1342 1342
 	 * @param int $subnetId
1343 1343
 	 * @return int
1344 1344
 	 */
1345
-	public function count_subnet_addresses ($subnetId) {
1345
+	public function count_subnet_addresses($subnetId) {
1346 1346
 		try { $count = $this->Database->numObjectsFilter("ipaddresses", "subnetId", $subnetId); }
1347 1347
 		catch (Exception $e) {
1348 1348
 			$this->Result->show("danger", _("Error: ").$e->getMessage());
@@ -1361,17 +1361,17 @@  discard block
 block discarded – undo
1361 1361
 	 * @param mixed $subnets
1362 1362
 	 * @return void
1363 1363
 	 */
1364
-	public function count_addresses_in_multiple_subnets ($subnets) {
1364
+	public function count_addresses_in_multiple_subnets($subnets) {
1365 1365
 		# empty
1366
-		if(empty($subnets)) { return 0; }
1366
+		if (empty($subnets)) { return 0; }
1367 1367
 
1368 1368
 		# create query
1369 1369
 		$tmp = array();
1370
-		foreach($subnets as $k=>$s) {
1371
-			if (is_object($s))	{ $tmp[] = " `subnetId`=$s->id "; }
1372
-			else				{ $tmp[] = " `subnetId`=$s "; }
1370
+		foreach ($subnets as $k=>$s) {
1371
+			if (is_object($s)) { $tmp[] = " `subnetId`=$s->id "; }
1372
+			else { $tmp[] = " `subnetId`=$s "; }
1373 1373
 		}
1374
-		$query  = "select count(*) as `cnt` from `ipaddresses` where ".implode("or", $tmp).";";
1374
+		$query = "select count(*) as `cnt` from `ipaddresses` where ".implode("or", $tmp).";";
1375 1375
 
1376 1376
 		# fetch
1377 1377
 		try { $addresses = $this->Database->getObjectsQuery($query); }
@@ -1394,37 +1394,37 @@  discard block
 block discarded – undo
1394 1394
 	 * @param bool $count
1395 1395
 	 * @return void
1396 1396
 	 */
1397
-	public function fetch_subnet_addresses_recursive ($subnetId, $count = false, $order=null, $order_direction=null ) {
1397
+	public function fetch_subnet_addresses_recursive($subnetId, $count = false, $order = null, $order_direction = null) {
1398 1398
 		# initialize subnets
1399
-		$this->initialize_subnets_object ();
1400
-		$this->Subnets = new Subnets ($this->Database);
1401
-		$this->Subnets->reset_subnet_slaves_recursive();				//reset array of slaves before continuing
1402
-	    $this->Subnets->fetch_subnet_slaves_recursive($subnetId);		//fetch array of slaves
1403
-	    $this->Subnets->slaves = array_unique($this->Subnets->slaves);	//remove possible duplicates
1399
+		$this->initialize_subnets_object();
1400
+		$this->Subnets = new Subnets($this->Database);
1401
+		$this->Subnets->reset_subnet_slaves_recursive(); //reset array of slaves before continuing
1402
+	    $this->Subnets->fetch_subnet_slaves_recursive($subnetId); //fetch array of slaves
1403
+	    $this->Subnets->slaves = array_unique($this->Subnets->slaves); //remove possible duplicates
1404 1404
 
1405 1405
 		# ip address order
1406
-		if(!is_null($order)) 	{ $order_addr = array($order, $order_direction); }
1407
-		else 					{ $order_addr = array("ip_addr", "asc"); }
1406
+		if (!is_null($order)) { $order_addr = array($order, $order_direction); }
1407
+		else { $order_addr = array("ip_addr", "asc"); }
1408 1408
 
1409 1409
 		# escape ordering
1410
-		$order_addr[0] = $this->Database->escape ($order_addr[0]);
1411
-		$order_addr[1] = $this->Database->escape ($order_addr[1]);
1410
+		$order_addr[0] = $this->Database->escape($order_addr[0]);
1411
+		$order_addr[1] = $this->Database->escape($order_addr[1]);
1412 1412
 
1413 1413
 		$ids = array();
1414 1414
 		$ids[] = $subnetId;
1415 1415
 
1416 1416
 	    # set query to fetch all ip addresses for specified subnets or just count
1417
-		if($count) 	{ $query = 'select count(*) as cnt from `ipaddresses` where `subnetId` = ? '; }
1418
-		else	 	{ $query = 'select * from `ipaddresses` where `subnetId` = ? '; }
1419
-	    foreach($this->Subnets->slaves as $subnetId2) {
1417
+		if ($count) { $query = 'select count(*) as cnt from `ipaddresses` where `subnetId` = ? '; }
1418
+		else { $query = 'select * from `ipaddresses` where `subnetId` = ? '; }
1419
+	    foreach ($this->Subnets->slaves as $subnetId2) {
1420 1420
 		    # ignore orphaned
1421
-	    	if($subnetId2 != $subnetId) {
1422
-				$query  .= " or `subnetId` = ? ";
1421
+	    	if ($subnetId2 != $subnetId) {
1422
+				$query .= " or `subnetId` = ? ";
1423 1423
 		    	$ids[] = $subnetId2;
1424 1424
 			}
1425 1425
 		}
1426 1426
 
1427
-	    $query      .= "order by `$order_addr[0]` $order_addr[1];";
1427
+	    $query .= "order by `$order_addr[0]` $order_addr[1];";
1428 1428
 		# fetch
1429 1429
 		try { $addresses = $this->Database->getObjectsQuery($query, $ids); }
1430 1430
 		catch (Exception $e) {
@@ -1449,12 +1449,12 @@  discard block
 block discarded – undo
1449 1449
 	 * @param bool $is_broadcast (default: false)
1450 1450
 	 * @return void
1451 1451
 	 */
1452
-	public function find_unused_addresses ($address1, $address2, $netmask, $empty=false, $is_subnet=false, $is_broadcast=false) {
1452
+	public function find_unused_addresses($address1, $address2, $netmask, $empty = false, $is_subnet = false, $is_broadcast = false) {
1453 1453
 		# make sure addresses are in decimal format
1454
-		$address1 = $this->transform_address ($address1, "decimal");
1455
-		$address2 = $this->transform_address ($address2, "decimal");
1454
+		$address1 = $this->transform_address($address1, "decimal");
1455
+		$address2 = $this->transform_address($address2, "decimal");
1456 1456
 		# check for space
1457
-		return $this->identify_address($address1)=="IPv6" ? $this->find_unused_addresses_IPv6 ($address1, $address2, $netmask, $empty, $is_subnet, $is_broadcast) : $this->find_unused_addresses_IPv4 ($address1, $address2, $netmask, $empty);
1457
+		return $this->identify_address($address1) == "IPv6" ? $this->find_unused_addresses_IPv6($address1, $address2, $netmask, $empty, $is_subnet, $is_broadcast) : $this->find_unused_addresses_IPv4($address1, $address2, $netmask, $empty);
1458 1458
 	}
1459 1459
 
1460 1460
 	/**
@@ -1469,12 +1469,12 @@  discard block
 block discarded – undo
1469 1469
 	 * @param bool $empty
1470 1470
 	 * @return void
1471 1471
 	 */
1472
-	protected function find_unused_addresses_IPv4 ($address1, $address2, $netmask, $empty) {
1472
+	protected function find_unused_addresses_IPv4($address1, $address2, $netmask, $empty) {
1473 1473
 		# calculate diff
1474
-		$diff = $this->calculate_address_diff ($address1, $address2);
1474
+		$diff = $this->calculate_address_diff($address1, $address2);
1475 1475
 		# 32 subnets
1476
-		if($netmask==32) {
1477
-			if($empty) {
1476
+		if ($netmask == 32) {
1477
+			if ($empty) {
1478 1478
 				return array("ip"=>$this->transform_to_dotted($address1), "hosts"=>1);
1479 1479
 			}
1480 1480
 			else {
@@ -1482,16 +1482,16 @@  discard block
 block discarded – undo
1482 1482
 			}
1483 1483
 		}
1484 1484
 		# 31 subnets
1485
-		elseif($netmask==31) {
1485
+		elseif ($netmask == 31) {
1486 1486
 
1487
-			if($empty) {
1487
+			if ($empty) {
1488 1488
 				return array("ip"=>$this->transform_to_dotted($address1), "hosts"=>2);
1489 1489
 			}
1490
-			elseif($diff==1) {
1491
-				if($this->is_network($address1, $netmask)) {
1490
+			elseif ($diff == 1) {
1491
+				if ($this->is_network($address1, $netmask)) {
1492 1492
 					return array("ip"=>$this->transform_to_dotted($address2), "hosts"=>1);
1493 1493
 				}
1494
-				elseif($this->is_broadcast($address2, $netmask)) {
1494
+				elseif ($this->is_broadcast($address2, $netmask)) {
1495 1495
 					return array("ip"=>$this->transform_to_dotted($address1), "hosts"=>1);
1496 1496
 				}
1497 1497
 				else {
@@ -1503,16 +1503,16 @@  discard block
 block discarded – undo
1503 1503
 			}
1504 1504
 		}
1505 1505
 		# if diff is less than 2 return false */
1506
-		elseif ( $diff < 2 ) {
1506
+		elseif ($diff < 2) {
1507 1507
         		return false;
1508 1508
     	}
1509 1509
 		# if diff is 2 return 1 IP address in the middle */
1510
-		elseif ( $diff == 2 ) {
1511
-				return array("ip"=>$this->transform_to_dotted($address1+1), "hosts"=>1);
1510
+		elseif ($diff == 2) {
1511
+				return array("ip"=>$this->transform_to_dotted($address1 + 1), "hosts"=>1);
1512 1512
     	}
1513 1513
 		# if diff is more than 2 return pool */
1514 1514
 		else {
1515
-            	return array("ip"=>$this->transform_to_dotted($address1+1)." - ".$this->transform_to_dotted(($address2-1)), "hosts"=>gmp_strval(gmp_sub($diff, 1)));
1515
+            	return array("ip"=>$this->transform_to_dotted($address1 + 1)." - ".$this->transform_to_dotted(($address2 - 1)), "hosts"=>gmp_strval(gmp_sub($diff, 1)));
1516 1516
     	}
1517 1517
     	# default false
1518 1518
     	return false;
@@ -1532,33 +1532,33 @@  discard block
 block discarded – undo
1532 1532
 	 * @param bool $is_broadcast (default: false)
1533 1533
 	 * @return void
1534 1534
 	 */
1535
-	protected function find_unused_addresses_IPv6 ($address1, $address2, $netmask, $empty = false, $is_subnet = false, $is_broadcast = false) {
1535
+	protected function find_unused_addresses_IPv6($address1, $address2, $netmask, $empty = false, $is_subnet = false, $is_broadcast = false) {
1536 1536
 		# Initialize PEAR NET object
1537
-		$this->initialize_pear_net_IPv6 ();
1537
+		$this->initialize_pear_net_IPv6();
1538 1538
 
1539
-		if($empty) {
1540
-    		$Subnets = new Subnets ($this->Database);
1541
-    		return array("ip"=>$this->transform_to_dotted(gmp_strval($address1))." - ".$this->transform_to_dotted(gmp_strval($address2)), "hosts"=>$Subnets->get_max_hosts ($netmask, "IPv6"));
1539
+		if ($empty) {
1540
+    		$Subnets = new Subnets($this->Database);
1541
+    		return array("ip"=>$this->transform_to_dotted(gmp_strval($address1))." - ".$this->transform_to_dotted(gmp_strval($address2)), "hosts"=>$Subnets->get_max_hosts($netmask, "IPv6"));
1542 1542
 		}
1543 1543
         else {
1544 1544
     		# calculate diff
1545
-    		$diff = $this->calculate_address_diff ($address1, $address2);
1545
+    		$diff = $this->calculate_address_diff($address1, $address2);
1546 1546
 
1547 1547
     		# /128
1548
-    		if($netmask == 128) {
1549
-        		if($diff>1) {
1548
+    		if ($netmask == 128) {
1549
+        		if ($diff > 1) {
1550 1550
                     return array("ip"=>$this->transform_to_dotted(gmp_strval($address1)), "hosts"=>1);
1551 1551
                 }
1552 1552
         	}
1553 1553
     		# /127
1554
-    	    elseif($netmask == 127) {
1555
-        	    if($diff==1 && $this->is_network($address1, $netmask)) {
1554
+    	    elseif ($netmask == 127) {
1555
+        	    if ($diff == 1 && $this->is_network($address1, $netmask)) {
1556 1556
     				return array("ip"=>$this->transform_to_dotted($address2), "hosts"=>1);
1557 1557
     			}
1558
-    			elseif($diff==1 && $this->is_broadcast($address2, $netmask)) {
1558
+    			elseif ($diff == 1 && $this->is_broadcast($address2, $netmask)) {
1559 1559
     				return array("ip"=>$this->transform_to_dotted($address1), "hosts"=>1);
1560 1560
     			}
1561
-    			elseif($diff==0) {
1561
+    			elseif ($diff == 0) {
1562 1562
         			return false;
1563 1563
     			}
1564 1564
     			else {
@@ -1566,15 +1566,15 @@  discard block
 block discarded – undo
1566 1566
     			}
1567 1567
     	    }
1568 1568
     	    # null
1569
-    	    elseif ($diff==0) {
1569
+    	    elseif ($diff == 0) {
1570 1570
         	    return false;
1571 1571
     	    }
1572 1572
     	    # diff 1
1573
-    	    elseif ($diff==1) {
1574
-         		if($is_subnet) {
1573
+    	    elseif ($diff == 1) {
1574
+         		if ($is_subnet) {
1575 1575
                     return array("ip"=>$this->transform_to_dotted(gmp_strval($address1)), "hosts"=>1);
1576 1576
         		}
1577
-        		elseif($is_broadcast) {
1577
+        		elseif ($is_broadcast) {
1578 1578
                     return array("ip"=>$this->transform_to_dotted(gmp_strval($address2)), "hosts"=>1);
1579 1579
         		}
1580 1580
         		else {
@@ -1582,19 +1582,19 @@  discard block
 block discarded – undo
1582 1582
                 }
1583 1583
     	    }
1584 1584
     	    # diff 2
1585
-    	    elseif ($diff==2 && !$is_subnet && !$is_broadcast) {
1586
-                return array("ip"=>$this->transform_to_dotted(gmp_strval(gmp_add($address1,1))), "hosts"=>1);
1585
+    	    elseif ($diff == 2 && !$is_subnet && !$is_broadcast) {
1586
+                return array("ip"=>$this->transform_to_dotted(gmp_strval(gmp_add($address1, 1))), "hosts"=>1);
1587 1587
     	    }
1588 1588
     	    # default
1589 1589
     	    else {
1590
-        		if($is_subnet) {
1591
-                    return array("ip"=>$this->transform_to_dotted(gmp_strval($address1))." - ".$this->transform_to_dotted(gmp_strval(gmp_sub($address2,1))), "hosts"=>$this->reformat_number(gmp_strval(gmp_sub($diff,0))));
1590
+        		if ($is_subnet) {
1591
+                    return array("ip"=>$this->transform_to_dotted(gmp_strval($address1))." - ".$this->transform_to_dotted(gmp_strval(gmp_sub($address2, 1))), "hosts"=>$this->reformat_number(gmp_strval(gmp_sub($diff, 0))));
1592 1592
         		}
1593
-        		elseif($is_broadcast) {
1594
-                    return array("ip"=>$this->transform_to_dotted(gmp_strval(gmp_add($address1,1)))." - ".$this->transform_to_dotted(gmp_strval($address2)), "hosts"=>$this->reformat_number(gmp_strval(gmp_sub($diff,0))));
1593
+        		elseif ($is_broadcast) {
1594
+                    return array("ip"=>$this->transform_to_dotted(gmp_strval(gmp_add($address1, 1)))." - ".$this->transform_to_dotted(gmp_strval($address2)), "hosts"=>$this->reformat_number(gmp_strval(gmp_sub($diff, 0))));
1595 1595
         		}
1596 1596
         		else {
1597
-                    return array("ip"=>$this->transform_to_dotted(gmp_strval(gmp_add($address1,1)))." - ".$this->transform_to_dotted(gmp_strval(gmp_sub($address2,1))), "hosts"=>$this->reformat_number(gmp_strval(gmp_strval(gmp_sub($diff,1)))));
1597
+                    return array("ip"=>$this->transform_to_dotted(gmp_strval(gmp_add($address1, 1)))." - ".$this->transform_to_dotted(gmp_strval(gmp_sub($address2, 1))), "hosts"=>$this->reformat_number(gmp_strval(gmp_strval(gmp_sub($diff, 1)))));
1598 1598
                 }
1599 1599
         	}
1600 1600
 
@@ -1628,13 +1628,13 @@  discard block
 block discarded – undo
1628 1628
 	 * @param bool $die (default: false)
1629 1629
 	 * @return boolean
1630 1630
 	 */
1631
-	public function verify_address( $address, $subnet, $no_strict = false, $die=true ) {
1631
+	public function verify_address($address, $subnet, $no_strict = false, $die = true) {
1632 1632
 		# subnet should be in CIDR format
1633
-		$this->initialize_subnets_object ();
1634
-		if(strlen($error = $this->Subnets->verify_cidr ($subnet))>1)				{ $this->Result->show("danger", $error, $die); return true; }
1633
+		$this->initialize_subnets_object();
1634
+		if (strlen($error = $this->Subnets->verify_cidr($subnet)) > 1) { $this->Result->show("danger", $error, $die); return true; }
1635 1635
 
1636 1636
 		# make checks
1637
-		return $this->identify_address ($address)=="IPv6" ? $this->verify_address_IPv6 ($address, $subnet, $die) : $this->verify_address_IPv4 ($address, $subnet, $no_strict, $die);
1637
+		return $this->identify_address($address) == "IPv6" ? $this->verify_address_IPv6($address, $subnet, $die) : $this->verify_address_IPv4($address, $subnet, $no_strict, $die);
1638 1638
 	}
1639 1639
 
1640 1640
 	/**
@@ -1647,24 +1647,24 @@  discard block
 block discarded – undo
1647 1647
 	 * @param bool $die
1648 1648
 	 * @return boolean
1649 1649
 	 */
1650
-	public function verify_address_IPv4 ($address, $subnet, $no_strict, $die) {
1650
+	public function verify_address_IPv4($address, $subnet, $no_strict, $die) {
1651 1651
 		# Initialize PEAR NET object
1652
-		$this->initialize_pear_net_IPv4 ();
1652
+		$this->initialize_pear_net_IPv4();
1653 1653
         # fetch mask part
1654 1654
         $mask = explode("/", $subnet);
1655 1655
 
1656 1656
 		# is address valid?
1657
-		if (!$this->Net_IPv4->validateIP($address)) 						{ $this->Result->show("danger", _("IP address not valid")."! ($address)", $die); return true; }
1657
+		if (!$this->Net_IPv4->validateIP($address)) { $this->Result->show("danger", _("IP address not valid")."! ($address)", $die); return true; }
1658 1658
 		# is address in provided subnet
1659
-		elseif (!$this->Net_IPv4->ipInNetwork($address, $subnet)) 			{ $this->Result->show("danger", _("IP address not in selected subnet")."! ($address)", $die); return true; }
1659
+		elseif (!$this->Net_IPv4->ipInNetwork($address, $subnet)) { $this->Result->show("danger", _("IP address not in selected subnet")."! ($address)", $die); return true; }
1660 1660
 		# ignore  /31 and /32 subnet broadcast and subnet checks!
1661
-		elseif ($mask[1] == 31 || $mask[1] == 32 || $no_strict == true) 	{ }
1661
+		elseif ($mask[1] == 31 || $mask[1] == 32 || $no_strict == true) { }
1662 1662
 		# It cannot be subnet or broadcast
1663 1663
 		else {
1664 1664
             $net = $this->Net_IPv4->parseAddress($subnet);
1665 1665
 
1666
-            if ($net->network == $address) 									{ $this->Result->show("danger", _("Cannot add subnet as IP address!"), $die); return true; }
1667
-            elseif ($net->broadcast == $address)							{ $this->Result->show("danger", _("Cannot add broadcast as IP address!"), $die); return true; }
1666
+            if ($net->network == $address) { $this->Result->show("danger", _("Cannot add subnet as IP address!"), $die); return true; }
1667
+            elseif ($net->broadcast == $address) { $this->Result->show("danger", _("Cannot add broadcast as IP address!"), $die); return true; }
1668 1668
 		}
1669 1669
 		# default
1670 1670
 		return false;
@@ -1679,14 +1679,14 @@  discard block
 block discarded – undo
1679 1679
 	 * @param bool $die
1680 1680
 	 * @return boolean
1681 1681
 	 */
1682
-	public function verify_address_IPv6 ($address, $subnet, $die) {
1682
+	public function verify_address_IPv6($address, $subnet, $die) {
1683 1683
 		# Initialize PEAR NET object
1684
-		$this->initialize_pear_net_IPv6 ();
1684
+		$this->initialize_pear_net_IPv6();
1685 1685
 
1686 1686
 		# is it valid?
1687
-		if (!$this->Net_IPv6->checkIPv6($address)) 							{ $this->Result->show("danger", _("IP address not valid")."! ($address)", $die); return true; }
1687
+		if (!$this->Net_IPv6->checkIPv6($address)) { $this->Result->show("danger", _("IP address not valid")."! ($address)", $die); return true; }
1688 1688
 		# it must be in provided subnet
1689
-		elseif (!$this->Net_IPv6->isInNetmask($address, $subnet)) 			{ $this->Result->show("danger", _("IP address not in selected subnet")."! ($address)", $die); return true; }
1689
+		elseif (!$this->Net_IPv6->isInNetmask($address, $subnet)) { $this->Result->show("danger", _("IP address not in selected subnet")."! ($address)", $die); return true; }
1690 1690
 		# default
1691 1691
 		return false;
1692 1692
 	}
@@ -1698,19 +1698,19 @@  discard block
 block discarded – undo
1698 1698
 	 * @param mixed $address
1699 1699
 	 * @return void
1700 1700
 	 */
1701
-	public function validate_address ($address) {
1701
+	public function validate_address($address) {
1702 1702
 		# Initialize PEAR NET object
1703
-		$this->initialize_pear_net_IPv4 ();
1704
-		$this->initialize_pear_net_IPv6 ();
1703
+		$this->initialize_pear_net_IPv4();
1704
+		$this->initialize_pear_net_IPv6();
1705 1705
 
1706 1706
 		// no null
1707
-		if($this->transform_address ($address, "decimal")==0) {
1707
+		if ($this->transform_address($address, "decimal") == 0) {
1708 1708
 			return false;
1709 1709
 		}
1710 1710
 		// transform
1711
-		$address = $this->transform_address ($address, "dotted");
1711
+		$address = $this->transform_address($address, "dotted");
1712 1712
 		// ipv6
1713
-		if($this->identify_address ($address)=="IPv6") {
1713
+		if ($this->identify_address($address) == "IPv6") {
1714 1714
 			return $this->Net_IPv6->checkIPv6($address) ?  true : false;
1715 1715
 		}
1716 1716
 		// ipv4
@@ -1727,10 +1727,10 @@  discard block
 block discarded – undo
1727 1727
 	 * @param int $netmask
1728 1728
 	 * @return boolean
1729 1729
 	 */
1730
-	public function is_network ($address, $netmask) {
1731
-		$this->initialize_subnets_object ();
1732
-		$boundaries = $this->Subnets->get_network_boundaries ($address, $netmask);
1733
-		return $this->transform_address($address,"dotted")==$boundaries['network'] ? true : false;
1730
+	public function is_network($address, $netmask) {
1731
+		$this->initialize_subnets_object();
1732
+		$boundaries = $this->Subnets->get_network_boundaries($address, $netmask);
1733
+		return $this->transform_address($address, "dotted") == $boundaries['network'] ? true : false;
1734 1734
 	}
1735 1735
 
1736 1736
 	/**
@@ -1741,10 +1741,10 @@  discard block
 block discarded – undo
1741 1741
 	 * @param int $netmask
1742 1742
 	 * @return boolean
1743 1743
 	 */
1744
-	public function is_broadcast ($address, $netmask) {
1745
-		$this->initialize_subnets_object ();
1746
-		$boundaries = $this->Subnets->get_network_boundaries ($address, $netmask);
1747
-		return $this->transform_address($address,"dotted")==$boundaries['broadcast'] ? true : false;
1744
+	public function is_broadcast($address, $netmask) {
1745
+		$this->initialize_subnets_object();
1746
+		$boundaries = $this->Subnets->get_network_boundaries($address, $netmask);
1747
+		return $this->transform_address($address, "dotted") == $boundaries['broadcast'] ? true : false;
1748 1748
 	}
1749 1749
 
1750 1750
 	/**
@@ -1754,13 +1754,13 @@  discard block
 block discarded – undo
1754 1754
 	 * @param mixed $hostname
1755 1755
 	 * @return boolean
1756 1756
 	 */
1757
-	public function is_hostname_unique ($hostname) {
1757
+	public function is_hostname_unique($hostname) {
1758 1758
 		try { $cnt = $this->Database->numObjectsFilter("ipaddresses", "hostname", $hostname); }
1759 1759
 		catch (Exception $e) {
1760 1760
 			$this->Result->show("danger", _("Error: ").$e->getMessage());
1761 1761
 			return false;
1762 1762
 		}
1763
-		return $cnt==0 ? true : false;
1763
+		return $cnt == 0 ? true : false;
1764 1764
 	}
1765 1765
 
1766 1766
 
@@ -1790,18 +1790,18 @@  discard block
 block discarded – undo
1790 1790
 	 * @param array $addresses
1791 1791
 	 * @return void
1792 1792
 	 */
1793
-	public function compress_address_ranges ($addresses, $state=4) {
1793
+	public function compress_address_ranges($addresses, $state = 4) {
1794 1794
     	# set size
1795 1795
     	$size = sizeof($addresses);
1796 1796
     	// vars
1797 1797
     	$addresses_formatted = array();
1798 1798
 
1799 1799
 		# loop through IP addresses
1800
-		for($c=0; $c<$size; $c++) {
1800
+		for ($c = 0; $c < $size; $c++) {
1801 1801
 			# ignore already comressed range
1802
-			if($addresses[$c]->class!="compressed-range") {
1802
+			if ($addresses[$c]->class != "compressed-range") {
1803 1803
 				# gap between this and previous
1804
-				if(gmp_strval( @gmp_sub($addresses[$c]->ip_addr, $addresses[$c-1]->ip_addr)) != 1) {
1804
+				if (gmp_strval(@gmp_sub($addresses[$c]->ip_addr, $addresses[$c - 1]->ip_addr)) != 1) {
1805 1805
 					# remove index flag
1806 1806
 					unset($fIndex);
1807 1807
 					# save IP address
@@ -1809,9 +1809,9 @@  discard block
 block discarded – undo
1809 1809
 					$addresses_formatted[$c]->class = "ip";
1810 1810
 
1811 1811
 					# no gap this -> next
1812
-					if(gmp_strval( @gmp_sub($addresses[$c]->ip_addr, $addresses[$c+1]->ip_addr)) == -1 && $addresses[$c]->state==$state) {
1812
+					if (gmp_strval(@gmp_sub($addresses[$c]->ip_addr, $addresses[$c + 1]->ip_addr)) == -1 && $addresses[$c]->state == $state) {
1813 1813
 						//is state the same?
1814
-						if($addresses[$c]->state==$addresses[$c+1]->state) {
1814
+						if ($addresses[$c]->state == $addresses[$c + 1]->state) {
1815 1815
 							$fIndex = $c;
1816 1816
 							$addresses_formatted[$fIndex]->startIP = $addresses[$c]->ip_addr;
1817 1817
 							$addresses_formatted[$c]->class = "compressed-range";
@@ -1821,9 +1821,9 @@  discard block
 block discarded – undo
1821 1821
 				# no gap between this and previous
1822 1822
 				else {
1823 1823
 					# is state same as previous?
1824
-					if($addresses[$c]->state==$addresses[$c-1]->state && $addresses[$c]->state==$state) {
1825
-						$addresses_formatted[$fIndex]->stopIP = $addresses[$c]->ip_addr;	//adds dhcp state
1826
-						$addresses_formatted[$fIndex]->numHosts = gmp_strval( gmp_add(@gmp_sub($addresses[$c]->ip_addr, $addresses_formatted[$fIndex]->ip_addr),1));	//add number of hosts
1824
+					if ($addresses[$c]->state == $addresses[$c - 1]->state && $addresses[$c]->state == $state) {
1825
+						$addresses_formatted[$fIndex]->stopIP = $addresses[$c]->ip_addr; //adds dhcp state
1826
+						$addresses_formatted[$fIndex]->numHosts = gmp_strval(gmp_add(@gmp_sub($addresses[$c]->ip_addr, $addresses_formatted[$fIndex]->ip_addr), 1)); //add number of hosts
1827 1827
 					}
1828 1828
 					# different state
1829 1829
 					else {
@@ -1833,7 +1833,7 @@  discard block
 block discarded – undo
1833 1833
 						$addresses_formatted[$c] = $addresses[$c];
1834 1834
 						$addresses_formatted[$c]->class = "ip";
1835 1835
 						# check if state is same as next to start range
1836
-						if($addresses[$c]->state==@$addresses[$c+1]->state &&  gmp_strval( @gmp_sub($addresses[$c]->ip_addr, $addresses[$c+1]->ip_addr)) == -1 && $addresses[$c]->state==$state) {
1836
+						if ($addresses[$c]->state == @$addresses[$c + 1]->state && gmp_strval(@gmp_sub($addresses[$c]->ip_addr, $addresses[$c + 1]->ip_addr)) == -1 && $addresses[$c]->state == $state) {
1837 1837
 							$fIndex = $c;
1838 1838
 							$addresses_formatted[$fIndex]->startIP = $addresses[$c]->ip_addr;
1839 1839
 							$addresses_formatted[$c]->class = "compressed-range";
@@ -1858,23 +1858,23 @@  discard block
 block discarded – undo
1858 1858
 	 * @access public
1859 1859
 	 * @return void
1860 1860
 	 */
1861
-	public function find_invalid_addresses () {
1861
+	public function find_invalid_addresses() {
1862 1862
     	// init
1863 1863
     	$false = array();
1864 1864
 		// find unique ids
1865
-		$ids = $this->find_unique_subnetids ();
1866
-		if ($ids===false)										{ return false; }
1865
+		$ids = $this->find_unique_subnetids();
1866
+		if ($ids === false) { return false; }
1867 1867
 
1868 1868
 		// validate
1869 1869
 		foreach ($ids as $id) {
1870
-			if ($this->verify_subnet_id ($id->subnetId)===false) {
1871
-				$false[] = $this->fetch_subnet_addresses ($id->subnetId);
1870
+			if ($this->verify_subnet_id($id->subnetId) === false) {
1871
+				$false[] = $this->fetch_subnet_addresses($id->subnetId);
1872 1872
 			}
1873 1873
 		}
1874 1874
 		// filter
1875 1875
 		$false = array_filter($false);
1876 1876
 		// return
1877
-		return sizeof($false)>0 ? $false : false;
1877
+		return sizeof($false) > 0 ? $false : false;
1878 1878
 	}
1879 1879
 
1880 1880
 	/**
@@ -1883,14 +1883,14 @@  discard block
 block discarded – undo
1883 1883
 	 * @access private
1884 1884
 	 * @return void
1885 1885
 	 */
1886
-	private function find_unique_subnetids () {
1886
+	private function find_unique_subnetids() {
1887 1887
 		try { $res = $this->Database->getObjectsQuery("select distinct(`subnetId`) from `ipaddresses` order by `subnetId` asc;"); }
1888 1888
 		catch (Exception $e) {
1889 1889
 			$this->Result->show("danger", _("Error: ").$e->getMessage());
1890 1890
 			return false;
1891 1891
 		}
1892 1892
 		# return
1893
-		return sizeof($res)>0 ? $res : false;
1893
+		return sizeof($res) > 0 ? $res : false;
1894 1894
 	}
1895 1895
 
1896 1896
 	/**
@@ -1900,14 +1900,14 @@  discard block
 block discarded – undo
1900 1900
 	 * @param mixed $id
1901 1901
 	 * @return void
1902 1902
 	 */
1903
-	private function verify_subnet_id ($id) {
1904
-		try { $res = $this->Database->numObjectsFilter("subnets", "id", $id ); }
1903
+	private function verify_subnet_id($id) {
1904
+		try { $res = $this->Database->numObjectsFilter("subnets", "id", $id); }
1905 1905
 		catch (Exception $e) {
1906 1906
 			$this->Result->show("danger", _("Error: ").$e->getMessage());
1907 1907
 			return false;
1908 1908
 		}
1909 1909
 		# return
1910
-		return $res==0 ? false : true;
1910
+		return $res == 0 ? false : true;
1911 1911
 	}
1912 1912
 
1913 1913
 
@@ -1935,17 +1935,17 @@  discard block
 block discarded – undo
1935 1935
 	 * @param int $subnetId
1936 1936
 	 * @return int permission level
1937 1937
 	 */
1938
-	public function check_permission ($user, $subnetId) {
1938
+	public function check_permission($user, $subnetId) {
1939 1939
 
1940 1940
 		# get all user groups
1941 1941
 		$groups = json_decode($user->groups);
1942 1942
 
1943 1943
 		# if user is admin then return 3, otherwise check
1944
-		if($user->role == "Administrator")	{ return 3; }
1944
+		if ($user->role == "Administrator") { return 3; }
1945 1945
 
1946 1946
     	# object
1947 1947
     	if (!is_object($this->Subnets)) {
1948
-        	$this->Subnets = new Subnets ($this->Database);
1948
+        	$this->Subnets = new Subnets($this->Database);
1949 1949
     	}
1950 1950
         # fetch subnet
1951 1951
         $subnet = $this->Subnets->fetch_subnet("id", $subnetId);
@@ -1953,20 +1953,20 @@  discard block
 block discarded – undo
1953 1953
 		$subnetP = json_decode($subnet->permissions);
1954 1954
 
1955 1955
 		# set section permissions
1956
-		$Section = new Section ($this->Database);
1957
-		$section = $Section->fetch_section ("id", $subnet->sectionId);
1956
+		$Section = new Section($this->Database);
1957
+		$section = $Section->fetch_section("id", $subnet->sectionId);
1958 1958
 		$sectionP = json_decode($section->permissions);
1959 1959
 
1960 1960
 		# default permission
1961 1961
 		$out = 0;
1962 1962
 
1963 1963
 		# for each group check permissions, save highest to $out
1964
-		if(sizeof($sectionP) > 0) {
1965
-			foreach($sectionP as $sk=>$sp) {
1964
+		if (sizeof($sectionP) > 0) {
1965
+			foreach ($sectionP as $sk=>$sp) {
1966 1966
 				# check each group if user is in it and if so check for permissions for that group
1967
-				foreach($groups as $uk=>$up) {
1968
-					if($uk == $sk) {
1969
-						if($sp > $out) { $out = $sp; }
1967
+				foreach ($groups as $uk=>$up) {
1968
+					if ($uk == $sk) {
1969
+						if ($sp > $out) { $out = $sp; }
1970 1970
 					}
1971 1971
 				}
1972 1972
 			}
@@ -1976,18 +1976,18 @@  discard block
 block discarded – undo
1976 1976
 		}
1977 1977
 
1978 1978
 		# if section permission == 0 then return 0
1979
-		if($out == 0) {
1979
+		if ($out == 0) {
1980 1980
 			return 0;
1981 1981
 		}
1982 1982
 		else {
1983 1983
 			$out = 0;
1984 1984
 			# ok, user has section access, check also for any higher access from subnet
1985
-			if(sizeof($subnetP) > 0) {
1986
-				foreach($subnetP as $sk=>$sp) {
1985
+			if (sizeof($subnetP) > 0) {
1986
+				foreach ($subnetP as $sk=>$sp) {
1987 1987
 					# check each group if user is in it and if so check for permissions for that group
1988
-					foreach($groups as $uk=>$up) {
1989
-						if($uk == $sk) {
1990
-							if($sp > $out) { $out = $sp; }
1988
+					foreach ($groups as $uk=>$up) {
1989
+						if ($uk == $sk) {
1990
+							if ($sp > $out) { $out = $sp; }
1991 1991
 						}
1992 1992
 					}
1993 1993
 				}
@@ -2019,12 +2019,12 @@  discard block
 block discarded – undo
2019 2019
 	 * @param mixed $number
2020 2020
 	 * @return void
2021 2021
 	 */
2022
-	public function reformat_number ($number) {
2022
+	public function reformat_number($number) {
2023 2023
 		$length = strlen($number);
2024
-		$pos	= $length - 3;
2024
+		$pos = $length - 3;
2025 2025
 
2026 2026
 		if ($length > 8) {
2027
-			$number = "~". substr($number, 0, $length - $pos) . "&middot;10^<sup>". $pos ."</sup>";
2027
+			$number = "~".substr($number, 0, $length - $pos)."&middot;10^<sup>".$pos."</sup>";
2028 2028
 		}
2029 2029
 		return $number;
2030 2030
 	}
@@ -2053,7 +2053,7 @@  discard block
 block discarded – undo
2053 2053
 	 * @param mixed $address
2054 2054
 	 * @return void
2055 2055
 	 */
2056
-	public function print_nat_link ($all_nats, $all_nats_per_object, $subnet, $address, $type="ipaddress") {
2056
+	public function print_nat_link($all_nats, $all_nats_per_object, $subnet, $address, $type = "ipaddress") {
2057 2057
     	// cast
2058 2058
     	$subnet = (object) $subnet;
2059 2059
     	$address = (object) $address;
@@ -2065,35 +2065,35 @@  discard block
 block discarded – undo
2065 2065
     	$cnt = 0;
2066 2066
 
2067 2067
     	// subnets
2068
-        if(isset($all_nats_per_object['subnets'][$subnet->id])) {
2068
+        if (isset($all_nats_per_object['subnets'][$subnet->id])) {
2069 2069
             foreach ($all_nats_per_object['subnets'][$subnet->id] as $nat) {
2070 2070
                 // set object
2071 2071
                 $n = $all_nats[$nat];
2072 2072
                 // print
2073
-                $html[] = str_replace("'", "\"", $this->print_nat_link_line ($n, false, "subnets", $subnet->id));
2073
+                $html[] = str_replace("'", "\"", $this->print_nat_link_line($n, false, "subnets", $subnet->id));
2074 2074
             }
2075 2075
             $cnt++;
2076 2076
         }
2077 2077
 
2078 2078
     	// addresses
2079
-    	if(isset($all_nats_per_object['ipaddresses'][$address->id])) {
2079
+    	if (isset($all_nats_per_object['ipaddresses'][$address->id])) {
2080 2080
             foreach ($all_nats_per_object['ipaddresses'][$address->id] as $nat) {
2081 2081
                 // set object
2082 2082
                 $n = $all_nats[$nat];
2083 2083
                 // print
2084
-                $html[] = str_replace("'", "\"", $this->print_nat_link_line ($n, false, "ipaddresses", $address->id));
2084
+                $html[] = str_replace("'", "\"", $this->print_nat_link_line($n, false, "ipaddresses", $address->id));
2085 2085
                 $cnt++;
2086 2086
             }
2087 2087
     	}
2088 2088
 
2089 2089
         // print if some
2090
-        if ($cnt>0) {
2090
+        if ($cnt > 0) {
2091 2091
             $html[] = "</table>";
2092
-            if($type=="subnet") {
2093
-                print  " <a href='".create_link("subnets",$subnet->sectionId, $subnet->id, "nat")."' class='btn btn-xs btn-default show_popover fa fa-exchange' style='font-size:11px;margin-top:-3px;padding:1px 3px;' data-toggle='popover' title='"._('Object is Natted')."' data-trigger='hover' data-html='true' data-content='".implode("\n", $html)."'></a>";
2092
+            if ($type == "subnet") {
2093
+                print  " <a href='".create_link("subnets", $subnet->sectionId, $subnet->id, "nat")."' class='btn btn-xs btn-default show_popover fa fa-exchange' style='font-size:11px;margin-top:-3px;padding:1px 3px;' data-toggle='popover' title='"._('Object is Natted')."' data-trigger='hover' data-html='true' data-content='".implode("\n", $html)."'></a>";
2094 2094
             }
2095 2095
             else {
2096
-                print  " <a href='".create_link("subnets",$subnet->sectionId, $subnet->id, "address-details", $address->id, "nat")."' class='btn btn-xs btn-default show_popover fa fa-exchange' style='font-size:11px;margin-top:-3px;padding:1px 3px;' data-toggle='popover' title='"._('Object is Natted')."' data-trigger='hover' data-html='true' data-content='".implode("\n", $html)."'></a>";
2096
+                print  " <a href='".create_link("subnets", $subnet->sectionId, $subnet->id, "address-details", $address->id, "nat")."' class='btn btn-xs btn-default show_popover fa fa-exchange' style='font-size:11px;margin-top:-3px;padding:1px 3px;' data-toggle='popover' title='"._('Object is Natted')."' data-trigger='hover' data-html='true' data-content='".implode("\n", $html)."'></a>";
2097 2097
             }
2098 2098
         }
2099 2099
 	}
@@ -2108,23 +2108,23 @@  discard block
 block discarded – undo
2108 2108
      * @param bool $object_id (default: false)
2109 2109
      * @return void
2110 2110
      */
2111
-    public function print_nat_link_line ($n, $nat_id = false, $object_type = false, $object_id=false) {
2111
+    public function print_nat_link_line($n, $nat_id = false, $object_type = false, $object_id = false) {
2112 2112
         // cast to object to be sure if array provided
2113 2113
         $n = (object) $n;
2114 2114
 
2115 2115
         // translate json to array, links etc
2116
-        $sources      = $this->translate_nat_objects_for_popup ($n->src, $nat_id, false, $object_type, $object_id);
2117
-        $destinations = $this->translate_nat_objects_for_popup ($n->dst, $nat_id, false, $object_type, $object_id);
2116
+        $sources      = $this->translate_nat_objects_for_popup($n->src, $nat_id, false, $object_type, $object_id);
2117
+        $destinations = $this->translate_nat_objects_for_popup($n->dst, $nat_id, false, $object_type, $object_id);
2118 2118
 
2119 2119
         // no src/dst
2120
-        if ($sources===false)
2120
+        if ($sources === false)
2121 2121
             $sources = array("<span class='badge badge1 badge5 alert-danger'>"._("None")."</span>");
2122
-        if ($destinations===false)
2122
+        if ($destinations === false)
2123 2123
             $destinations = array("<span class='badge badge1 badge5 alert-danger'>"._("None")."</span>");
2124 2124
 
2125 2125
 
2126 2126
         // icon
2127
-        $icon =  $n->type=="static" ? "fa-arrows-h" : "fa-long-arrow-right";
2127
+        $icon = $n->type == "static" ? "fa-arrows-h" : "fa-long-arrow-right";
2128 2128
 
2129 2129
         // to html
2130 2130
         $html = array();
@@ -2135,7 +2135,7 @@  discard block
 block discarded – undo
2135 2135
         $html[] = "</tr>";
2136 2136
 
2137 2137
         // append ports
2138
-        if(($n->type=="static" || $n->type=="destination") && (strlen($n->src_port)>0 && strlen($n->dst_port)>0)) {
2138
+        if (($n->type == "static" || $n->type == "destination") && (strlen($n->src_port) > 0 && strlen($n->dst_port) > 0)) {
2139 2139
             $sources      = implode("<br>", $sources)." /".$n->src_port;
2140 2140
             $destinations = implode("<br>", $destinations)." /".$n->dst_port;
2141 2141
         }
@@ -2170,24 +2170,24 @@  discard block
 block discarded – undo
2170 2170
      * @param int|bool object_id (default: false) - to bold it
2171 2171
      * @return void
2172 2172
      */
2173
-    public function translate_nat_objects_for_popup ($json_objects, $nat_id = false, $admin = false, $object_type = false, $object_id=false) {
2173
+    public function translate_nat_objects_for_popup($json_objects, $nat_id = false, $admin = false, $object_type = false, $object_id = false) {
2174 2174
         // to array "subnets"=>array(1,2,3)
2175 2175
         $objects = json_decode($json_objects, true);
2176 2176
         // init out array
2177 2177
         $out = array();
2178 2178
         // check
2179
-        if(is_array($objects)) {
2180
-            if(sizeof($objects)>0) {
2179
+        if (is_array($objects)) {
2180
+            if (sizeof($objects) > 0) {
2181 2181
                 foreach ($objects as $ot=>$ids) {
2182
-                    if (sizeof($ids)>0) {
2182
+                    if (sizeof($ids) > 0) {
2183 2183
                         foreach ($ids as $id) {
2184 2184
                             // fetch
2185 2185
                             $item = $this->fetch_object($ot, "id", $id);
2186
-                            if($item!==false) {
2186
+                            if ($item !== false) {
2187 2187
                                 // bold
2188
-                                $bold = $item->id==$object_id && $ot==$object_type ? "<span class='strong'>" : "<span>";
2188
+                                $bold = $item->id == $object_id && $ot == $object_type ? "<span class='strong'>" : "<span>";
2189 2189
                                 // subnets
2190
-                                if ($ot=="subnets") {
2190
+                                if ($ot == "subnets") {
2191 2191
                                     $out[] = "$bold".$this->transform_address($item->subnet, "dotted")."/".$item->mask."</span></span>";
2192 2192
                                 }
2193 2193
                                 // addresses
@@ -2201,7 +2201,7 @@  discard block
 block discarded – undo
2201 2201
             }
2202 2202
         }
2203 2203
         // result
2204
-        return sizeof($out)>0 ? $out : false;
2204
+        return sizeof($out) > 0 ? $out : false;
2205 2205
     }
2206 2206
 
2207 2207
 }
Please login to merge, or discard this patch.
functions/classes/class.Mail.php 3 patches
Indentation   +272 added lines, -272 removed lines patch added patch discarded remove patch
@@ -11,278 +11,278 @@
 block discarded – undo
11 11
 class phpipam_mail extends Common_functions {
12 12
 
13 13
 
14
-	/**
15
-	 * phpipam settings
16
-	 *
17
-	 * (default value: null)
18
-	 *
19
-	 * @var object|bool
20
-	 * @access public
21
-	 */
22
-	public $settings = null;
23
-
24
-	/**
25
-	 * (obj) mail settings
26
-	 *
27
-	 * (default value: null)
28
-	 *
29
-	 * @var mixed
30
-	 * @access private
31
-	 */
32
-	private $mail_settings = null;
33
-
34
-	/**
35
-	 * Php_mailer object
36
-	 *
37
-	 * @var mixed
38
-	 * @access public
39
-	 */
40
-	public $Php_mailer;
41
-
42
-
43
-
44
-
45
-
46
-
47
-	/**
48
-	 * __construct function.
49
-	 *
50
-	 * @access public
51
-	 * @param mixed $settings
52
-	 */
53
-	public function __construct ($settings, $mail_settings) {
54
-		# set settings and mailsettings
55
-		$this->settings = $settings;
56
-		$this->mail_settings = $mail_settings;
57
-
58
-		# we need phpmailer
59
-		if(file_exists(dirname(__FILE__).'/../PHPMailer/PHPMailerAutoload.php')) {
60
-			// legacy versions
61
-			require_once( dirname(__FILE__).'/../PHPMailer/PHPMailerAutoload.php');
62
-
63
-			# initialize object
64
-			$this->Php_mailer = new PHPMailer(true);			//localhost by default
65
-		}
66
-		elseif (file_exists(dirname(__FILE__).'/../PHPMailer/src/Exception.php')) {
67
-			require_once( dirname(__FILE__).'/../PHPMailer/src/Exception.php');
68
-			require_once( dirname(__FILE__).'/../PHPMailer/src/PHPMailer.php');
69
-			require_once( dirname(__FILE__).'/../PHPMailer/src/SMTP.php');
70
-
71
-			$this->Php_mailer = new PHPMailer\PHPMailer\PHPMailer();
72
-		} else {
73
-			throw new Exception(_('PHPMailer submodule is missing.'));
74
-		}
75
-
76
-		$this->Php_mailer->CharSet="UTF-8";					//set utf8
77
-		$this->Php_mailer->SMTPDebug = 0;					//default no debugging
78
-
79
-		# localhost or smtp?
80
-		if ($this->mail_settings->mtype=="smtp")    { $this->set_smtp(); }
81
-	}
82
-
83
-	/**
84
-	 * Sets SMTP parameters
85
-	 *
86
-	 * @access private
87
-	 * @return void
88
-	 */
89
-	private function set_smtp() {
90
-		//set smtp
91
-		$this->Php_mailer->isSMTP();
92
-		//tls, ssl?
93
-		if($this->mail_settings->msecure!='none') {
94
-			$this->Php_mailer->SMTPAutoTLS = true;
95
-			$this->Php_mailer->SMTPSecure = $this->mail_settings->msecure=='ssl' ? 'ssl' : 'tls';
96
-		}
97
-		else {
98
-			$this->Php_mailer->SMTPAutoTLS = false;
99
-			$this->Php_mailer->SMTPSecure = '';
100
-		}
101
-		//server
102
-		$this->Php_mailer->Host = $this->mail_settings->mserver;
103
-		$this->Php_mailer->Port = $this->mail_settings->mport;
104
-		//permit self-signed certs and dont verify certs
105
-		$this->Php_mailer->SMTPOptions = array("ssl"=>array("verify_peer"=>false, "verify_peer_name"=>false, "allow_self_signed"=>true));
106
-		// uncomment this to disable AUTOTLS if security is set to none
107
-		$this->Php_mailer->SMTPAutoTLS = false;
108
-		//set smtp auth
109
-		$this->set_smtp_auth();
110
-	}
111
-
112
-	/**
113
-	 * Set SMTP login parameters
114
-	 *
115
-	 * @access private
116
-	 * @return void
117
-	 */
118
-	private function set_smtp_auth() {
119
-		if ($this->mail_settings->mauth == "yes") {
120
-			$this->Php_mailer->SMTPAuth = true;
121
-			$this->Php_mailer->Username = $this->mail_settings->muser;
122
-			$this->Php_mailer->Password = $this->mail_settings->mpass;
123
-		} else {
124
-			$this->Php_mailer->SMTPAuth = false;
125
-		}
126
-	}
127
-
128
-	/**
129
-	 * Overrides mail settings in database. For sending test emails.
130
-	 *
131
-	 * @access public
132
-	 * @param mixed $override_settings
133
-	 * @return void
134
-	 */
135
-	public function override_settings($override_settings) {
136
-		foreach ($override_settings as $k=>$s) {
137
-			$this->mail_settings->{$k} = $s;
138
-		}
139
-	}
140
-
141
-	/**
142
-	 * Resets SMTP debugging
143
-	 *
144
-	 * @access public
145
-	 * @param int $level (default: 2)
146
-	 * @return void
147
-	 */
148
-	public function set_debugging ($level = 2) {
149
-		$this->Php_mailer->SMTPDebug = $level == 1 ? 1 : 2;
150
-		// output
151
-		$this->Php_mailer->Debugoutput = 'html';
152
-	}
153
-
154
-
155
-
156
-
157
-
158
-
159
-
160
-
161
-	/**
162
-	 * Generates mail message
163
-	 *
164
-	 * @access public
165
-	 * @param string $body
166
-	 * @return string
167
-	 */
168
-	public function generate_message ($body) {
169
-    	$html = array();
170
-		$html[] = $this->set_header ();			//set header
171
-		$html[] = $this->set_body_start ();		//start body
172
-		$html[] = $body;						//set body
173
-		$html[] = $this->set_footer ();			//set footer
174
-		$html[] = $this->set_body_end ();		//end
175
-		# return
176
-		return implode("\n", $html);
177
-	}
178
-
179
-	/**
180
-	 * Generates plain text mail
181
-	 *
182
-	 * @access public
183
-	 * @param mixed $body
184
-	 * @return void
185
-	 */
186
-	public function generate_message_plain ($body) {
187
-    	$html = array();
188
-		$html[] = $body;						//set body
189
-		$html[] = $this->set_footer_plain ();	//set footer
190
-	}
191
-
192
-	/**
193
-	 * set_header function.
194
-	 *
195
-	 * @access private
196
-	 * @return string
197
-	 */
198
-	private function set_header () {
199
-    	$html = array();
200
-		$html[] = "<!DOCTYPE HTML PUBLIC '-//W3C//DTD HTML 4.01 Transitional//EN' 'http://www.w3.org/TR/html4/loose.dtd'>";
201
-		$html[] = "<html><head>";
202
-		$html[] = "<meta http-equiv='Content-Type' content='text/html; charset=utf-8'>";
203
-		$html[] = "<meta name='viewport' content='width=device-width, initial-scale=0.7, maximum-scale=1, user-scalable=no'>";
204
-		$html[] = "</head>";
205
-		# return
206
-		return implode("\n", $html);
207
-	}
208
-
209
-	/**
210
-	 * Begins message body
211
-	 *
212
-	 * @access private
213
-	 * @return string
214
-	 */
215
-	private function set_body_start () {
216
-		# read config
217
-		require_once( dirname(__FILE__).'/../../config.php');
218
-
219
-		// set width
220
-		$logo_width = isset($config['logo_width']) ? $config['logo_width'] : 220;
221
-
222
-    	$html = array();
223
-    	$html[] = "<body style='margin:0px;padding:0px;background:#f9f9f9;border-collapse:collapse;'>";
224
-    	# logo
225
-    	if(!file_exists( dirname(__FILE__)."/../../css/images/logo/logo.png")) {
226
-			$img = ''; // Load built-in image
227
-			require( dirname(__FILE__).'/../../app/admin/settings/logo/logo-builtin.php' );
228
-			$html[] = $img;
229
-		}
230
-		else {
231
-			$html[] = "<img style='max-width:".$logo_width."px;margin-top:15px;margin-bottom:20px;' alt='phpipam' src='data:image/png;base64,".base64_encode(file_get_contents(dirname(__FILE__)."/../../css/images/logo/logo.png"))."'>";
232
-		}
233
-
234
-		# return
235
-		return implode("\n", $html);
236
-	}
237
-
238
-	/**
239
-	 * Sets message body
240
-	 *
241
-	 * @access public
242
-	 * @param mixed $body
243
-	 * @return void
244
-	 */
245
-	public function set_body ($body) {
246
-		return is_array($body) ? implode("\n", $body) : $body;
247
-	}
248
-
249
-	/**
250
-	 * ends message body and html
251
-	 *
252
-	 * @access private
253
-	 * @return string
254
-	 */
255
-	private function set_body_end () {
256
-		return "</body></html>";
257
-	}
258
-
259
-	/**
260
-	 * Sets footer
261
-	 *
262
-	 * @access public
263
-	 * @return string
264
-	 */
265
-	public function set_footer () {
266
-    	$html = array();
267
-		$html[] = "<hr style='margin-left:10px;width:300px;height:0px;margin-top:40px;margin-left:0px;border-top:0px;border-bottom:1px solid #ddd;'>";
268
-		$html[] = "<div class='padding-left:10px;'>";
269
-		$html[] = "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; $this->mail_font_style_light This email was automatically generated. You can change your notification settings in account details!</font><br>";
270
-		$html[] = "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <a href='".$this->settings->siteURL."' font-size:'11px;'>$this->mail_font_style_href ".$this->settings->siteURL."</font></a><br>";
271
-		$html[] = "</div>";
272
-
273
-		# return
274
-		return implode("\n", $html);
275
-	}
276
-
277
-	/**
278
-	 * Sets plain footer
279
-	 *
280
-	 * @access public
281
-	 * @return string
282
-	 */
283
-	public function set_footer_plain () {
284
-		return "\r\n------------------------------\r\n".$this->settings->siteAdminName." (".$this->settings->siteAdminMail.") :: ".$this->settings->siteURL;
285
-	}
14
+    /**
15
+     * phpipam settings
16
+     *
17
+     * (default value: null)
18
+     *
19
+     * @var object|bool
20
+     * @access public
21
+     */
22
+    public $settings = null;
23
+
24
+    /**
25
+     * (obj) mail settings
26
+     *
27
+     * (default value: null)
28
+     *
29
+     * @var mixed
30
+     * @access private
31
+     */
32
+    private $mail_settings = null;
33
+
34
+    /**
35
+     * Php_mailer object
36
+     *
37
+     * @var mixed
38
+     * @access public
39
+     */
40
+    public $Php_mailer;
41
+
42
+
43
+
44
+
45
+
46
+
47
+    /**
48
+     * __construct function.
49
+     *
50
+     * @access public
51
+     * @param mixed $settings
52
+     */
53
+    public function __construct ($settings, $mail_settings) {
54
+        # set settings and mailsettings
55
+        $this->settings = $settings;
56
+        $this->mail_settings = $mail_settings;
57
+
58
+        # we need phpmailer
59
+        if(file_exists(dirname(__FILE__).'/../PHPMailer/PHPMailerAutoload.php')) {
60
+            // legacy versions
61
+            require_once( dirname(__FILE__).'/../PHPMailer/PHPMailerAutoload.php');
62
+
63
+            # initialize object
64
+            $this->Php_mailer = new PHPMailer(true);			//localhost by default
65
+        }
66
+        elseif (file_exists(dirname(__FILE__).'/../PHPMailer/src/Exception.php')) {
67
+            require_once( dirname(__FILE__).'/../PHPMailer/src/Exception.php');
68
+            require_once( dirname(__FILE__).'/../PHPMailer/src/PHPMailer.php');
69
+            require_once( dirname(__FILE__).'/../PHPMailer/src/SMTP.php');
70
+
71
+            $this->Php_mailer = new PHPMailer\PHPMailer\PHPMailer();
72
+        } else {
73
+            throw new Exception(_('PHPMailer submodule is missing.'));
74
+        }
75
+
76
+        $this->Php_mailer->CharSet="UTF-8";					//set utf8
77
+        $this->Php_mailer->SMTPDebug = 0;					//default no debugging
78
+
79
+        # localhost or smtp?
80
+        if ($this->mail_settings->mtype=="smtp")    { $this->set_smtp(); }
81
+    }
82
+
83
+    /**
84
+     * Sets SMTP parameters
85
+     *
86
+     * @access private
87
+     * @return void
88
+     */
89
+    private function set_smtp() {
90
+        //set smtp
91
+        $this->Php_mailer->isSMTP();
92
+        //tls, ssl?
93
+        if($this->mail_settings->msecure!='none') {
94
+            $this->Php_mailer->SMTPAutoTLS = true;
95
+            $this->Php_mailer->SMTPSecure = $this->mail_settings->msecure=='ssl' ? 'ssl' : 'tls';
96
+        }
97
+        else {
98
+            $this->Php_mailer->SMTPAutoTLS = false;
99
+            $this->Php_mailer->SMTPSecure = '';
100
+        }
101
+        //server
102
+        $this->Php_mailer->Host = $this->mail_settings->mserver;
103
+        $this->Php_mailer->Port = $this->mail_settings->mport;
104
+        //permit self-signed certs and dont verify certs
105
+        $this->Php_mailer->SMTPOptions = array("ssl"=>array("verify_peer"=>false, "verify_peer_name"=>false, "allow_self_signed"=>true));
106
+        // uncomment this to disable AUTOTLS if security is set to none
107
+        $this->Php_mailer->SMTPAutoTLS = false;
108
+        //set smtp auth
109
+        $this->set_smtp_auth();
110
+    }
111
+
112
+    /**
113
+     * Set SMTP login parameters
114
+     *
115
+     * @access private
116
+     * @return void
117
+     */
118
+    private function set_smtp_auth() {
119
+        if ($this->mail_settings->mauth == "yes") {
120
+            $this->Php_mailer->SMTPAuth = true;
121
+            $this->Php_mailer->Username = $this->mail_settings->muser;
122
+            $this->Php_mailer->Password = $this->mail_settings->mpass;
123
+        } else {
124
+            $this->Php_mailer->SMTPAuth = false;
125
+        }
126
+    }
127
+
128
+    /**
129
+     * Overrides mail settings in database. For sending test emails.
130
+     *
131
+     * @access public
132
+     * @param mixed $override_settings
133
+     * @return void
134
+     */
135
+    public function override_settings($override_settings) {
136
+        foreach ($override_settings as $k=>$s) {
137
+            $this->mail_settings->{$k} = $s;
138
+        }
139
+    }
140
+
141
+    /**
142
+     * Resets SMTP debugging
143
+     *
144
+     * @access public
145
+     * @param int $level (default: 2)
146
+     * @return void
147
+     */
148
+    public function set_debugging ($level = 2) {
149
+        $this->Php_mailer->SMTPDebug = $level == 1 ? 1 : 2;
150
+        // output
151
+        $this->Php_mailer->Debugoutput = 'html';
152
+    }
153
+
154
+
155
+
156
+
157
+
158
+
159
+
160
+
161
+    /**
162
+     * Generates mail message
163
+     *
164
+     * @access public
165
+     * @param string $body
166
+     * @return string
167
+     */
168
+    public function generate_message ($body) {
169
+        $html = array();
170
+        $html[] = $this->set_header ();			//set header
171
+        $html[] = $this->set_body_start ();		//start body
172
+        $html[] = $body;						//set body
173
+        $html[] = $this->set_footer ();			//set footer
174
+        $html[] = $this->set_body_end ();		//end
175
+        # return
176
+        return implode("\n", $html);
177
+    }
178
+
179
+    /**
180
+     * Generates plain text mail
181
+     *
182
+     * @access public
183
+     * @param mixed $body
184
+     * @return void
185
+     */
186
+    public function generate_message_plain ($body) {
187
+        $html = array();
188
+        $html[] = $body;						//set body
189
+        $html[] = $this->set_footer_plain ();	//set footer
190
+    }
191
+
192
+    /**
193
+     * set_header function.
194
+     *
195
+     * @access private
196
+     * @return string
197
+     */
198
+    private function set_header () {
199
+        $html = array();
200
+        $html[] = "<!DOCTYPE HTML PUBLIC '-//W3C//DTD HTML 4.01 Transitional//EN' 'http://www.w3.org/TR/html4/loose.dtd'>";
201
+        $html[] = "<html><head>";
202
+        $html[] = "<meta http-equiv='Content-Type' content='text/html; charset=utf-8'>";
203
+        $html[] = "<meta name='viewport' content='width=device-width, initial-scale=0.7, maximum-scale=1, user-scalable=no'>";
204
+        $html[] = "</head>";
205
+        # return
206
+        return implode("\n", $html);
207
+    }
208
+
209
+    /**
210
+     * Begins message body
211
+     *
212
+     * @access private
213
+     * @return string
214
+     */
215
+    private function set_body_start () {
216
+        # read config
217
+        require_once( dirname(__FILE__).'/../../config.php');
218
+
219
+        // set width
220
+        $logo_width = isset($config['logo_width']) ? $config['logo_width'] : 220;
221
+
222
+        $html = array();
223
+        $html[] = "<body style='margin:0px;padding:0px;background:#f9f9f9;border-collapse:collapse;'>";
224
+        # logo
225
+        if(!file_exists( dirname(__FILE__)."/../../css/images/logo/logo.png")) {
226
+            $img = ''; // Load built-in image
227
+            require( dirname(__FILE__).'/../../app/admin/settings/logo/logo-builtin.php' );
228
+            $html[] = $img;
229
+        }
230
+        else {
231
+            $html[] = "<img style='max-width:".$logo_width."px;margin-top:15px;margin-bottom:20px;' alt='phpipam' src='data:image/png;base64,".base64_encode(file_get_contents(dirname(__FILE__)."/../../css/images/logo/logo.png"))."'>";
232
+        }
233
+
234
+        # return
235
+        return implode("\n", $html);
236
+    }
237
+
238
+    /**
239
+     * Sets message body
240
+     *
241
+     * @access public
242
+     * @param mixed $body
243
+     * @return void
244
+     */
245
+    public function set_body ($body) {
246
+        return is_array($body) ? implode("\n", $body) : $body;
247
+    }
248
+
249
+    /**
250
+     * ends message body and html
251
+     *
252
+     * @access private
253
+     * @return string
254
+     */
255
+    private function set_body_end () {
256
+        return "</body></html>";
257
+    }
258
+
259
+    /**
260
+     * Sets footer
261
+     *
262
+     * @access public
263
+     * @return string
264
+     */
265
+    public function set_footer () {
266
+        $html = array();
267
+        $html[] = "<hr style='margin-left:10px;width:300px;height:0px;margin-top:40px;margin-left:0px;border-top:0px;border-bottom:1px solid #ddd;'>";
268
+        $html[] = "<div class='padding-left:10px;'>";
269
+        $html[] = "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; $this->mail_font_style_light This email was automatically generated. You can change your notification settings in account details!</font><br>";
270
+        $html[] = "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <a href='".$this->settings->siteURL."' font-size:'11px;'>$this->mail_font_style_href ".$this->settings->siteURL."</font></a><br>";
271
+        $html[] = "</div>";
272
+
273
+        # return
274
+        return implode("\n", $html);
275
+    }
276
+
277
+    /**
278
+     * Sets plain footer
279
+     *
280
+     * @access public
281
+     * @return string
282
+     */
283
+    public function set_footer_plain () {
284
+        return "\r\n------------------------------\r\n".$this->settings->siteAdminName." (".$this->settings->siteAdminMail.") :: ".$this->settings->siteURL;
285
+    }
286 286
 
287 287
 }
288 288
 
Please login to merge, or discard this patch.
Spacing   +31 added lines, -31 removed lines patch added patch discarded remove patch
@@ -50,34 +50,34 @@  discard block
 block discarded – undo
50 50
 	 * @access public
51 51
 	 * @param mixed $settings
52 52
 	 */
53
-	public function __construct ($settings, $mail_settings) {
53
+	public function __construct($settings, $mail_settings) {
54 54
 		# set settings and mailsettings
55 55
 		$this->settings = $settings;
56 56
 		$this->mail_settings = $mail_settings;
57 57
 
58 58
 		# we need phpmailer
59
-		if(file_exists(dirname(__FILE__).'/../PHPMailer/PHPMailerAutoload.php')) {
59
+		if (file_exists(dirname(__FILE__).'/../PHPMailer/PHPMailerAutoload.php')) {
60 60
 			// legacy versions
61
-			require_once( dirname(__FILE__).'/../PHPMailer/PHPMailerAutoload.php');
61
+			require_once(dirname(__FILE__).'/../PHPMailer/PHPMailerAutoload.php');
62 62
 
63 63
 			# initialize object
64
-			$this->Php_mailer = new PHPMailer(true);			//localhost by default
64
+			$this->Php_mailer = new PHPMailer(true); //localhost by default
65 65
 		}
66 66
 		elseif (file_exists(dirname(__FILE__).'/../PHPMailer/src/Exception.php')) {
67
-			require_once( dirname(__FILE__).'/../PHPMailer/src/Exception.php');
68
-			require_once( dirname(__FILE__).'/../PHPMailer/src/PHPMailer.php');
69
-			require_once( dirname(__FILE__).'/../PHPMailer/src/SMTP.php');
67
+			require_once(dirname(__FILE__).'/../PHPMailer/src/Exception.php');
68
+			require_once(dirname(__FILE__).'/../PHPMailer/src/PHPMailer.php');
69
+			require_once(dirname(__FILE__).'/../PHPMailer/src/SMTP.php');
70 70
 
71 71
 			$this->Php_mailer = new PHPMailer\PHPMailer\PHPMailer();
72 72
 		} else {
73 73
 			throw new Exception(_('PHPMailer submodule is missing.'));
74 74
 		}
75 75
 
76
-		$this->Php_mailer->CharSet="UTF-8";					//set utf8
77
-		$this->Php_mailer->SMTPDebug = 0;					//default no debugging
76
+		$this->Php_mailer->CharSet = "UTF-8"; //set utf8
77
+		$this->Php_mailer->SMTPDebug = 0; //default no debugging
78 78
 
79 79
 		# localhost or smtp?
80
-		if ($this->mail_settings->mtype=="smtp")    { $this->set_smtp(); }
80
+		if ($this->mail_settings->mtype == "smtp") { $this->set_smtp(); }
81 81
 	}
82 82
 
83 83
 	/**
@@ -90,9 +90,9 @@  discard block
 block discarded – undo
90 90
 		//set smtp
91 91
 		$this->Php_mailer->isSMTP();
92 92
 		//tls, ssl?
93
-		if($this->mail_settings->msecure!='none') {
93
+		if ($this->mail_settings->msecure != 'none') {
94 94
 			$this->Php_mailer->SMTPAutoTLS = true;
95
-			$this->Php_mailer->SMTPSecure = $this->mail_settings->msecure=='ssl' ? 'ssl' : 'tls';
95
+			$this->Php_mailer->SMTPSecure = $this->mail_settings->msecure == 'ssl' ? 'ssl' : 'tls';
96 96
 		}
97 97
 		else {
98 98
 			$this->Php_mailer->SMTPAutoTLS = false;
@@ -145,7 +145,7 @@  discard block
 block discarded – undo
145 145
 	 * @param int $level (default: 2)
146 146
 	 * @return void
147 147
 	 */
148
-	public function set_debugging ($level = 2) {
148
+	public function set_debugging($level = 2) {
149 149
 		$this->Php_mailer->SMTPDebug = $level == 1 ? 1 : 2;
150 150
 		// output
151 151
 		$this->Php_mailer->Debugoutput = 'html';
@@ -165,13 +165,13 @@  discard block
 block discarded – undo
165 165
 	 * @param string $body
166 166
 	 * @return string
167 167
 	 */
168
-	public function generate_message ($body) {
168
+	public function generate_message($body) {
169 169
     	$html = array();
170
-		$html[] = $this->set_header ();			//set header
171
-		$html[] = $this->set_body_start ();		//start body
172
-		$html[] = $body;						//set body
173
-		$html[] = $this->set_footer ();			//set footer
174
-		$html[] = $this->set_body_end ();		//end
170
+		$html[] = $this->set_header(); //set header
171
+		$html[] = $this->set_body_start(); //start body
172
+		$html[] = $body; //set body
173
+		$html[] = $this->set_footer(); //set footer
174
+		$html[] = $this->set_body_end(); //end
175 175
 		# return
176 176
 		return implode("\n", $html);
177 177
 	}
@@ -183,10 +183,10 @@  discard block
 block discarded – undo
183 183
 	 * @param mixed $body
184 184
 	 * @return void
185 185
 	 */
186
-	public function generate_message_plain ($body) {
186
+	public function generate_message_plain($body) {
187 187
     	$html = array();
188
-		$html[] = $body;						//set body
189
-		$html[] = $this->set_footer_plain ();	//set footer
188
+		$html[] = $body; //set body
189
+		$html[] = $this->set_footer_plain(); //set footer
190 190
 	}
191 191
 
192 192
 	/**
@@ -195,7 +195,7 @@  discard block
 block discarded – undo
195 195
 	 * @access private
196 196
 	 * @return string
197 197
 	 */
198
-	private function set_header () {
198
+	private function set_header() {
199 199
     	$html = array();
200 200
 		$html[] = "<!DOCTYPE HTML PUBLIC '-//W3C//DTD HTML 4.01 Transitional//EN' 'http://www.w3.org/TR/html4/loose.dtd'>";
201 201
 		$html[] = "<html><head>";
@@ -212,9 +212,9 @@  discard block
 block discarded – undo
212 212
 	 * @access private
213 213
 	 * @return string
214 214
 	 */
215
-	private function set_body_start () {
215
+	private function set_body_start() {
216 216
 		# read config
217
-		require_once( dirname(__FILE__).'/../../config.php');
217
+		require_once(dirname(__FILE__).'/../../config.php');
218 218
 
219 219
 		// set width
220 220
 		$logo_width = isset($config['logo_width']) ? $config['logo_width'] : 220;
@@ -222,9 +222,9 @@  discard block
 block discarded – undo
222 222
     	$html = array();
223 223
     	$html[] = "<body style='margin:0px;padding:0px;background:#f9f9f9;border-collapse:collapse;'>";
224 224
     	# logo
225
-    	if(!file_exists( dirname(__FILE__)."/../../css/images/logo/logo.png")) {
225
+    	if (!file_exists(dirname(__FILE__)."/../../css/images/logo/logo.png")) {
226 226
 			$img = ''; // Load built-in image
227
-			require( dirname(__FILE__).'/../../app/admin/settings/logo/logo-builtin.php' );
227
+			require(dirname(__FILE__).'/../../app/admin/settings/logo/logo-builtin.php');
228 228
 			$html[] = $img;
229 229
 		}
230 230
 		else {
@@ -242,7 +242,7 @@  discard block
 block discarded – undo
242 242
 	 * @param mixed $body
243 243
 	 * @return void
244 244
 	 */
245
-	public function set_body ($body) {
245
+	public function set_body($body) {
246 246
 		return is_array($body) ? implode("\n", $body) : $body;
247 247
 	}
248 248
 
@@ -252,7 +252,7 @@  discard block
 block discarded – undo
252 252
 	 * @access private
253 253
 	 * @return string
254 254
 	 */
255
-	private function set_body_end () {
255
+	private function set_body_end() {
256 256
 		return "</body></html>";
257 257
 	}
258 258
 
@@ -262,7 +262,7 @@  discard block
 block discarded – undo
262 262
 	 * @access public
263 263
 	 * @return string
264 264
 	 */
265
-	public function set_footer () {
265
+	public function set_footer() {
266 266
     	$html = array();
267 267
 		$html[] = "<hr style='margin-left:10px;width:300px;height:0px;margin-top:40px;margin-left:0px;border-top:0px;border-bottom:1px solid #ddd;'>";
268 268
 		$html[] = "<div class='padding-left:10px;'>";
@@ -280,7 +280,7 @@  discard block
 block discarded – undo
280 280
 	 * @access public
281 281
 	 * @return string
282 282
 	 */
283
-	public function set_footer_plain () {
283
+	public function set_footer_plain() {
284 284
 		return "\r\n------------------------------\r\n".$this->settings->siteAdminName." (".$this->settings->siteAdminMail.") :: ".$this->settings->siteURL;
285 285
 	}
286 286
 
Please login to merge, or discard this patch.
Braces   +4 added lines, -2 removed lines patch added patch discarded remove patch
@@ -69,7 +69,8 @@  discard block
 block discarded – undo
69 69
 			require_once( dirname(__FILE__).'/../PHPMailer/src/SMTP.php');
70 70
 
71 71
 			$this->Php_mailer = new PHPMailer\PHPMailer\PHPMailer();
72
-		} else {
72
+		}
73
+		else {
73 74
 			throw new Exception(_('PHPMailer submodule is missing.'));
74 75
 		}
75 76
 
@@ -120,7 +121,8 @@  discard block
 block discarded – undo
120 121
 			$this->Php_mailer->SMTPAuth = true;
121 122
 			$this->Php_mailer->Username = $this->mail_settings->muser;
122 123
 			$this->Php_mailer->Password = $this->mail_settings->mpass;
123
-		} else {
124
+		}
125
+		else {
124 126
 			$this->Php_mailer->SMTPAuth = false;
125 127
 		}
126 128
 	}
Please login to merge, or discard this patch.
app/subnets/addresses/mail-notify-check.php 2 patches
Indentation   +35 added lines, -35 removed lines patch added patch discarded remove patch
@@ -20,54 +20,54 @@
 block discarded – undo
20 20
 
21 21
 # verify each recipient
22 22
 foreach (explode(",", $_POST['recipients']) as $rec) {
23
-	if(!filter_var(trim($rec), FILTER_VALIDATE_EMAIL)) {
24
-		$Result->show("danger", _("Invalid email address")." - ".$rec, true);
25
-	}
23
+    if(!filter_var(trim($rec), FILTER_VALIDATE_EMAIL)) {
24
+        $Result->show("danger", _("Invalid email address")." - ".$rec, true);
25
+    }
26 26
 }
27 27
 # strip html tags
28 28
 $_POST = $Tools->strip_input_tags($_POST);
29 29
 
30 30
 # try to send
31 31
 try {
32
-	# fetch mailer settings
33
-	$mail_settings = $Tools->fetch_object("settingsMail", "id", 1);
32
+    # fetch mailer settings
33
+    $mail_settings = $Tools->fetch_object("settingsMail", "id", 1);
34 34
 
35
-	# initialize mailer
36
-	$phpipam_mail = new phpipam_mail($User->settings, $mail_settings);
35
+    # initialize mailer
36
+    $phpipam_mail = new phpipam_mail($User->settings, $mail_settings);
37 37
 
38
-	// set subject
39
-	$subject	= $_POST['subject'];
38
+    // set subject
39
+    $subject	= $_POST['subject'];
40 40
 
41
-	// set html content
42
-	$content[] = "<table style='margin-left:10px;margin-top:5px;width:auto;padding:0px;border-collapse:collapse;'>";
43
-	$content[] = "<tr><td style='padding:5px;margin:0px;border-bottom:1px solid #eeeeee;'>$User->mail_font_style<strong>$subject</strong></font></td></tr>";
44
-	foreach(explode("\r\n", $_POST['content']) as $c) {
45
-	$content[] = "<tr><td style='padding-left:15px;margin:0px;'>$User->mail_font_style $c</font></td></tr>";
46
-	}
47
-	$content[] = "<tr><td style='padding-left:15px;padding-top:20px;margin:0px;font-style:italic;'>$User->mail_font_style_light Sent by user ".$User->user->real_name." at ".date('Y/m/d H:i')."</font></td></tr>";
48
-	//set al content
49
-	$content_plain[] = "$subject"."\r\n------------------------------\r\n";
50
-	$content_plain[] = str_replace("&middot;", "\t - ", $_POST['content']);
51
-	$content_plain[] = "\r\n\r\n"._("Sent by user")." ".$User->user->real_name." at ".date('Y/m/d H:i');
52
-	$content[] = "</table>";
41
+    // set html content
42
+    $content[] = "<table style='margin-left:10px;margin-top:5px;width:auto;padding:0px;border-collapse:collapse;'>";
43
+    $content[] = "<tr><td style='padding:5px;margin:0px;border-bottom:1px solid #eeeeee;'>$User->mail_font_style<strong>$subject</strong></font></td></tr>";
44
+    foreach(explode("\r\n", $_POST['content']) as $c) {
45
+    $content[] = "<tr><td style='padding-left:15px;margin:0px;'>$User->mail_font_style $c</font></td></tr>";
46
+    }
47
+    $content[] = "<tr><td style='padding-left:15px;padding-top:20px;margin:0px;font-style:italic;'>$User->mail_font_style_light Sent by user ".$User->user->real_name." at ".date('Y/m/d H:i')."</font></td></tr>";
48
+    //set al content
49
+    $content_plain[] = "$subject"."\r\n------------------------------\r\n";
50
+    $content_plain[] = str_replace("&middot;", "\t - ", $_POST['content']);
51
+    $content_plain[] = "\r\n\r\n"._("Sent by user")." ".$User->user->real_name." at ".date('Y/m/d H:i');
52
+    $content[] = "</table>";
53 53
 
54
-	// set alt content
55
-	$content 		= $phpipam_mail->generate_message (implode("\r\n", $content));
56
-	$content_plain 	= implode("\r\n",$content_plain);
54
+    // set alt content
55
+    $content 		= $phpipam_mail->generate_message (implode("\r\n", $content));
56
+    $content_plain 	= implode("\r\n",$content_plain);
57 57
 
58
-	$phpipam_mail->Php_mailer->setFrom($mail_settings->mAdminMail, $mail_settings->mAdminName);
59
-	foreach(explode(",", $_POST['recipients']) as $r) {
60
-	$phpipam_mail->Php_mailer->addAddress(addslashes(trim($r)));
61
-	}
62
-	$phpipam_mail->Php_mailer->Subject = $subject;
63
-	$phpipam_mail->Php_mailer->msgHTML($content);
64
-	$phpipam_mail->Php_mailer->AltBody = $content_plain;
65
-	//send
66
-	$phpipam_mail->Php_mailer->send();
58
+    $phpipam_mail->Php_mailer->setFrom($mail_settings->mAdminMail, $mail_settings->mAdminName);
59
+    foreach(explode(",", $_POST['recipients']) as $r) {
60
+    $phpipam_mail->Php_mailer->addAddress(addslashes(trim($r)));
61
+    }
62
+    $phpipam_mail->Php_mailer->Subject = $subject;
63
+    $phpipam_mail->Php_mailer->msgHTML($content);
64
+    $phpipam_mail->Php_mailer->AltBody = $content_plain;
65
+    //send
66
+    $phpipam_mail->Php_mailer->send();
67 67
 } catch (phpmailerException $e) {
68
-	$Result->show("danger", "Mailer Error: ".$e->errorMessage(), true);
68
+    $Result->show("danger", "Mailer Error: ".$e->errorMessage(), true);
69 69
 } catch (Exception $e) {
70
-	$Result->show("danger", "Mailer Error: ".$e->getMessage(), true);
70
+    $Result->show("danger", "Mailer Error: ".$e->getMessage(), true);
71 71
 }
72 72
 
73 73
 # all good
Please login to merge, or discard this patch.
Spacing   +13 added lines, -13 removed lines patch added patch discarded remove patch
@@ -5,22 +5,22 @@  discard block
 block discarded – undo
5 5
  *************************************************/
6 6
 
7 7
 # include required scripts
8
-require_once( dirname(__FILE__) . '/../../../functions/functions.php' );
8
+require_once(dirname(__FILE__).'/../../../functions/functions.php');
9 9
 
10 10
 # initialize required objects
11
-$Database 	= new Database_PDO;
12
-$Result		= new Result;
13
-$User		= new User ($Database);
14
-$Tools		= new Tools ($Database);
11
+$Database = new Database_PDO;
12
+$Result = new Result;
13
+$User = new User($Database);
14
+$Tools = new Tools($Database);
15 15
 
16
-$User->Crypto->csrf_cookie ("validate", "mail_notify", $_POST['csrf_cookie']) === false ? $Result->show("danger", _("Invalid CSRF cookie"), true) : "";
16
+$User->Crypto->csrf_cookie("validate", "mail_notify", $_POST['csrf_cookie']) === false ? $Result->show("danger", _("Invalid CSRF cookie"), true) : "";
17 17
 
18 18
 # verify that user is logged in
19 19
 $User->check_user_session();
20 20
 
21 21
 # verify each recipient
22 22
 foreach (explode(",", $_POST['recipients']) as $rec) {
23
-	if(!filter_var(trim($rec), FILTER_VALIDATE_EMAIL)) {
23
+	if (!filter_var(trim($rec), FILTER_VALIDATE_EMAIL)) {
24 24
 		$Result->show("danger", _("Invalid email address")." - ".$rec, true);
25 25
 	}
26 26
 }
@@ -36,12 +36,12 @@  discard block
 block discarded – undo
36 36
 	$phpipam_mail = new phpipam_mail($User->settings, $mail_settings);
37 37
 
38 38
 	// set subject
39
-	$subject	= $_POST['subject'];
39
+	$subject = $_POST['subject'];
40 40
 
41 41
 	// set html content
42 42
 	$content[] = "<table style='margin-left:10px;margin-top:5px;width:auto;padding:0px;border-collapse:collapse;'>";
43 43
 	$content[] = "<tr><td style='padding:5px;margin:0px;border-bottom:1px solid #eeeeee;'>$User->mail_font_style<strong>$subject</strong></font></td></tr>";
44
-	foreach(explode("\r\n", $_POST['content']) as $c) {
44
+	foreach (explode("\r\n", $_POST['content']) as $c) {
45 45
 	$content[] = "<tr><td style='padding-left:15px;margin:0px;'>$User->mail_font_style $c</font></td></tr>";
46 46
 	}
47 47
 	$content[] = "<tr><td style='padding-left:15px;padding-top:20px;margin:0px;font-style:italic;'>$User->mail_font_style_light Sent by user ".$User->user->real_name." at ".date('Y/m/d H:i')."</font></td></tr>";
@@ -52,11 +52,11 @@  discard block
 block discarded – undo
52 52
 	$content[] = "</table>";
53 53
 
54 54
 	// set alt content
55
-	$content 		= $phpipam_mail->generate_message (implode("\r\n", $content));
56
-	$content_plain 	= implode("\r\n",$content_plain);
55
+	$content 		= $phpipam_mail->generate_message(implode("\r\n", $content));
56
+	$content_plain = implode("\r\n", $content_plain);
57 57
 
58 58
 	$phpipam_mail->Php_mailer->setFrom($mail_settings->mAdminMail, $mail_settings->mAdminName);
59
-	foreach(explode(",", $_POST['recipients']) as $r) {
59
+	foreach (explode(",", $_POST['recipients']) as $r) {
60 60
 	$phpipam_mail->Php_mailer->addAddress(addslashes(trim($r)));
61 61
 	}
62 62
 	$phpipam_mail->Php_mailer->Subject = $subject;
@@ -71,5 +71,5 @@  discard block
 block discarded – undo
71 71
 }
72 72
 
73 73
 # all good
74
-$Result->show("success", _('Sending mail succeeded')."!" , true);
74
+$Result->show("success", _('Sending mail succeeded')."!", true);
75 75
 ?>
76 76
\ No newline at end of file
Please login to merge, or discard this patch.