<?php

/*
 * Let you create ports and ip addresses by reading snmp ifTable / ifxTable / ipAdEntIfIndex 
 * If Port name or L2Address already exists the port is not checked for adding.
 *
 * Also bind ip addresses to Object if not already allocated.
 * 
 * Let you select the interfaces, ip address and attributes to be created / set.
 *
 * Won't add anything until "Create Ports and IPs" pressed!
 * 
 *
 * Tested only with some Enterasys switches C/B and S !!!!
 *	cisco 2620XM (thx to Rob)
 * 
 * 
 * 
 * TESTED on FreeBSD 8.2, nginx/1.0.8, php 5.3.8, NET-SNMP 5.7
 *
 * (c)2012 Maik Ehinger <m.ehinger@ltur.de>
 */

/****
 * INSTALL
 *
 * add to local.php
 *	include 'inc/snmpgeneric.php';
 * 
 */

/* TODOs
 * 
 *  - code cleanup
 *  - test and finalize SNMP v3 support
 *
 *  - set more Object attributs / fields
 *  
 */

/*************************
 * Change Log
 * 
 * 09.12.11	minor cleanups
 * 10.02.12	make host selectable
 * 16.02.12	use getConfigVar('DEFAULT_SNMP_COMMUNITY');
 *		make snmp port types ignorable (see ifType2oif_id array)
 *		add create_noconnector_ports
 * 17.02.12	changed operator & to &&
 *		make attributes, add port, add ip and port type changeable before create
 *		add sg_oid2attr
 *		add trigger (prepared only)
 *		add ifType_ignore
 * 19.02.12	add ifAlias to visible label 
 *		allow ifName input if empty (preset with ifDescr)
 * 20.02.12 	change attribute code
 *		add $sg_known_sysObjectIDs (set to $known_switches from snmp.php) to set HW Type
 * 		added attribute processor function code
 * 21.02.12	add vendor / device specific ports
 *		change processor function code
 *			allow to return attributes and ports
 *		add check / uncheck all (doesn't work with IE)
 *		hide snmpv3 settings if not needed
 *		add ifInOctets and ifOutOctets to interface list
 * 22.02.12	add hrefs to l2address and ipaddr
 *
 */

require_once('snmp.php');

$tab['object']['snmpgeneric'] = 'SNMP Generic sync';
$tabhandler['object']['snmpgeneric'] = 'snmpgeneric_tabhandler';
//$trigger['object']['snmpgeneric'] = 'snmpgeneric_tabtrigger';

$ophandler['object']['snmpgeneric']['create'] = 'snmpgeneric_opcreate';

/* create ports without connector */
$sg_create_noconnector_ports = FALSE;

/* deselect add port for this snmp port types */
$ifType_ignore = array(
	  '1',	/* other */
	 '24',	/* softwareLoopback */
	 '33',	/*  rs232 */
	 '34', 	/* para */
	 '53',	/* propVirtual */
	'131',	/* tunnel */
	'136',	/* l3ipvlan */
	'160',	/* usb */
	'161',	/* ieee8023adLag */
);

/* ifType to RT oif_id mapping */
$ifType2oif_id = array(
	/* 440 causes SQLSTATE[23000]: Integrity constraint violation:
	 *				 1452 Cannot add or update a child row: 
	 *					a foreign key constraint fails
	 */
	//  '1' => 440,	/* other => unknown 440 */
	  '1' => 1469,	/* other => virutal port 1469 */
	  '6' => 24, 	/* ethernetCsmacd => 1000BASE-T 24 */
	 '24' => 1469,	/* softwareLoopback => virtual port 1469 */
	 '33' => 1469,	/*  rs232 => RS-232 (DB-9) 681 */
	 '34' => 1469, 	/* para => virtual port 1469 */
	 '53' => 1469,	/* propVirtual => virtual port 1469 */
	 '62' => 1195,	/* fastEther => 100BASE-FX 1195 */
	'131' => 1469,	/* tunnel => virtual port 1469 */
	'136' => 1469,	/* l3ipvlan => virtual port 1469 */
	'160' => 1469,	/* usb => virtual port 1469 */
	'161' => 1469,	/* ieee8023adLag => virtual port 1469 */
);

/* -------------------------------------------------- */

/* use $known_switches dict_key for HW Type attrib from snmp.php */
$sg_known_sysObjectIDs = &$known_switches;

/* overwrite/add known_switches values */
//$sg_known_sysObjectIDs['12325.1.1.2.1.1']['dict_key'] = 1234567; 

/* default attributes */
$sg_known_sysObjectIDs['default'] = array(
	'vendor' => 'unknown',
	'text' => 'default',
	'attr' => array( 'id_2' => array('pf' => 'snmpgeneric_pf_hwtype'), 	/* HW Typ*/
			 'id_3' => array('oid' => 'sysName.0'),			/* FQDN */
			 'id_14' => array('oid' => 'sysContact.0'),		/* Contact person */
			), 
	'port' => array( 
			// 'AC-in' => array('porttypeid' => '1-16'),
			// 'name' => array('porttypeid' => '1-24', 'ifPhysAddress' => '001122334455', 'ifDescr' => 'visiable label'),
			),
);

/* vendor and device array will be merged */
/* snmp vendor list http://www.iana.org/assignments/enterprise-numbers */
/* attributes for vendor */
$sg_known_sysObjectIDs['12325'] = array(
	'vendor' => 'Fraunhofer FOKUS',
);

/* attributes for device */
$sg_known_sysObjectIDs['12325.1.1.2.1.1'] = array(
	'dict_key' => 115,
	'text'	=> 'BSNMP - mini SNMP daemon (bsnmpd)',
);

/* add Vendor specifict stuff */
$sg_known_sysObjectIDs['5624'] = array(
	'vendor' => 'Enterasys',
);

/* add device specific stuff */
$sg_known_sysObjectIDs['5624.2.1.131'] = array(
	'dict_key' => 50001,
	'text' => 'Enterasys Sx',
);

/* -------------------------------------------------- */

$portiifoptions= getPortIIFOptions();
$portiifoptions[-1] = 'sfp'; /* generic sfp */

$portoifoptions= getPortOIOptions();

//function snmpgeneric_tabtrigger() {
//      return 'std';
//}


/* -------------------------------------------------- */

/*
 * Sample Precessing Function (pf)
 *
 * return TRUE to add attr and ports
 * return FALSE do nothing
 *
 */
function snmpgeneric_pf_sample(&$snmp, &$sysObjectID, $attr_id, &$attrs, &$ports) {

	if(!isset($sysObjectID[$attr_id]['oid']))
		return FALSE;


	/* access attribute oid setting and do snmpget */
	$oid = $sysObjectID[$attr_id]['oid'];
	$value = $snmp->get($oid);

	/* set new attribute value */
	$attrs = array(
	 		$attr_id => $value,
		);

	return TRUE;

/* to return ports use */
/*
 *	$ports = array(
 *			'name' => array('porttypeid' => '1-24', 'ifPhysAddress' => '001122334455', 'ifDescr' => 'visible label'),
 *		);
 */

} /* snmpgeneric_pf_sample */

/* -------------------------------------------------- */

/* HW Type processor function */
function snmpgeneric_pf_hwtype(&$snmp, &$sysObjectID, $attr_id, &$attrs, &$ports) {

	if (isset($sysObjectID['dict_key'])) {

		$value = $sysObjectID['dict_key'];
		showSuccess("Found HW type dict_key: $value");
	
		/* return array of attr_id => attr_value) */
		$attrs = array($attr_id => $value);

		return TRUE;

	} else {
		showNotice("HW type dict_key not set");
		return FALSE;
	}

} /* snmpgeneric_pf_hwtype */

/* -------------------------------------------------- */
/* -------------------------------------------------- */

function snmpgeneric_tabhandler($object_id) {

	if(isset($_POST['snmpconfig'])) {
		if($_POST['snmpconfig'] == '1') {
			snmpgeneric_list($object_id);
		}	
	} else {
		snmpgeneric_snmpconfig($object_id);
	}
}

/* -------------------------------------------------- */

function snmpgeneric_snmpconfig($object_id) {

	$object = spotEntity ('object', $object_id);
	//$object['attr'] = getAttrValues($object_id);
        $endpoints = findAllEndpoints ($object_id, $object['name']);

	addJS('function showsnmpv3(element) {
				if(element.value != \''.SNMPgeneric::VERSION_3.'\')
					style = \'none\';
				else
					style = \'\';

				elements = document.getElementsByName(\'snmpv3\');
				for(i=0;i<elements.length;i++) {
					elements[i].style.display=style;
				}
			};',TRUE);

	foreach( $endpoints as $key => $value) {
		$endpoints[$value] = $value;
		unset($endpoints[$key]);
	}

	foreach( getObjectIPv4Allocations($object_id) as $ip => $value) {

		if(!in_array($ip, $endpoints))
			$endpoints[$ip] = $ip;
	}

//	sg_var_dump_html($endpoints);	

	$snmpcomm = getConfigVar('DEFAULT_SNMP_COMMUNITY');
	if(empty($snmpcomm))
		$snmpcomm = mySNMP::SNMP_COMMUNITY;
			
	echo '<h1 align=center>SNMP Config</h1>';
	echo '<p align=center> SNMPv3 untested !!!</p>';
	echo '<form method=post name=snmpconfig action='.$_SERVER['REQUEST_URI'].' />';


        echo '<table cellspacing=0 cellpadding=5 align=center class=widetable>
	<tr><th class=tdright>Host:</th><td>';
	
	echo getSelect ($endpoints, array ('name' => 'host'), NULL, FALSE);

	echo'</td></tr>
        <tr>
                <th class=tdright><label for=snmpversion>Version:</label></th>
                <td class=tdleft><select id="snmpversion" name=version value=v1 onchange="showsnmpv3(this)">
			<option value='.SNMPgeneric::VERSION_1.'>v1</options>
			<option value='.SNMPgeneric::VERSION_2C.' selected>v2c</options>
			<option value='.SNMPgeneric::VERSION_3.'>v3</options>
		</td>
        </tr>
        <tr>
                <th class=tdright><label for=community>Community / Security Name:</label></th>
                <td class=tdleft><input type=text name=community value='.$snmpcomm.' ></td>
        </tr>
        <tr name="snmpv3" style="display:none;">
		<th></th>
                <td class=tdleft><p><label>Fields below are for SNMPv3 only</label></p></td>
        </tr>
        <tr name="snmpv3" style="display:none;">
                <th class=tdright><label">Security Level:</label></th>
                <td class=tdleft><select name="sec_level">
                        <option value="noAuthNoPriv" selected="selected">noAuth and no Priv</option>
                        <option value="authNoPriv" >auth without Priv</option>
                        <option value="authPriv" >auth with Priv</option>
                </select></td>
        </tr>
        <tr name="snmpv3" style="display:none;">
                <th class=tdright><label>Auth Type:</label></th>
                <td class=tdleft>
                <input name=auth_protocol type=radio value=MD5 /><label>MD5</label>
                <input name=auth_protocol type=radio value=SHA /><label>SHA</label>
                </td>
        </tr>
        <tr name="snmpv3" style="display:none;">
                <th class=tdright><label>Auth Key:</label></th>
                <td class=tdleft><input type=text id=auth_passphrase name=auth_passphrase></td>
        </tr>
        <tr name="snmpv3" style="display:none;">
                <th class=tdright><label>Priv Type:</label></th>
                <td class=tdleft>
                <input name=priv_protocol type=radio value=DES /><label>DES</label>
                <input name=priv_protocol type=radio value=AES /><label>AES</label>
                </td>
        </tr>
        <tr name="snmpv3" style="display:none;">
                <th class=tdright><label>Priv Key</label></th>
                <td class=tdleft><input type=text name=priv_passphrase></td>
        </tr>
	</tr>
	<td colspan=2>

        <input type=hidden name=snmpconfig value=1>
	<input type=submit value="Show List"></td></tr>

        </table></form>';

	
}

function snmpgeneric_list($object_id) {

    	global $sg_create_noconnector_ports, $sg_known_sysObjectIDs, $portoifoptions, $ifType_ignore;

	if(isset($_POST['snmpconfig'])) {
		$snmpconfig = $_POST;	
	} else {
		showError("Missing SNMP Config");
		return;
	}

	addJS('function setchecked(classname) { var boxes = document.getElementsByClassName(classname);
				 value = document.getElementById(classname).checked;
				 for(i=0;i<boxes.length;i++) {
					if(boxes[i].disabled == false)
						boxes[i].checked=value;
				 }
		};', TRUE);

	$object = spotEntity ('object', $object_id);
	$object['attr'] = getAttrValues($object_id);

	$snmpdev = new mySNMP($snmpconfig['version'], $snmpconfig['host'], $snmpconfig['community']);

	if($snmpconfig['version'] == SNMPgeneric::VERSION_3 ) {
		$snmpdev->setSecurity( $snmpconfig['sec_level'],
					$snmpconfig['auth_protocol'],
					$snmpconfig['auth_passphrase'],
					$snmpconfig['priv_protocol'],
					$snmpconfig['priv_passphrase']
					);
	}

	if($snmpdev->getErrno()) {
		showError($snmpdev->getError());
		return;
	} else {
		showSuccess("SNMP connect to ${snmpconfig['host']} successfull");
	}

	echo '<form name=CreatePorts method=post action='.$_SERVER['REQUEST_URI'].'&module=redirect&op=create>';

	echo "<table>";
	echo "<tr><th>OID</th><th>Value</th></tr>";
	$systemoids = array('sysDescr', 'sysObjectID', 'sysUpTime', 'sysContact', 'sysName', 'sysLocation');
	foreach ($systemoids as $shortoid) {

		$value = $snmpdev->{$shortoid};

		if($shortoid == 'sysUpTime') {
			/* in hundredths of a second */
			$secs = (int)($value / 100);
			$days = (int)($secs / (60 * 60 * 24));
			$secs -= $days * 60 *60 * 24;
			$hours = (int)($secs / (60 * 60));
			$secs -= $hours * 60 * 60;
			$mins = (int)($secs / (60));
			$secs -= $mins * 60;
			$value = "$value ($days $hours:$mins:$secs)";
		}

		echo "<tr><td>$shortoid</td><td>".$value."</td></tr>";
	}
	echo "</table>";

	/* Attributes */

	echo '<br>Attributes<br><table>';
	echo '<tr><th><input type="checkbox" id="attribute" checked="checked" onclick="setchecked(this.id)"></td>';
	echo '<th>Name</th><th>Current Value</th><th>new value</th></tr>';

	/* set defaults */
	$sysObjectID = $sg_known_sysObjectIDs['default'];
	$attribs = $sysObjectID['attr'];

	if(isset($sysObjectID['port']))
		$ports = $sysObjectID['port'];
	else
		$ports = array();

	/* get sysObjectID and vendor_number */
	$matches;
 	preg_match('/^.*enterprises\.(([[:digit:]]+)\.[\.[:digit:]]+)$/', $snmpdev->sysObjectID, $matches);

	$sysObjectID['raw_value'] = $matches[0];
	$sysObjectID['vendor_number'] = $matches[2];
	$sysObjectID['device_id'] = $matches[1];

	unset($matches);

	/* get vendor attribs */
	if(isset($sg_known_sysObjectIDs[$sysObjectID['vendor_number']])) {
		/* also overwrites ['attr'] */
		$sysObjectID = array_merge($sysObjectID, $sg_known_sysObjectIDs[$sysObjectID['vendor_number']]);

		if(isset($sg_known_sysObjectIDs[$sysObjectID['vendor_number']]['attr']))
			$attribs = array_merge($attribs,$sysObjectID['attr']);

		if(isset($sg_known_sysObjectIDs[$sysObjectID['vendor_number']]['port']))
			$ports = array_merge($ports,$sysObjectID['port']);

		showSuccess("found Vendor (".$sysObjectID['vendor_number'].") ".$sysObjectID['vendor']);
	}

	/* get device attibs */
	if(isset($sg_known_sysObjectIDs[$sysObjectID['device_id']])) {
		/* also overwrites ['attr'] */
		$sysObjectID = array_merge($sysObjectID, $sg_known_sysObjectIDs[$sysObjectID['device_id']]);

		if(isset($sg_known_sysObjectIDs[$sysObjectID['device_id']]['attr']))
			$attribs = array_merge($attribs,$sysObjectID['attr']);
	
		if(isset($sg_known_sysObjectIDs[$sysObjectID['device_id']]['port']))
			$ports = array_merge($ports,$sysObjectID['port']);

		showSuccess("found device (".$sysObjectID['device_id'].") ".$sysObjectID['text']);
	} else
		showNotice('unknown device (sysObjectID: '.$sysObjectID['device_id'].')');

//	sg_var_dump_html($attribs);
//	sg_var_dump_html($ports);

	foreach($attribs as $key => $value) {

		/* merge doesn't work with numeric keys */
		$attr_id = explode('id_',$key);
		$attr_id = $attr_id[1];

		if(isset($object['attr'][$attr_id])) {

			$newattrvalues = array();

			switch(TRUE) {

				case isset($value['oid']):
					$attrvalue = $snmpdev->get($value['oid']);
		 			$newattrvalues = array($attr_id => $attrvalue);	
					break;
				case isset($value['pf']):
					if(function_exists($value['pf'])) {

						$moreports = array();
						$moreattrs = array();

						$retval = $value['pf']($snmpdev, $sysObjectID, $attr_id, $moreattrs, $moreports);

						if($retval) {
							/* preserve numeric keys don't use array_merge */
							$newattrvalues = $moreattrs + $newattrvalues;
							$ports = $moreports + $ports;
						}

					} else {
						showWarning("Missing processor function ".$value['pf']." for attribute $attr_id");
					}

					break;

			}

			/* print attributes */
			foreach($newattrvalues as $newattr_id => $newattr_value) {			

				if(isset($object['attr'][$newattr_id]) && !empty($newattr_value)) {

					$val_key = (isset($object['attr'][$newattr_id]['key']) ? ' ('.$object['attr'][$newattr_id]['key'].')' : '' );

					$updateattrcheckbox = '<b style="background-color:#00ff00"><input style="background-color:#00ff00" class="attribute" type="checkbox" name="updateattr['
							.$newattr_id.']" value="'.$newattr_value.'" checked="checked"></b></td><td>'
							.$object['attr'][$newattr_id]['name'].'</td><td style="background-color:#d8d8d8">'
							.$object['attr'][$newattr_id]['value'].$val_key.'</td><td>'
							.$newattr_value;

					echo "<tr><td>$updateattrcheckbox</td></tr>";
				}
			}
		}

	}


	echo '</table>';

	/* ports */

	$objectports = getPortsNameL2address($object_id);

	$newporttypeoptions = getNewPortTypeOptions();

	if(!empty($ports)) {

		echo '<br>Vendor / Device specific ports<br>';
		echo '<table><tr><th><input type="checkbox" id="moreport" checked="checked" onclick="setchecked(this.id)"></th><th>ifName</th><th>porttypeid</th><th>ifPhysAddress</th><th>ifDescr</th></tr>';
	
		foreach($ports as $name => $port) {

			if(array_key_exists($name,$objectports))
				$disableport = TRUE;
			else
				$disableport = FALSE;

			$portcreatecheckbox = '<b style="background-color:'.($disableport ? '#ff0000' : '#00ff00')
					.'"><input style="background-color:'.($disableport ? '#ff0000' : '#00ff00').'" class="moreport" type="checkbox" name="portcreate['.$name.']" value="'.$name.'"'
					.($disableport ? ' disabled="disbaled"' : ' checked="checked"').'></b>';

			$formfield = '<input type="hidden" name="ifName['.$name.']" value="'.$name.'">';
			echo "<tr>$formfield<td>$portcreatecheckbox</td><td>$name</td>";


			foreach($port as $key => $value) {
	
				if($key == 'porttypeid')
					$displayvalue = getNiftySelect($newporttypeoptions,
							 array('name' => "porttypeid[$name]", 'disabled' => "disabled" ), $value);
											/* disabled formfied won't be submitted ! */
				else 
					$displayvalue = $value;

				$formfield = '<input type="hidden" name="'.$key.'['.$name.']" value="'.$value.'">';
				echo "$formfield<td>$displayvalue</td>";
			}

			echo '</tr>';
		}
		
		echo '</table>';
	}

	/* snmp ports */

	$ifsnmp = new ifSNMP($snmpdev);

	echo "<br><br>ifNumber: ".$ifsnmp->ifNumber."<br>";

	$portcompat = getPortInterfaceCompat();

	$ifsnmp->printifInfoTableHeader("<th>add port</th><th>add ip</th><th>porttypeid</th><th>comment</th></tr>");

	echo '<tr><td colspan="12"></td>
		<td><input type="checkbox" id="ports" onclick="setchecked(this.id)"></td>
		<td><input type="checkbox" id="ipaddr" onclick="setchecked(this.id)"></td></tr>';

	foreach($ifsnmp as $if) {

		$createport = TRUE;
		$disableport = FALSE;
		$ignoreport = FALSE;

		$hrefs = array();

		$comment = "";

		if(trim($ifsnmp->ifName($if)) == '') {
			$comment .= "no ifName";
			$createport = FALSE;
		} else {

			if(array_key_exists($ifsnmp->ifName($if),$objectports)){
				$comment .= "Name exists";
				$createport = FALSE;
				$disableport = TRUE;
			}
		}

		if($ifsnmp->ifPhysAddress($if) != '' ) {

			$l2port =  sg_checkL2Address($ifsnmp->ifPhysAddress($if));

			//if(alreadyUsedL2Address($ifsnmp->ifPhysAddress($if), $object_id)) {

			if(!empty($l2port)) {
				$l2object_id = key($l2port);

				$porthref = makeHref(array('page'=>'object', 'tab' => 'ports',
								 'object_id' => $l2object_id, 'hl_port_id' => $l2port[$l2object_id]));

				$comment .= ", L2Address exists";
				$hrefs['ifPhysAddress'] = $porthref;
				$createport = FALSE;
			//	$disableport = TRUE;
			}
		}


		$porttypeid = guessRToif_id($ifsnmp->ifType($if), $ifsnmp->ifDescr($if));

		if(in_array($ifsnmp->ifType($if),$ifType_ignore)) {
			$comment .= ", ignore if type";
			$createport = FALSE;
			$ignoreport = TRUE;
		}
		
		/* ignore ports without an Connector */
		if(!$sg_create_noconnector_ports && ($ifsnmp->ifConnectorPresent($if) == 2)) {
			$comment .= ", no Connector";
			$createport = FALSE;
		}

		
		/* Allocate IPs */
		$createipaddr = FALSE;		
		$disableipaddr = FALSE;

		$ipaddr = $ifsnmp->ipaddress($if);
	
		if( $ipaddr != '' ) {

			/* TODO getIPAdressNetworkId */

			$address = getIPAddress($ipaddr);

			/* only if ip not already allocated */
			if(empty($address['allocs'])) {
				if(!$ignoreport)
					$createipaddr = TRUE;
			} else {
				$disableipaddr = TRUE;

				$ipobject_id = $address['allocs'][0]['object_id'];

				$ipaddrhref = makeHref(array('page'=>'object',
								 'object_id' => $l2object_id, 'hl_ipv4_addr' => $ipaddr));

				$hrefs['ipaddress'] = $ipaddrhref;
			}
					
			if($ipaddr == '127.0.0.1') {
				$createipaddr = FALSE;
			}
		}
		

		/* checkboxes for add port and add ip */
	 	/* FireFox needs <b style=..>, IE and Opera work with <td style=..> */	
		$portcreatecheckbox = '<b style="background-color:'.($disableport ? '#ff0000' : '#00ff00').'"><input class="ports" style="background-color:'.($disableport ? '#ff0000' : '#00ff00')
					.'" type="checkbox" name="portcreate['.$if.']" value="'.$if.'"'
					.($disableport ? ' disabled="disbaled"' : '').($createport ? ' checked="checked"' : '').'></b>';
		
		if(!empty($ipaddr))
			$ipaddrcreatecheckbox = '<b style="background-color:'.($disableipaddr ? '#ff0000' : '#00ff00').'"><input class="ipaddr" style="background-color:'.($disableipaddr ? '#ff0000' : '#00ff00')
					.'" type="checkbox" name="ipaddrcreate['.$if.']" value="'.$if.'"'
					.($disableipaddr ? ' disabled="disabled"' : '').($createipaddr ? ' checked="checked"' : '').'></b>';
		else
			$ipaddrcreatecheckbox = '';
		
		/* port type id */
		/* add port type to newporttypeoptions if missing */
		if(strpos(serialize($newporttypeoptions),$porttypeid) === FALSE) {

			$portids = explode('-',$porttypeid);
			$oif_name = $portoifoptions[$portids[1]];

			$newporttypeoptions['auto'] = array($porttypeid => "*$oif_name");  
		}

		$selectoptions = array('name' => "porttypeid[$if]");

		if($disableport)
			$selectoptions['disabled'] = "disabled";

		$porttypeidselect = getNiftySelect($newporttypeoptions, $selectoptions, $porttypeid);

		$ifsnmp->printifInfoTableRow($if,"<td>$portcreatecheckbox</td><td>$ipaddrcreatecheckbox</td><td>$porttypeidselect</td><td>$comment</td>", $hrefs);

	}

	echo "</table>";

	/* preserve snmpconfig */
	foreach($_POST as $key => $value) {
		echo '<input type=hidden name='.$key.' value='.$value.' />';
	}

	echo '<p align="right"><input type=submit value="Create Ports and IPs"></p></form>';

}

/* -------------------------------------------------- */
function snmpgeneric_opcreate() {

	$object_id = $_REQUEST['object_id'];
	$attr = getAttrValues($object_id);

//	sg_var_dump_html($_REQUEST);
//	sg_var_dump_html($attr);

	if(isset($_POST['updateattr']))
		$updateattr = TRUE;
	else
		$updateattr = FALSE;

	if(isset($_POST['portcreate']))
		$portcreate = TRUE;
	else
		$portcreate = FALSE;

	if(isset($_POST['ipaddrcreate']))
		$ipaddrcreate = TRUE;
	else
		$ipaddrcreate = FALSE;

	
	/* commitUpdateAttrValue ($object_id, $attr_id, $new_value); */
	if($updateattr)
		foreach($_POST['updateattr'] as $attr_id => $value) {
		//	if(empty($attr[$attr_id]['value']))
				if(!empty($value)) {
					commitUpdateAttrValue ($object_id, $attr_id, $value);
					showSuccess("Attribute ".$attr[$attr_id]['name']." set to $value");
				}
		}

	/* create ports */
	if($portcreate)
		foreach($_POST['portcreate'] as $if => $value) {

			$ifName = (isset($_POST['ifName'][$if]) ? trim($_POST['ifName'][$if]) : '' );
			$ifPhysAddress = (isset($_POST['ifPhysAddress'][$if]) ? trim($_POST['ifPhysAddress'][$if]) : '' );
			$ifAlias = (isset($_POST['ifAlias'][$if]) ? trim($_POST['ifAlias'][$if]) : '' );
			$ifDescr = (isset($_POST['ifDescr'][$if]) ? trim($_POST['ifDescr'][$if]) : '' );

			$visible_label = (empty($ifAlias) ? '' : $ifAlias.'; ').$ifDescr;

			if(empty($ifName)) {
				showError('Port without ifName '.$_POST['porttypeid'][$if].', '.$visible_label.', '.$ifPhysAddress);
			} else {
 				commitAddPort ($object_id, $ifName, $_POST['porttypeid'][$if], $visible_label, $ifPhysAddress);
				showSuccess('Port created '.$ifName.', '.$_POST['porttypeid'][$if].', '.$visible_label.', '.$ifPhysAddress);
			}
		}

	/* allocate ip adresses */
	if($ipaddrcreate) {
		foreach($_POST['ipaddrcreate'] as $if => $value) {	

			$ipaddr = $_POST['ipaddress'][$if];

			bindIpToObject($ipaddr, $object_id,$_POST['ifName'][$if], 1); /* connected */
			showSuccess("$ipaddr allocated"); 
		}
	}

} /* snmpgeneric_opcreate */

/* -------------------------------------------------- */

/* returns RT interface type depending on ifType, ifDescr, .. */
function guessRToif_id($ifType,$ifDescr = NULL) {
	global $ifType2oif_id;
	global $portiifoptions;
	global $portoifoptions;

	/* default value */
	$retval = '24'; /* 1000BASE-T */

	if(isset($ifType2oif_id[$ifType])) {
		$retval = $ifType2oif_id[$ifType];
	}

	if(strpos($retval,'-') === FALSE)
		$retval = "1-$retval";

	/* no ethernetCsmacd */
	if($ifType != 6) 
		return $retval;


	/* try to identify outer and inner interface type from ifDescr */

	/**********************
	 * ifDescr samples
	 *
	 * Enterasys C3
	 *
	 * Unit: 1 1000BASE-T RJ45 Gigabit Ethernet Frontpanel Port 45 - no sfp inserted
	 * Unit: 1 1000BASE-T RJ45 Gigabit Ethernet Frontpanel Port 47 - sfp 1000BASE-SX inserted
	 *
	 *
	 * Enterasys S4
	 *
         * Enterasys Networks, Inc. 1000BASE Gigabit Ethernet Port; No GBIC/MGBIC Inserted
	 * Enterasys Networks, Inc. 1000BASE-SX Mini GBIC w/LC connector
	 * Enterasys Networks, Inc. 10GBASE SFP+ 10-Gigabit Ethernet Port; No SFP+ Inserted
	 * Enterasys Networks, Inc. 10GBASE-SR SFP+ 10-Gigabit Ethernet Port (850nm Short Wavelength, 33/82m MMF, LC)
	 * Enterasys Networks, Inc. 1000BASE Gigabit Ethernet Port; Unknown GBIC/MGBIC Inserted
 	 *
	 */

	foreach($portiifoptions as $iif_id => $iif_type) {
		
		/* TODO better matching */


		/* find iif_type */
		if(preg_match('/(.*?)('.preg_quote($iif_type).')(.*)/i',$ifDescr,$matches)) {

			$oif_type = "empty ".$iif_type;

			$no = preg_match('/ no $/i', $matches[1]);

			if(preg_match('/(\d+[G]?)BASE[^ ]+/i', $matches[1], $basematch)) {
				$oif_type=$basematch[0];
			} else {
				if(preg_match('/(\d+[G]?)BASE[^ ]+/i', $matches[3], $basematch)) {
					$oif_type=$basematch[0];
				}
			}

			if($iif_id == -1) {
				/* 2 => SFP-100 or 4 => SFP-1000 */

				if(isset($basematch[1])) {
					switch($basematch[1]) {
						case '100' :
							$iif_id = 2;
							$iif_type = "SFP-100";
							break;
						default:
						case '1000' :
							$iif_id = 4;	
							$iif_type = "SFP-1000";
							break;
					}
				}
				
			}

			if($no) {
				$oif_type = "empty ".$iif_type;
			}

			$oif_type = preg_replace('/BASE/',"Base",$oif_type);

			$oif_id = array_search($oif_type,$portoifoptions);

			if($oif_id != '') {
				$retval = "$iif_id-$oif_id";
			}

			/* TODO check port compat */

			/* stop foreach */
			break;
		}
	}

	if(strpos($retval,'-') === FALSE)
		$retval = "1-$retval";

	return $retval;

}

/* --------------------------------------------------- */

/* returns object_id and port_id to a given l2address */
function sg_checkL2Address ($address)
{
        $result = usePreparedSelectBlade
        (
                'SELECT object_id,id FROM Port WHERE BINARY l2address = ?',
                array ($address)
        );
        $row = $result->fetchAll(PDO::FETCH_GROUP|PDO::FETCH_UNIQUE|PDO::FETCH_COLUMN);
        return $row;
}

/* returns Ports Name and L2Address as associated array Name => L2Address */
function getPortsNameL2address($my_object_id)
{
        $result = usePreparedSelectBlade
        (
                'SELECT name,l2address FROM Port WHERE object_id = ? ORDER BY name',
                array ($my_object_id)
        );
        $row = $result->fetchAll(PDO::FETCH_GROUP|PDO::FETCH_UNIQUE|PDO::FETCH_COLUMN);

        return $row;
}

/* returns oi_id and name */
function getPortOIOptions()
{
        $result = usePreparedSelectBlade
        (
		'SELECT dict_key,dict_value from Dictionary where chapter_id = 2',
                array ()
        );
        $row = $result->fetchAll(PDO::FETCH_GROUP|PDO::FETCH_UNIQUE|PDO::FETCH_COLUMN);
        return $row;
}



/* ------------------------------------------------------- */
class SNMPgeneric {

	protected $host;
	protected $version;

	/* SNMPv1 and SNMPv2c */
	protected $community;

	/* SNMPv3 */
	protected $sec_level;
	protected $auth_protocol;
	protected $auth_passphrase;
	protected $priv_protocol;
	protected $priv_passphrase;
//	protected $contextName;
//	protected $contextEngineID;

	const VERSION_1 = 1;
	const VERSION_2C = 2;
	const VERSION_3 = 3;


	protected $result;

	function __construct($version, $host, $community) {
		
		$this->host = $host;
		$this->version = $version;
		$this->community = $community;	

		//snmp_set_valueretrieval(SNMP_VALUE_LIBRARY);

		/* Return values without SNMP type hint */
		snmp_set_valueretrieval(SNMP_VALUE_PLAIN);

	//	snmp_set_oid_output_format(SNMP_OID_OUTPUT_FULL);
		
	//	snmp_set_quick_print(1);

	}

	function __destruct() {
	}

	function setSecurity($sec_level, $auth_protocol = 'md5', $auth_passphrase = '', $priv_protocol = 'des', $priv_passphrase = '') {
		$this->sec_level = $sec_level;
		$this->auth_protocol = $auth_protocol;
		$this->auth_passphrase = $auth_passphrase;
		$this->priv_protocol = $priv_protocol;
		$this->priv_passphrase = $priv_passphrase;
	}

	function walk( $oid, $suffix_as_key = FALSE) {

		switch($this->version) {
			case self::VERSION_1:
				if($suffix_as_key){
					$this->result = snmpwalk($this->host,$this->community,$oid);
				} else {
					$this->result = snmprealwalk($this->host,$this->community,$oid);
				}
				break;

			case self::VERSION_2C:
				if($suffix_as_key){
					$this->result = snmp2_walk($this->host,$this->community,$oid);
				} else {
					$this->result = snmp2_real_walk($this->host,$this->community,$oid);
				}
				break;

			case self::VERSION_3:
				if($suffix_as_key){
					$this->result = snmp3_walk($this->host,$this->community, $this->sec_level, $this->auth_protocol, $this->auth_passphrase, $this->priv_protocol, $this->priv_passphrase,$oid);
				} else {
					$this->result = snmp3_real_walk($this->host,$this->community, $this->sec_level, $this->auth_protocol, $this->auth_passphrase, $this->priv_protocol, $this->priv_passphrase,$oid);
				}
				break;
		}

		return $this->result;

	}

	private function __snmpget($object_id) {

		$retval = FALSE;
		
		switch($this->version) {
			case self::VERSION_1:
				$retval = snmpget($this->host,$this->community,$object_id);
				break;

			case self::VERSION_2C:
				$retval = snmp2_get($this->host,$this->community,$object_id);
				break;

			case self::VERSION_3:
				$retval = snmp3_get($this->host,$this->community, $this->sec-level, $this->auth_protocol, $this->auth_passphrase, $this->priv_protocol, $this->priv_passphrase,$object_id);
				break;
		}

		return $retval;
	}

	function get($object_id, $preserve_keys = false) {

		if(is_array($object_id)) {

			if( $preserve_keys ) {
				foreach($object_id as $oid) {
					$this->result[$oid] = $this->__snmpget($oid);
				}
			} else {
				foreach($object_id as $oid) {
					$result_oid = preg_replace('/.\d$/','',$oid);
					$this->result[$result_oid] = $this->__snmpget($oid);
				}
			}
		} else {
			$this->result = $this->__snmpget($object_id);
		}

		return $this->result;
		
	}

	function close() {
	}

	function getErrno() {
		return ($this->result === FALSE);
	}

	function getError() {
		$var = error_get_last();
		return $var['message'];
	}
} /* SNMPgeneric */

/* ------------------------------------------------------- */
/*
 * SNMP with system OIDs 
 */
class mySNMP extends SNMPgeneric implements Iterator {

	const SNMP_VERSION = SNMPgeneric::VERSION_2C;
	const SNMP_COMMUNITY = 'public';

	//private $sysInfo;
	private $system;

	/* is system table available ? */
	private $systemerror = TRUE;

	function __construct($version, $host, $community) {
		parent::__construct($version, $host, $community);

		/* .iso.org.dod.internet.mgmt.mib-2.system */
		$this->system = $this->walk(".1.3.6.1.2.1.1");

		$this->systemerror = $this->getErrno();
		
	}

	/* get value from system cache */
	private function _getvalue($object_id) {

		/* TODO better matching  */

		if( isset($this->system["SNMPv2-MIB::$object_id"])) {
			return $this->system["SNMPv2-MIB::$object_id"];
		} else {
			if( isset($this->system[".iso.org.dod.internet.mgmt.mib-2.system.$object_id"])) {
				return $this->system[".iso.org.dod.internet.mgmt.mib-2.system.$object_id"];
			} else {
				if( isset($this->system[$object_id])) {
					return $this->system[$object_id];
				} else {
					foreach($this->system as $key => $value) {
						if(strpos($key, $object_id)) {
							return $value;
						}
					}
				}
			}
		}

		return NULL;
	}

	function get($object_id, $preserve_keys = false) {

		$retval = $this->_getvalue($object_id);

		if($retval === NULL) 
			$retval = parent::get($object_id,$preserve_keys);
		
		return $retval;

	}
/*
	function get_new($object_id, $preserve_keys = false) {
		$result = parent::get($object_id,$preserve_keys);
		return $this->removeDatatype($result);
	}

	function walk_new($object_id) {
		$result = parent::walk($object_id);
		return $this->removeDatatype($result);
	}

*/
	/* use snmp_set_valueretrieval(SNMP_VALUE_PLAIN) instead */
/*	function removeDatatype($val) {
		return preg_replace('/^\w+: /','',$val);
	}
*/
	/* make something like $class->sysDescr work */
	function __get($name) {
		if($this->systemerror) {
			return;
		}
		
		$retval = $this->_getvalue($name);

		if($retval === NULL) {

			$trace = debug_backtrace();
        		trigger_error(
            			'Undefinierte Eigenschaft für __call(): ' . $name .
            			' in ' . $trace[0]['file'] .
            			' Zeile ' . $trace[0]['line'],
            			E_USER_NOTICE);
		}

		return $retval;
	}


	/* Iteration through all system OIDs */
	/* Iterator */

	function current() {
		if($this->systemerror)
			return;

		return current($this->system);
	}

	function key() {
		if($this->systemerror)
			return;

		return key($this->system);
	}

	function next() {
		return next($this->system);
	}

	function valid() {
		return ($this->current() !== FALSE) && ($this->systemerror !== TRUE);
	}

	function rewind() {
		if($this->systemerror)
			return;

		reset($this->system);
	}

	/* END Iterator */

} /* mySNMP */

/* ------------------------------------------------------- */

class ifSNMP implements Iterator {
	private $snmpdevice;
	private $ifNumber = 0;
	private $ifTable;

	private $interfaceserror = TRUE;

	function __construct(&$snmpdevice) {
		$this->snmpdevice = $snmpdevice;	

		$this->interfaceserror = $this->snmpdevice->getErrno();

		if($this->interfaceserror) {
			return;
		}
		
		$this->ifNumber = intval($this->snmpdevice->get('ifNumber.0'));
		
		$this->interfaceserror = $this->snmpdevice->getErrno();

		if(!$this->interfaceserror) {
			
			$this->getifTable();
		}
		
	}

	function getifTable() {
		$this->ifTable['ifIndex'] = $this->snmpdevice->walk('ifIndex',TRUE);
		$this->ifTable['ifDescr'] = $this->snmpdevice->walk('ifDescr',TRUE);
		$this->ifTable['ifAlias'] = $this->snmpdevice->walk('ifAlias',TRUE);
		$this->ifTable['ifName'] =  $this->snmpdevice->walk('ifName',TRUE);
		
		$this->ifTable['ifType'] =  $this->snmpdevice->walk('ifType',TRUE);

		$this->ifTable['ifSpeed'] =  $this->snmpdevice->walk('ifSpeed',TRUE);

		/* notation changes when SNMP_VALUE_PLAIN is set string -> hex!! */
		$this->ifTable['ifPhysAddress'] =  $this->snmpdevice->walk('ifPhysAddress',TRUE);

		$this->ifTable['ifOperStatus'] =  $this->snmpdevice->walk('ifOperStatus',TRUE);

		$this->ifTable['ifInOctets'] =  $this->snmpdevice->walk('ifInOctets',TRUE);
		$this->ifTable['ifOutOctets'] =  $this->snmpdevice->walk('ifOutOctets',TRUE);

		$this->ifTable['ifConnectorPresent'] =  $this->snmpdevice->walk('ifConnectorPresent',TRUE);

		/* ip address */
		$ipAdEntIfIndex =  $this->snmpdevice->walk('ipAdEntIfIndex');

		foreach($ipAdEntIfIndex as $oid => $value) {
			$ipaddr = preg_replace('/.*\.([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)$/','$1',$oid);
			$this->ifTable['ipaddress'][ array_search($value,$this->ifTable['ifIndex']) ] = $ipaddr;
		}
	}

	function printifInfoTableHeader($suffix = "") {
		if($this->interfaceserror) {
			return;
		}

		echo "<table>";
		echo "<tr>";
		foreach ($this->ifTable as $key => $value) {
			echo "<th>".$key."</th>";
		}
		echo "$suffix</tr>";
	}

	private $formfieldlist = array('ifName', 'ifDescr', 'ifAlias', 'ifPhysAddress', 'ipaddress');

	function printifInfoTableRow($ifIndex, $suffix = "", $hrefs = NULL) {
		if($this->interfaceserror) {
			return;
		}

		echo "<tr>";
		foreach ($this->ifTable as $key => $value) {

			$textfield = FALSE;

			/* minimize posted data to necessary fields */
			if(in_array($key,$this->formfieldlist)) {

				/* $value would contain raw values; $this->{$key}($ifIndex) post processed values */
				$fieldvalue = $this->{$key}($ifIndex);

				if(!empty($fieldvalue)) {
					$formfield = '<input type="hidden" name="'.$key.'['.$ifIndex.']" value="'.$fieldvalue.'">';
					echo $formfield;
				} else {
					if($key == 'ifName') {
						/* create textfield set to ifDescr */
				 		$formfield = '<input type="text" size="8" name="ifName['.$ifIndex.']" value="'
								.$this->ifDescr($ifIndex).'">';
						$textfield = TRUE;
					}
				}

			}
		

			if($textfield)
				$displayvalue=$formfield;
			else {
				$displayvalue = $this->{$key}($ifIndex);

				if(isset($hrefs) && isset($hrefs[$key])) {
					$displayvalue = "<a href=".$hrefs[$key].">$displayvalue</a>";
				}
			}
			
			echo "<td>$displayvalue</td>";
		}
		echo "$suffix</tr>";
	}

	function formatMACAddr($addr) {

		$retval = '';

		/* TODO test origin format */
		if(strlen($addr)== 6 ) {
			$retval =  unpack('H12',$addr);
			$retval = $retval[1];
		}

		/* often used as loopback on Enterasys switches */
		if($retval == '000000000000') {
			$retval = '';
		}

		return $retval;
	}

	function ifPhysAddress($index) {

		if(isset($this->ifTable['ifPhysAddress'][$index-1])) {
			return strtoupper($this->formatMACAddr($this->ifTable['ifPhysAddress'][$index-1]));
		}
	}

	function ipaddress($index) {
		if(isset($this->ifTable['ipaddress'][$index-1])) {
			return $this->ifTable['ipaddress'][$index-1];
		}

	}

	function __get($name) {

		switch($name) {
			case 'ifNumber': 
				return $this->{$name};
				break;
		}
	
		$trace = debug_backtrace();
        	trigger_error(
            		'Undefinierte Eigenschaft für __get(): ' . $name .
            		' in ' . $trace[0]['file'] .
            		' Zeile ' . $trace[0]['line'],
            		E_USER_NOTICE);

       		return NULL;
	}

	/* $obj->ifDescr(3) = $ifTable[$name][$arg]*/
	function __call($name,$args) {
		
		if($this->interfaceserror)
			return;
	
		if(isset($this->ifTable[$name])) {
			if(isset($this->ifTable[$name][$args[0]-1])) {
				return $this->ifTable[$name][$args[0]-1];
			}
		} else {
	
			/* for debug */
			$trace = debug_backtrace();
        		trigger_error(
            			'Undefinierte Methode für __call(): ' . $name .
            			' in ' . $trace[0]['file'] .
            			' Zeile ' . $trace[0]['line'],
        	    		E_USER_NOTICE);
		}

        	return NULL;

	} /* __call */

	/* Iterator */

	private $IteratorIndex = 1;

	function current() {
		return $this->IteratorIndex;
	}

	function key() {
	}

	function next() {
		$this->IteratorIndex++;
	}

	function valid() {
		return ($this->IteratorIndex<=$this->ifNumber);
	}

	function rewind() {
		$this->IteratorIndex = 1;
	}

	/* END Iterator */
}

/* ------------------------------------------------------- */
/* ------------------------------------------------------- */
/* for debugging */
function sg_var_dump_html(&$var) {
	
	echo "<pre>------------------Start Var Dump -------------------------\n";
	var_dump($var);
	echo "\n---------------------END Var Dump ------------------------</pre>";
}
?>
