1<?php
2
3/*
4 * Discover new vlans with snmp
5 *******************************/
6
7/* functions */
8require_once( dirname(__FILE__) . '/../../../functions/functions.php' );
9
10# initialize user object
11$Database 	= new Database_PDO;
12$User 		= new User ($Database);
13$Admin	 	= new Admin ($Database, false);
14$Tools	 	= new Tools ($Database);
15$Result 	= new Result ();
16
17# verify that user is logged in
18$User->check_user_session();
19# check maintaneance mode
20$User->check_maintaneance_mode ();
21# perm check popup
22$User->check_module_permissions ("vlan", 3, true, true);
23# validate csrf cookie
24$User->Crypto->csrf_cookie ("validate", "scan", $_POST['csrf_cookie']) === false ? $Result->show("danger", _("Invalid CSRF cookie"), true) : "";
25
26# fake error
27print "<div class='alert-danger hidden'></div>";
28
29# scan disabled
30if ($User->settings->enableSNMP!="1")           { $Result->show("danger", _("SNMP module disbled"), true); }
31# admin check
32if($User->is_admin()!==true) 	                { $Result->show("danger", _('Admin privileges required'), true); }
33
34# set class
35$Snmp = new phpipamSNMP ();
36
37# domain Id must be int
38if (!is_numeric($_POST['domainId']))            { $Result->show("danger", _("Invalid domain Id"), true); }
39# fetch domain
40$domain = $Tools->fetch_object ("vlanDomains", "id", $_POST['domainId']);
41if ($domain===false)                            { $Result->show("danger", _("Invalid domain Id"), true); }
42
43# get existing vlans
44$existing_vlans = $Tools->fetch_multiple_objects ("vlans", "domainId", $domain->id, "vlanId");
45if ($existing_vlans!==false) {
46    foreach ($existing_vlans as $v) {
47        $ex_vlans[$v->number] = $name;
48    }
49}
50
51// no errors
52error_reporting(E_ERROR);
53
54# set devices
55foreach ($_POST as $k=>$p) {
56    if (strpos($k, "device-")!==false) {
57        # fetch device
58        $device = $Tools->fetch_object ("devices", "id", str_replace("device-", "", $k));
59        if ($device !== false) {
60            $scan_devices[] = $device;
61        }
62    }
63}
64
65// if none set die
66if (!isset($scan_devices))                      { $Result->show("danger", _("No devices for SNMP VLAN query available"), true); }
67
68// init result array
69$new_vlans = array();
70
71// ok, we have devices, connect to each device and do query
72foreach ($scan_devices as $d) {
73    // init
74    $Snmp->set_snmp_device ($d);
75    // fetch arp table
76    try {
77        $res = $Snmp->get_query("get_vlan_table");
78        // remove those not in subnet
79        if (is_array($res) && sizeof($res)>0) {
80           // save for debug
81           $debug[$d->hostname]["get_vlan_table"] = $res;
82           // loop and save
83           foreach ($res as $k=>$r) {
84               if (!array_key_exists($k, $new_vlans) && !array_key_exists($k, $ex_vlans) ) {
85                   $new_vlans[$k] = $r;
86               }
87           }
88        }
89     } catch (Exception $e) {
90       // save for debug
91       $debug[$d->hostname]["get_vlan_table"] = $res;
92       $errors[] = $e->getMessage();
93	}
94}
95
96# none and errors
97if(sizeof($new_vlans)==0 && isset($errors)) {
98    $Result->show("info", _("No VLANS found"), false);
99    $Result->show("warning", implode("<hr>", $errors), false);
100}
101# none
102elseif(sizeof($new_vlans)==0) 	                     { $Result->show("info", _("No VLANS found")."!", false); }
103# ok
104else {
105    // fetch custom fields and check for required
106    $required_fields = $Tools->fetch_custom_fields ('vlans');
107    if($required_fields!==false) {
108        foreach ($required_fields as $k=>$f) {
109            if ($f['Null']!="NO") {
110                unset($required_fields[$k]);
111            }
112        }
113    }
114
115    // calculate colspan
116	$colspan = 4 + sizeof(@$required_fields);
117
118
119	//form
120	print "<form name='scan-snmp-vlan-form' class='scan-snmp-arp-form' id='scan-snmp-vlan-form'>";
121	print "<table class='table table-striped table-top table-condensed'>";
122
123	// titles
124	print "<tr>";
125	print "	<th>"._("Number")."</th>";
126	print "	<th>"._("Name")."</th>";
127	print "	<th>"._("Description")."</th>";
128    // custom
129	if (isset($required_fields)) {
130		foreach ($required_fields as $field) {
131            print "<th>"._($field['name'])."</th>";
132		}
133    }
134	print "	<th></th>";
135	print "</tr>";
136
137	// alive
138	$m=0;
139	foreach ($new_vlans as $number=>$name ) {
140        print "<tr class='result$m'>";
141		//number
142		print "<td>$number</td>";
143		//name
144		print "<td>";
145		print "	<input type='text' class='form-control input-sm' name='name$m' value='$name'>";
146		print "	<input type='hidden' name='number$m' value='$number'>";
147		print "	<input type='hidden' name='domainId$m' value='$_POST[domainId]'>";
148
149		print "</td>";
150		//description
151		print "<td>";
152		print "	<input type='text' class='form-control input-sm' name='description$m' value='$name'>";
153		print "</td>";
154		// custom
155		if (isset($required_fields)) {
156    		foreach ($required_fields as $field) {
157    			# replace spaces with |
158    			$field['nameNew'] = str_replace(" ", "___", $field['name']);
159
160    			print '	<td>'. "\n";
161
162    			//set type
163    			if(substr($field['type'], 0,3) == "set" || substr($field['type'], 0,4) == "enum") {
164    				//parse values
165    				$tmp = substr($field['type'], 0,3)=="set" ? explode(",", str_replace(array("set(", ")", "'"), "", $field['type'])) : explode(",", str_replace(array("enum(", ")", "'"), "", $field['type']));
166    				//null
167    				if($field['Null']!="NO") { array_unshift($tmp, ""); }
168
169    				print "<select name='$field[nameNew]$m' class='form-control input-sm input-w-auto' rel='tooltip' data-placement='right' title='$field[Comment]'>";
170    				foreach($tmp as $v) {
171    					if($v==@$address[$field['name']])	{ print "<option value='$v' selected='selected'>$v</option>"; }
172    					else								{ print "<option value='$v'>$v</option>"; }
173    				}
174    				print "</select>";
175    			}
176    			//date and time picker
177    			elseif($field['type'] == "date" || $field['type'] == "datetime") {
178    				// just for first
179    				if($timeP==0) {
180    					print '<link rel="stylesheet" type="text/css" href="css/bootstrap/bootstrap-datetimepicker.min.css?v='.SCRIPT_PREFIX.'">';
181    					print '<script src="js/bootstrap-datetimepicker.min.js?v='.SCRIPT_PREFIX.'"></script>';
182    					print '<script>';
183    					print '$(document).ready(function() {';
184    					//date only
185    					print '	$(".datepicker").datetimepicker( {pickDate: true, pickTime: false, pickSeconds: false });';
186    					//date + time
187    					print '	$(".datetimepicker").datetimepicker( { pickDate: true, pickTime: true } );';
188
189    					print '})';
190    					print '</script>';
191    				}
192    				$timeP++;
193
194    				//set size
195    				if($field['type'] == "date")	{ $size = 10; $class='datepicker';		$format = "yyyy-MM-dd"; }
196    				else							{ $size = 19; $class='datetimepicker';	$format = "yyyy-MM-dd"; }
197
198    				//field
199    				if(!isset($address[$field['name']]))	{ print ' <input type="text" class="'.$class.' form-control input-sm input-w-auto" data-format="'.$format.'" name="'. $field['nameNew'].$m .'" maxlength="'.$size.'" '.$delete.' rel="tooltip" data-placement="right" title="'.$field['Comment'].'">'. "\n"; }
200    				else									{ print ' <input type="text" class="'.$class.' form-control input-sm input-w-auto" data-format="'.$format.'" name="'. $field['nameNew'].$m .'" maxlength="'.$size.'" value="'. $address[$field['name']]. '" '.$delete.' rel="tooltip" data-placement="right" title="'.$field['Comment'].'">'. "\n"; }
201    			}
202    			//boolean
203    			elseif($field['type'] == "tinyint(1)") {
204    				print "<select name='$field[nameNew]$m' class='form-control input-sm input-w-auto' rel='tooltip' data-placement='right' title='$field[Comment]'>";
205    				$tmp = array(0=>"No",1=>"Yes");
206    				//null
207    				if($field['Null']!="NO") { $tmp[2] = ""; }
208
209    				foreach($tmp as $k=>$v) {
210    					if(strlen(@$address[$field['name']])==0 && $k==2)	{ print "<option value='$k' selected='selected'>"._($v)."</option>"; }
211    					elseif($k==@$address[$field['name']])				{ print "<option value='$k' selected='selected'>"._($v)."</option>"; }
212    					else												{ print "<option value='$k'>"._($v)."</option>"; }
213    				}
214    				print "</select>";
215    			}
216    			//default - input field
217    			else {
218    				print ' <input type="text" class="ip_addr form-control input-sm" name="'. $field['nameNew'].$m .'" placeholder="'. $field['name'] .'" value="'. @$address[$field['name']]. '" size="30" '.$delete.' rel="tooltip" data-placement="right" title="'.$field['Comment'].'">'. "\n";
219    			}
220
221                print " </td>";
222    		}
223		}
224		//remove button
225		print 	"<td><a href='' class='btn btn-xs btn-danger resultRemove' data-target='result$m'><i class='fa fa-times'></i></a></td>";
226		print "</tr>";
227
228		$m++;
229	}
230
231	//submit
232	print "<tr>";
233	print "	<td colspan='$colspan'>";
234	print " <div id='vlanScanAddResult'></div>";
235	print "		<a href='' class='btn btn-sm btn-success pull-right' id='saveVlanScanResults' data-script='vlans-scan' data-subnetId='".$_POST['subnetId']."'><i class='fa fa-plus'></i> "._("Add discovered VLANS")."</a>";
236	print "	</td>";
237	print "</tr>";
238
239	print "</table>";
240	print '<input type="hidden" name="csrf_cookie" value="'.$_POST['csrf_cookie'].'">';
241	print "</form>";
242
243    // print errors
244    if (isset($errors)) {
245        print "<hr>";
246        foreach ($errors as $e) {
247            print $Result->show ("warning", $e, false);
248        }
249    }
250}
251
252//print scan method
253print "<div class='text-right' style='margin-top:7px;'>";
254print " <span class='muted'>";
255print " Scan method: SNMP VLAN table<hr>";
256print " Scanned devices: <br>";
257foreach ($debug as $k=>$d) {
258    print "&middot; ".$k."<br>";
259}
260print "</span>";
261print "</div>";
262
263# show debug?
264if($_POST['debug']==1) 				{ print "<pre>"; print_r($debug); print "</pre>"; }