Exemplo n.º 1
0
function renderVLANMembership($object_id)
{
    try {
        $data = getSwitchVLANs($object_id);
    } catch (RTGatewayError $re) {
        showWarning('Device configuration unavailable:<br>' . $re->getMessage());
        return;
    }
    list($vlanlist, $portlist, $maclist) = $data;
    $vlanpermissions = array();
    foreach ($portlist as $port) {
        if (array_key_exists($port['vlanid'], $vlanpermissions)) {
            continue;
        }
        $vlanpermissions[$port['vlanid']] = array();
        foreach (array_keys($vlanlist) as $to) {
            if (permitted(NULL, NULL, 'setPortVLAN', array(array('tag' => '$fromvlan_' . $port['vlanid']), array('tag' => '$vlan_' . $port['vlanid']))) and permitted(NULL, NULL, 'setPortVLAN', array(array('tag' => '$tovlan_' . $to), array('tag' => '$vlan_' . $to)))) {
                $vlanpermissions[$port['vlanid']][] = $to;
            }
        }
    }
    if (isset($_REQUEST['hl_port_id'])) {
        assertUIntArg('hl_port_id');
        $hl_port_id = intval($_REQUEST['hl_port_id']);
        $object = spotEntity('object', $object_id);
        amplifyCell($object);
        foreach ($object['ports'] as $port) {
            if (mb_strlen($port['name']) && $port['id'] == $hl_port_id) {
                $hl_port_name = $port['name'];
                break;
            }
        }
    }
    echo '<table border=0 width="100%"><tr><td colspan=3>';
    startPortlet('Current status');
    echo "<table class=widetable cellspacing=3 cellpadding=5 align=center width='100%'><tr>";
    printOpFormIntro('setPortVLAN');
    $portcount = count($portlist);
    echo "<input type=hidden name=portcount value=" . $portcount . ">\n";
    $portno = 0;
    $ports_per_row = 12;
    foreach ($portlist as $port) {
        // Don't let wide forms break our fancy pages.
        if ($portno % $ports_per_row == 0) {
            if ($portno > 0) {
                echo "</tr>\n";
            }
            echo "<tr><th>" . ($portno + 1) . "-" . ($portno + $ports_per_row > $portcount ? $portcount : $portno + $ports_per_row) . "</th>";
        }
        $td_class = 'port_';
        if ($port['status'] == 'notconnect') {
            $td_class .= 'notconnect';
        } elseif ($port['status'] == 'disabled') {
            $td_class .= 'disabled';
        } elseif ($port['status'] != 'connected') {
            $td_class .= 'unknown';
        } elseif (!isset($maclist[$port['portname']])) {
            $td_class .= 'connected_none';
        } else {
            $maccount = 0;
            foreach ($maclist[$port['portname']] as $vlanid => $addrs) {
                $maccount += count($addrs);
            }
            if ($maccount == 1) {
                $td_class .= 'connected_single';
            } else {
                $td_class .= 'connected_multi';
            }
        }
        if (isset($hl_port_name) and strcasecmp($hl_port_name, $port['portname']) == 0) {
            $td_class .= (strlen($td_class) ? ' ' : '') . 'border_highlight';
        }
        echo "<td class='{$td_class}'>" . $port['portname'] . '<br>';
        echo "<input type=hidden name=portname_{$portno} value=" . $port['portname'] . '>';
        if ($port['vlanid'] == 'trunk') {
            echo "<input type=hidden name=vlanid_{$portno} value='trunk'>";
            echo "<select disabled multiple='multiple' size=1><option>TRUNK</option></select>";
        } elseif ($port['vlanid'] == 'routed') {
            echo "<input type=hidden name=vlanid_{$portno} value='routed'>";
            echo "<select disabled multiple='multiple' size=1><option>ROUTED</option></select>";
        } elseif (!array_key_exists($port['vlanid'], $vlanpermissions) or !count($vlanpermissions[$port['vlanid']])) {
            echo "<input type=hidden name=vlanid_{$portno} value={$port['vlanid']}>";
            echo "<select disabled name=vlanid_{$portno}>";
            echo "<option value={$port['vlanid']} selected>{$port['vlanid']}</option>";
            echo "</select>";
        } else {
            echo "<select name=vlanid_{$portno}>";
            // A port may belong to a VLAN, which is absent from the VLAN table, this is normal.
            // We must be able to render its SELECT properly at least.
            $in_table = FALSE;
            foreach ($vlanpermissions[$port['vlanid']] as $v) {
                echo "<option value={$v}";
                if ($v == $port['vlanid']) {
                    echo ' selected';
                    $in_table = TRUE;
                }
                echo ">{$v}</option>\n";
            }
            if (!$in_table) {
                echo "<option value={$port['vlanid']} selected>{$port['vlanid']}</option>\n";
            }
            echo "</select>";
        }
        $portno++;
        echo "</td>";
    }
    echo "</tr><tr><td colspan=" . ($ports_per_row + 1) . "><input type=submit value='Save changes'></form></td></tr></table>";
    finishPortlet();
    echo '</td></tr><tr><td class=pcleft>';
    startPortlet('VLAN table');
    echo '<table class=cooltable cellspacing=0 cellpadding=5 align=center width="100%">';
    echo "<tr><th>ID</th><th>Description</th></tr>";
    $order = 'even';
    global $nextorder;
    foreach ($vlanlist as $id => $descr) {
        echo "<tr class=row_{$order}><td class=tdright>{$id}</td><td class=tdleft>{$descr}</td></tr>";
        $order = $nextorder[$order];
    }
    echo '</table>';
    finishPortlet();
    echo '</td><td class=pcright>';
    startPortlet('Color legend');
    echo '<table>';
    echo "<tr><th>port state</th><th>color code</th></tr>";
    echo "<tr><td>not connected</td><td class=port_notconnect>SAMPLE</td></tr>";
    echo "<tr><td>disabled</td><td class=port_disabled>SAMPLE</td></tr>";
    echo "<tr><td>unknown</td><td class=port_unknown>SAMPLE</td></tr>";
    echo "<tr><td>connected with none MAC addresses active</td><td class=port_connected_none>SAMPLE</td></tr>";
    echo "<tr><td>connected with 1 MAC addresses active</td><td class=port_connected_single>SAMPLE</td></tr>";
    echo "<tr><td>connected with 1+ MAC addresses active</td><td class=port_connected_multi>SAMPLE</td></tr>";
    echo '</table>';
    finishPortlet();
    echo '</td><td class=pcright>';
    if (count($maclist)) {
        startPortlet('MAC address table');
        echo '<table border=0 class=cooltable align=center cellspacing=0 cellpadding=5>';
        echo "<tr><th>Port</th><th>VLAN ID</th><th>MAC address</th></tr>\n";
        $order = 'even';
        foreach ($maclist as $portname => $portdata) {
            foreach ($portdata as $vlanid => $addrgroup) {
                foreach ($addrgroup as $addr) {
                    echo "<tr class=row_{$order}><td class=tdleft>{$portname}</td><td class=tdleft>{$vlanid}</td>";
                    echo "<td class=tdleft>{$addr}</td></tr>\n";
                    $order = $nextorder[$order];
                }
            }
        }
        echo '</table>';
        finishPortlet();
    }
    // End of main table.
    echo '</td></tr></table>';
}
Exemplo n.º 2
0
function renderPortsInfo($object_id)
{
    try {
        if (permitted(NULL, NULL, 'get_link_status')) {
            $linkStatus = queryDevice($object_id, 'getportstatus');
        } else {
            showWarning("You don't have permission to view ports link status");
        }
        if (permitted(NULL, NULL, 'get_mac_list')) {
            $macList = sortPortList(queryDevice($object_id, 'getmaclist'));
        } else {
            showWarning("You don't have permission to view learned MAC list");
        }
    } catch (RTGatewayError $e) {
        showError($e->getMessage());
        return;
    }
    global $nextorder;
    echo "<table width='100%'><tr>";
    if (!empty($linkStatus)) {
        echo "<td valign='top' width='50%'>";
        startPortlet('Link status');
        echo "<table width='80%' class='widetable' cellspacing=0 cellpadding='5px' align='center'><tr><th>Port<th><th>Link status<th>Link info</tr>";
        $order = 'even';
        foreach ($linkStatus as $pn => $link) {
            switch ($link['status']) {
                case 'up':
                    $img_filename = 'link-up.png';
                    break;
                case 'down':
                    $img_filename = 'link-down.png';
                    break;
                case 'disabled':
                    $img_filename = 'link-disabled.png';
                    break;
                default:
                    $img_filename = '1x1t.gif';
            }
            echo "<tr class='row_{$order}'>";
            $order = $nextorder[$order];
            echo '<td>' . $pn;
            echo '<td>' . '<img width=16 height=16 src="?module=chrome&uri=pix/' . $img_filename . '">';
            echo '<td>' . $link['status'];
            $info = '';
            if (isset($link['speed'])) {
                $info .= $link['speed'];
            }
            if (isset($link['duplex'])) {
                if (!empty($info)) {
                    $info .= ', ';
                }
                $info .= $link['duplex'];
            }
            echo '<td>' . $info;
            echo '</tr>';
        }
        echo "</table></td>";
        finishPortlet();
    }
    if (!empty($macList)) {
        echo "<td valign='top' width='50%'>";
        $rendered_macs = '';
        $mac_count = 0;
        $rendered_macs .= "<table width='80%' class='widetable' cellspacing=0 cellpadding='5px' align='center'><tr><th>MAC<th>Vlan<th>Port</tr>";
        $order = 'even';
        foreach ($macList as $pn => $list) {
            $order = $nextorder[$order];
            foreach ($list as $item) {
                ++$mac_count;
                $rendered_macs .= "<tr class='row_{$order}'>";
                $rendered_macs .= '<td style="font-family: monospace">' . $item['mac'];
                $rendered_macs .= '<td>' . $item['vid'];
                $rendered_macs .= '<td>' . $pn;
                $rendered_macs .= '</tr>';
            }
        }
        $rendered_macs .= "</table></td>";
        startPortlet("Learned MACs ({$mac_count})");
        echo $rendered_macs;
        finishPortlet();
    }
    echo "</td></tr></table>";
}
Exemplo n.º 3
0
function doGenericSNMPmining($device)
{
    global $objectInfo, $known_devices, $iftable_processors;
    if (FALSE === ($sysObjectID = $device->snmpget('sysObjectID.0'))) {
        showFuncMessage(__FUNCTION__, 'ERR3');
        // // fatal SNMP failure
        return;
    }
    $sysObjectID = preg_replace('/^.*(enterprises\\.|joint-iso-ccitt\\.)([\\.[:digit:]]+)$/', '\\2', $sysObjectID);
    if (!isset($known_devices[$sysObjectID])) {
        showFuncMessage(__FUNCTION__, 'ERR4', array($sysObjectID));
        // unknown OID
        return;
    }
    $sysName = substr($device->snmpget('sysName.0'), strlen('STRING: '));
    $sysDescr = substr($device->snmpget('sysDescr.0'), strlen('STRING: '));
    $sysDescr = str_replace(array("\n", "\r"), " ", $sysDescr);
    // Make it one line
    showSuccess($known_devices[$sysObjectID]['text']);
    updateStickerForCell($objectInfo, 2, $known_devices[$sysObjectID]['dict_key']);
    // HW type
    updateStickerForCell($objectInfo, 3, $sysName);
    detectSoftwareType($objectInfo, $sysDescr);
    switch (1) {
        case preg_match('/^9\\.1\\./', $sysObjectID):
            // Catalyst w/one AC port
        // Catalyst w/one AC port
        case preg_match('/^9\\.5\\.18/', $sysObjectID):
            $exact_release = preg_replace('/^.*, Version ([^ ]+), .*$/', '\\1', $sysDescr);
            $major_line = preg_replace('/^([[:digit:]]+\\.[[:digit:]]+)[^[:digit:]].*/', '\\1', $exact_release);
            $ios_codes = array('12.0' => 244, '12.1' => 251, '12.2' => 252, '15.0' => 1901, '15.1' => 2082);
            updateStickerForCell($objectInfo, 5, $exact_release);
            if (array_key_exists($major_line, $ios_codes)) {
                updateStickerForCell($objectInfo, 4, $ios_codes[$major_line]);
            }
            $sysChassi = $device->snmpget('1.3.6.1.4.1.9.3.6.3.0');
            if ($sysChassi !== FALSE or $sysChassi !== NULL) {
                updateStickerForCell($objectInfo, 1, str_replace('"', '', substr($sysChassi, strlen('STRING: '))));
            }
            // some models have the console port located on a module instead of the chassis
            $no_console = array('9.1.222', '9.1.283', '9.1.503');
            if (!in_array($sysObjectID, $no_console)) {
                checkPIC('1-29');
                commitAddPort($objectInfo['id'], 'con0', '1-29', 'console', '');
                // RJ-45 RS-232 console
            }
            if (preg_match('/Cisco IOS Software, C2600/', $sysDescr)) {
                commitAddPort($objectInfo['id'], 'aux0', '1-29', 'auxillary', '');
            }
            // RJ-45 RS-232 aux port
            $dual_ac = array('9.1.222', '9.1.283', '9.1.956');
            if (in_array($sysObjectID, $dual_ac)) {
                // models with two AC inputs
                checkPIC('1-16');
                commitAddPort($objectInfo['id'], 'AC-in-1', '1-16', 'AC1', '');
                commitAddPort($objectInfo['id'], 'AC-in-2', '1-16', 'AC2', '');
            } elseif ($sysObjectID != '9.1.749' and $sysObjectID != '9.1.920') {
                // assume the rest have one AC input, but exclude blade devices
                checkPIC('1-16');
                // AC input
                commitAddPort($objectInfo['id'], 'AC-in', '1-16', '', '');
            }
            break;
        case preg_match('/^9\\.5\\.42/', $sysObjectID):
            // Catalyst 2948 running CatOS
        // Catalyst 2948 running CatOS
        case preg_match('/^9\\.6\\.1\\./', $sysObjectID):
            // Cisco SF series
        // Cisco SF series
        case preg_match('/^2011\\.2\\.239?\\./', $sysObjectID):
            // Huawei
            checkPIC('1-681');
            commitAddPort($objectInfo['id'], 'con0', '1-681', 'console', '');
            // DB-9 RS-232 console
            checkPIC('1-16');
            commitAddPort($objectInfo['id'], 'AC-in', '1-16', '', '');
            break;
        case preg_match('/^9\\.12\\.3\\.1\\.3\\./', $sysObjectID):
            // Nexus
            $exact_release = preg_replace('/^.*, Version ([^ ]+), .*$/', '\\1', $sysDescr);
            $major_line = preg_replace('/^([[:digit:]]+\\.[[:digit:]]+)[^[:digit:]].*/', '\\1', $exact_release);
            $nxos_codes = array('4.0' => 963, '4.1' => 964);
            if (array_key_exists($major_line, $nxos_codes)) {
                updateStickerForCell($objectInfo, 4, $nxos_codes[$major_line]);
            }
            updateStickerForCell($objectInfo, 5, $exact_release);
            $sysChassi = $device->snmpget('1.3.6.1.2.1.47.1.1.1.1.11.149');
            if ($sysChassi !== FALSE or $sysChassi !== NULL) {
                updateStickerForCell($objectInfo, 1, str_replace('"', '', substr($sysChassi, strlen('STRING: '))));
            }
            checkPIC('1-29');
            commitAddPort($objectInfo['id'], 'con0', '1-29', 'console', '');
            // RJ-45 RS-232 console
            checkPIC('1-16');
            // AC input
            commitAddPort($objectInfo['id'], 'AC-in-1', '1-16', 'AC1', '');
            commitAddPort($objectInfo['id'], 'AC-in-2', '1-16', 'AC2', '');
            break;
        case preg_match('/^11\\.2\\.3\\.7\\.11\\.(\\d+)$/', $sysObjectID, $matches):
            // ProCurve
            $console_per_product = array(33 => '1-29', 63 => '1-29', 78 => '1-29', 79 => '1-29', 80 => '1-29', 84 => '1-29', 86 => '1-29', 87 => '1-29', 94 => '1-29', 95 => '1-29', 154 => '1-29', 19 => '1-681', 31 => '1-681', 34 => '1-681', 58 => '1-681', 59 => '1-681');
            if (array_key_exists($matches[1], $console_per_product)) {
                checkPIC($console_per_product[$matches[1]]);
                commitAddPort($objectInfo['id'], 'console', $console_per_product[$matches[1]], 'console', '');
            }
            $oom_per_product = array(33 => '1-24');
            if (array_key_exists($matches[1], $oom_per_product)) {
                checkPIC($oom_per_product[$matches[1]]);
                commitAddPort($objectInfo['id'], 'mgmt', $oom_per_product[$matches[1]], 'mgmt', '');
            }
            checkPIC('1-16');
            commitAddPort($objectInfo['id'], 'AC-in', '1-16', '', '');
            $exact_release = preg_replace('/^.* revision ([^ ]+), .*$/', '\\1', $sysDescr);
            updateStickerForCell($objectInfo, 5, $exact_release);
            break;
        case preg_match('/^2636\\.1\\.1\\.1\\.2\\.3(0|1)/', $sysObjectID):
            // Juniper EX3200/EX4200
            $sw_version = preg_replace('/^.*, kernel JUNOS ([^ ]+).*$/', '\\1', $sysDescr);
            updateStickerForCell($objectInfo, 5, $sw_version);
            // one RJ-45 RS-232 and one AC port (it could be DC, but chances are it's AC)
            checkPIC('1-29');
            commitAddPort($objectInfo['id'], 'con', '1-29', 'CON', '');
            // RJ-45 RS-232 console
            checkPIC('1-16');
            commitAddPort($objectInfo['id'], 'AC-in', '1-16', '', '');
            // Juniper uses the same sysObjectID for multiple HW models, override if necessary
            if (preg_match('/^Juniper Networks, Inc. ex3200-48t internet router/', $sysDescr)) {
                updateStickerForCell($objectInfo, 2, 902);
            }
            if (preg_match('/^Juniper Networks, Inc. ex4200-48t internet router/', $sysDescr)) {
                updateStickerForCell($objectInfo, 2, 907);
            }
            break;
        case preg_match('/^1991\\.1\\.3\\.53\\.1\\.2$/', $sysObjectID):
            // TurboIron 24X
        // TurboIron 24X
        case preg_match('/^2636\\.1\\.1\\.1\\.2\\./', $sysObjectID):
            // Juniper
            checkPIC('1-681');
            commitAddPort($objectInfo['id'], 'console', '1-681', 'console', '');
            // DB-9 RS-232 console
            break;
        case preg_match('/^1991\\.1\\.3\\.45\\./', $sysObjectID):
            // snFGSFamily
        // snFGSFamily
        case preg_match('/^1991\\.1\\.3\\.46\\./', $sysObjectID):
            // snFLSFamily
        // snFLSFamily
        case preg_match('/^1991\\.1\\.3\\.54\\.2\\.4\\.1\\.1$/', $sysObjectID):
            // FCX 648
            $exact_release = preg_replace('/^.*, IronWare Version ([^ ]+) .*$/', '\\1', $sysDescr);
            updateStickerForCell($objectInfo, 5, $exact_release);
            # FOUNDRY-SN-AGENT-MIB::snChasSerNum.0
            $sysChassi = $device->snmpget('enterprises.1991.1.1.1.1.2.0');
            if ($sysChassi !== FALSE or $sysChassi !== NULL) {
                updateStickerForCell($objectInfo, 1, str_replace('"', '', substr($sysChassi, strlen('STRING: '))));
            }
            # Type of uplink module installed.
            # table: FOUNDRY-SN-AGENT-MIB::snAgentBrdMainBrdDescription
            # Possible part numbers are:
            # FGS-1XG1XGC (one fixed CX4 port)
            # FGS-2XGC (two fixed CX4 ports)
            # FGS-2XG (two XFP slots)
            # And for FLS result (which is not handled here) would be:
            # 1991.1.1.2.2.1.1.2.1 = STRING: "FLS-24G 24-port Management Module"
            # 1991.1.1.2.2.1.1.2.3 = STRING: "FLS-1XG 1-port 10G Module (1-XFP)"
            # 1991.1.1.2.2.1.1.2.4 = STRING: "FLS-1XG 1-port 10G Module (1-XFP)"
            # (assuming, that the device has 2 XFP modules in slots 3 and 4).
            foreach ($device->snmpwalkoid('enterprises.1991.1.1.2.2.1.1.2') as $module_raw) {
                if (preg_match('/^STRING: "(FGS-1XG1XGC|FGS-2XGC) /i', $module_raw)) {
                    $iftable_processors['fgs-uplinks']['dict_key'] = '1-40';
                    // CX4
                    break;
                }
            }
            # AC inputs
            # table: FOUNDRY-SN-AGENT-MIB::snChasPwrSupplyDescription
            # "Power supply 1 "
            # "Power supply 2 "
            foreach ($device->snmpwalkoid('enterprises.1991.1.1.1.2.1.1.2') as $PSU_raw) {
                $count = 0;
                $PSU_cooked = trim(preg_replace('/^string: "(.+)"$/i', '\\1', $PSU_raw, 1, $count));
                if ($count) {
                    checkPIC('1-16');
                    commitAddPort($objectInfo['id'], $PSU_cooked, '1-16', '', '');
                }
            }
            # fixed console port
            checkPIC('1-681');
            commitAddPort($objectInfo['id'], 'console', '1-681', 'console', '');
            // DB-9 RS-232 console
            break;
        case preg_match('/^1916\\.2\\./', $sysObjectID):
            // Extreme Networks Summit
            $xos_release = preg_replace('/^ExtremeXOS version ([[:digit:]]+)\\..*$/', '\\1', $sysDescr);
            $xos_codes = array('10' => 1350, '11' => 1351, '12' => 1352);
            if (array_key_exists($xos_release, $xos_codes)) {
                updateStickerForCell($objectInfo, 4, $xos_codes[$xos_release]);
            }
            checkPIC('1-681');
            commitAddPort($objectInfo['id'], 'console', '1-681', 'console', '');
            // DB-9 RS-232
            checkPIC('1-16');
            commitAddPort($objectInfo['id'], 'AC-in', '1-16', '', '');
            break;
        case preg_match('/^6027\\.1\\./', $sysObjectID):
            # Force10
            commitAddPort($objectInfo['id'], 'aux0', '1-29', 'RS-232', '');
            // RJ-45 RS-232 console
            $m = array();
            if (preg_match('/Force10 Application Software Version: ([\\d\\.]+)/', $sysDescr, $m)) {
                updateStickerForCell($objectInfo, 5, $m[1]);
                $ftos_release = preg_replace('/^([678])\\..+$/', '\\1', $m[1]);
                $ftos_codes = array('6' => 1592, '7' => 1593, '8' => 1594);
                if (array_key_exists($ftos_release, $ftos_codes)) {
                    updateStickerForCell($objectInfo, 4, $ftos_codes[$ftos_release]);
                }
            }
            # F10-S-SERIES-CHASSIS-MIB::chStackUnitSerialNumber.1
            $serialNo = $device->snmpget('enterprises.6027.3.10.1.2.2.1.12.1');
            # F10-S-SERIES-CHASSIS-MIB::chSysPowerSupplyType.1.1
            if ($device->snmpget('enterprises.6027.3.10.1.2.3.1.3.1.1') == 'INTEGER: 1') {
                checkPIC('1-16');
                commitAddPort($objectInfo['id'], 'PSU0', '1-16', 'PSU0', '');
            }
            # F10-S-SERIES-CHASSIS-MIB::chSysPowerSupplyType.1.2
            if ($device->snmpget('enterprises.6027.3.10.1.2.3.1.3.1.2') == 'INTEGER: 1') {
                checkPIC('1-16');
                commitAddPort($objectInfo['id'], 'PSU1', '1-16', 'PSU1', '');
            }
            if (strlen($serialNo)) {
                updateStickerForCell($objectInfo, 1, str_replace('"', '', substr($serialNo, strlen('STRING: '))));
            }
            break;
        case preg_match('/^171\\.10\\.63\\.8/', $sysObjectID):
            // D-Link DES-3052
        // D-Link DES-3052
        case preg_match('/^202\\.20\\./', $sysObjectID):
            // SMC TigerSwitch
        // SMC TigerSwitch
        case preg_match('/^674\\.10895\\.4/', $sysObjectID):
            // Dell PowerConnect
        // Dell PowerConnect
        case preg_match('/^674\\.10895\\.300(3|4|7|9)/', $sysObjectID):
        case preg_match('/^674\\.10895\\.301(0|4|7|9)/', $sysObjectID):
        case preg_match('/^674\\.10895\\.302(0|1|8)/', $sysObjectID):
        case preg_match('/^3955\\.6\\.1\\.20(24|48)\\.1/', $sysObjectID):
            // Linksys
        // Linksys
        case preg_match('/^3955\\.6\\.50(24|48)/', $sysObjectID):
            // Linksys
        // Linksys
        case preg_match('/^4526\\.100\\./', $sysObjectID):
            // NETGEAR (with console)
        // NETGEAR (with console)
        case preg_match('/^11863\\.1\\.1\\.1/', $sysObjectID):
            // TPLink
        // TPLink
        case preg_match('/^11863\\.6\\.10\\.58/', $sysObjectID):
            // one DB-9 RS-232 and one AC port
            checkPIC('1-681');
            commitAddPort($objectInfo['id'], 'console', '1-681', '', '');
            // DB-9 RS-232
            checkPIC('1-16');
            commitAddPort($objectInfo['id'], 'AC-in', '1-16', '', '');
            break;
        case preg_match('/^388\\.18/', $sysObjectID):
            // Motorola RFS 4000
            // one RJ-45 RS-232 and one AC port
            checkPIC('1-29');
            commitAddPort($objectInfo['id'], 'console', '1-29', 'console', '');
            checkPIC('1-16');
            commitAddPort($objectInfo['id'], 'AC-in', '1-16', '', '');
            break;
        case preg_match('/^207\\.1\\.14\\./', $sysObjectID):
            // Allied Telesyn
            // one RJ-45 RS-232 and two AC ports
            checkPIC('1-29');
            commitAddPort($objectInfo['id'], 'console', '1-29', 'console', '');
            checkPIC('1-16');
            commitAddPort($objectInfo['id'], 'AC-in-1', '1-16', 'AC1', '');
            commitAddPort($objectInfo['id'], 'AC-in-2', '1-16', 'AC2', '');
            break;
        case preg_match('/^674\\.10895\\.3000/', $sysObjectID):
            // one DB-9 RS-232, one 100Mb OOB mgmt, and one AC port
            checkPIC('1-681');
            commitAddPort($objectInfo['id'], 'console', '1-681', '', '');
            // DB-9 RS-232
            checkPIC('1-19');
            commitAddPort($objectInfo['id'], 'mgmt', '1-19', '', '');
            checkPIC('1-16');
            commitAddPort($objectInfo['id'], 'AC-in', '1-16', '', '');
            break;
        case preg_match('/^43\\.1\\.16\\.4\\.3\\./', $sysObjectID):
            // 3Com
            $sw_version = preg_replace('/^.* Version 3Com OS ([^ ]+).*$/', '\\1', $sysDescr);
            updateStickerForCell($objectInfo, 5, $sw_version);
            // one RJ-45 RS-232 and one AC port
            checkPIC('1-29');
            commitAddPort($objectInfo['id'], 'console', '1-29', '', '');
            // RJ-45 RS-232 console
            checkPIC('1-16');
            commitAddPort($objectInfo['id'], 'AC-in', '1-16', '', '');
            break;
        case preg_match('/^10977\\.11825\\.11833\\.97\\.25451\\.12800\\.100\\.4\\.4/', $sysObjectID):
            // Netgear
            $sw_version = preg_replace('/^.* V([^ ]+).*$/', '\\1', $sysDescr);
            updateStickerForCell($objectInfo, 5, $sw_version);
            // one AC port, no console
            checkPIC('1-16');
            commitAddPort($objectInfo['id'], 'AC-in', '1-16', '', '');
            break;
        case preg_match('/^171\\.10\\.76\\.10/', $sysObjectID):
            // D-Link DGS-1210-24
        // D-Link DGS-1210-24
        case preg_match('/^207\\.1\\.4\\./', $sysObjectID):
            // Allied Telesyn AT-GS950/24
        // Allied Telesyn AT-GS950/24
        case preg_match('/^4526\\.100\\.4\\.(6|10)/', $sysObjectID):
            // NETGEAR (without console)
            // one AC port, no console
            checkPIC('1-16');
            commitAddPort($objectInfo['id'], 'AC-in', '1-16', '', '');
            break;
        case preg_match('/^30065\\.1\\.3011\\./', $sysObjectID):
            // Arista
            checkPIC('1-29');
            commitAddPort($objectInfo['id'], 'console', '1-29', 'IOIOI', '');
            $sw_version = preg_replace('/^Arista Networks EOS version (.+) running on .*$/', '\\1', $sysDescr);
            updateStickerForCell($objectInfo, 5, $sw_version);
            if (strlen($serialNo = $device->snmpget('mib-2.47.1.1.1.1.11.1'))) {
                # entPhysicalSerialNumber.1
                updateStickerForCell($objectInfo, 1, str_replace('"', '', substr($serialNo, strlen('STRING: '))));
            }
            break;
        case preg_match('/^119\\.1\\.203\\.2\\.2\\./', $sysObjectID):
            # NEC
            checkPIC('1-681');
            commitAddPort($objectInfo['id'], 'console 0', '1-681', 'console', '');
            checkPIC('1-16');
            commitAddPort($objectInfo['id'], 'PS1', '1-16', '', '');
            commitAddPort($objectInfo['id'], 'PS2', '1-16', '', '');
            break;
        case preg_match('/^26543\\.1\\.7\\./', $sysObjectID):
            # IBM
            checkPIC('1-29');
            commitAddPort($objectInfo['id'], 'console', '1-29', '', '');
            # RJ-45 RS-232 console
            break;
        default:
            // Nortel...
            break;
    }
    if (isset($known_devices[$sysObjectID]['modular'])) {
        // this is a modular device
        // TODO: put the entire mining operation inside a single transaction (not possible now because commitAddPort() LOCKs/UNLOCKs the Port table which auto-commits any open transactions)
        global $snmp_data;
        $snmp_data = array();
        foreach ($device->snmpwalkoid('mib-2.47.1.1.1.1.4') as $raw_key => $raw_value) {
            $key = substr($raw_key, strlen('SNMPv2-SMI::mib-2.47.1.1.1.1.4.'));
            $value = substr($raw_value, strlen('INTEGER: '));
            $snmp_data['entPhysicalContainedIn'][$key] = $value;
        }
        foreach ($device->snmpwalkoid('mib-2.47.1.1.1.1.2') as $raw_key => $raw_value) {
            $key = substr($raw_key, strlen('SNMPv2-SMI::mib-2.47.1.1.1.1.2.'));
            $value = str_ireplace(array('STRING: ', '"'), '', $raw_value);
            $snmp_data['entPhysicalDescr'][$key] = $value;
        }
        foreach ($device->snmpwalkoid('mib-2.47.1.1.1.1.7') as $raw_key => $raw_value) {
            $key = substr($raw_key, strlen('SNMPv2-SMI::mib-2.47.1.1.1.1.7.'));
            $value = str_ireplace(array('STRING: ', '"'), '', $raw_value);
            $snmp_data['entPhysicalName'][$key] = $value;
        }
        foreach ($device->snmpwalkoid('mib-2.47.1.1.1.1.13') as $raw_key => $raw_value) {
            $key = substr($raw_key, strlen('SNMPv2-SMI::mib-2.47.1.1.1.1.13.'));
            $value = str_ireplace(array('STRING: ', '"'), '', $raw_value);
            $snmp_data['entPhysicalModelName'][$key] = $value;
        }
        foreach ($device->snmpwalkoid('mib-2.47.1.1.1.1.11') as $raw_key => $raw_value) {
            $key = substr($raw_key, strlen('SNMPv2-SMI::mib-2.47.1.1.1.1.11.'));
            $value = str_ireplace(array('STRING: ', '"'), '', $raw_value);
            $snmp_data['entPhysicalSerialNum'][$key] = $value;
        }
        updateStickerForCell($objectInfo, 1, $snmp_data['entPhysicalSerialNum'][1]);
        // OEM S/N 1, safe to assume that the chassis is the first array element
        foreach ($device->snmpwalkoid('mib-2.47.1.1.1.1.9') as $raw_key => $raw_value) {
            $key = substr($raw_key, strlen('SNMPv2-SMI::mib-2.47.1.1.1.1.9.'));
            $value = str_ireplace(array('STRING: ', '"'), '', $raw_value);
            $snmp_data['entPhysicalFirmwareRev'][$key] = $value;
        }
        foreach ($device->snmpwalkoid('ifPhysAddress') as $raw_key => $raw_value) {
            $key = substr($raw_key, strlen('IF-MIB::ifPhysAddress.'));
            $value = str_ireplace(array('STRING: ', '"'), '', $raw_value);
            if (preg_match('/^[0-9a-f]{1,2}(:[0-9a-f]{1,2}){5}/i', $value)) {
                $addrbytes = explode(':', $value);
                foreach ($addrbytes as $bidx => $bytestr) {
                    if (strlen($bytestr) == 1) {
                        $addrbytes[$bidx] = '0' . $bytestr;
                    }
                }
            } elseif (preg_match('/^[0-9a-f]{1,2}( [0-9a-f]{1,2}){5}/i', $value)) {
                // xx yy zz xx yy zz
                $addrbytes = explode(' ', substr($value, -17));
            } elseif (preg_match('/22[0-9a-f]{12}22$/', bin2hex($value))) {
                // "??????"
                $addrbytes = array(substr(bin2hex($value), -14, 12));
            } else {
                break;
            }
            // martian format
            // if this port's MAC is already assigned to another port, mark it as an empty string instead of causing a conflict
            $mac = implode('', $addrbytes);
            $snmp_data['ifPhysAddress'][$key] = (array_key_exists('ifPhysAddress', $snmp_data) and in_array($mac, $snmp_data['ifPhysAddress'])) ? '' : $mac;
        }
        // map entPhysicalIndex to ifIndex for MAC addresses association
        // first try to use entAliasMappingIdentifier (some devices don't support it)
        if ($entToIfMapping_raw = @$device->snmpwalkoid('mib-2.47.1.3.2.1.2')) {
            foreach ($entToIfMapping_raw as $key => $value) {
                // find the entID and map it to the ifID
                $e_array = explode('.', $key);
                $e_index = count($e_array) - 2;
                $eid = $e_array[$e_index];
                $iid = substr($value, strrpos($value, '.') + 1);
                $snmp_data['entToIfMapping'][$eid] = $iid;
            }
        } else {
            // entAliasMappingIdentifier isn't available, use entPhysicalName
            $ifName = array();
            foreach ($device->snmpwalkoid('ifName') as $raw_key => $raw_value) {
                $key = substr($raw_key, strlen('IF-MIB::ifName.'));
                $value = str_ireplace(array('STRING: ', '"'), '', $raw_value);
                $ifName[$key] = $value;
            }
            // query entPhysicalClass and note which entries which are ports
            foreach ($device->snmpwalkoid('mib-2.47.1.1.1.1.5') as $raw_key => $raw_value) {
                if (substr($raw_value, strlen('INTEGER: ')) == 10) {
                    $snmp_data['entPhysicalPorts'][] = substr($raw_key, strlen('SNMPv2-SMI::mib-2.47.1.1.1.1.5.'));
                }
            }
            // do the mapping, but only for ports
            foreach ($snmp_data['entPhysicalName'] as $key => $value) {
                if (in_array($key, $snmp_data['entPhysicalPorts'])) {
                    $snmp_data['entToIfMapping'][$key] = array_search($value, $ifName);
                }
            }
        }
        addModules(1, $objectInfo['id']);
    } else {
        // this is not a modular device
        $ifDescr_tablename = isset($known_devices[$sysObjectID]['ifDescrOID']) ? $known_devices[$sysObjectID]['ifDescrOID'] : 'ifDescr';
        foreach (array_keys($known_devices[$sysObjectID]['processors']) as $pkey) {
            if (!array_key_exists($known_devices[$sysObjectID]['processors'][$pkey], $iftable_processors)) {
                showWarning('processor "' . $known_devices[$sysObjectID]['processors'][$pkey] . '" not found');
                unset($known_devices[$sysObjectID]['processors'][$pkey]);
            }
        }
        $ifInfo = array();
        foreach ($device->snmpwalkoid($ifDescr_tablename) as $oid => $value) {
            $randomindex = preg_replace("/^.*{$ifDescr_tablename}\\.(.+)\$/", '\\1', $oid);
            $value = trim(preg_replace('/^[^:]+: (.+)$/', '\\1', $value), '"');
            $ifInfo[$randomindex]['ifDescr'] = $value;
        }
        foreach ($device->snmpwalkoid('ifPhysAddress') as $oid => $value) {
            $randomindex = preg_replace("/^.*ifPhysAddress\\.(.+)\$/", '\\1', $oid);
            $value = trim($value);
            // NET-SNMP may return MAC addresses in one of two (?) formats depending on
            // DISPLAY-HINT internal database. The best we can do about it is to accept both.
            // Bug originally reported by Walery Wysotsky against openSUSE 11.0.
            if (preg_match('/^string: [0-9a-f]{1,2}(:[0-9a-f]{1,2}){5}/i', $value)) {
                list($dummy, $value) = explode(' ', $value);
                $addrbytes = explode(':', $value);
                foreach ($addrbytes as $bidx => $bytestr) {
                    if (strlen($bytestr) == 1) {
                        $addrbytes[$bidx] = '0' . $bytestr;
                    }
                }
            } elseif (preg_match('/^hex-string:( [0-9a-f]{2}){6}/i', $value)) {
                // Hex-STRING: xx yy zz xx yy zz
                $addrbytes = explode(' ', substr($value, -17));
            } elseif (preg_match('/22[0-9a-f]{12}22$/', bin2hex($value))) {
                // STRING: "??????"
                $addrbytes = array(substr(bin2hex($value), -14, 12));
            } else {
                continue;
            }
            // martian format
            $ifInfo[$randomindex]['ifPhysAddress'] = implode('', $addrbytes);
        }
        // process each interface only once regardless of how many processors we have to run
        foreach ($ifInfo as $iface) {
            foreach ($known_devices[$sysObjectID]['processors'] as $processor_name) {
                $newname = preg_replace($iftable_processors[$processor_name]['pattern'], $iftable_processors[$processor_name]['replacement'], $iface['ifDescr'], 1, $count);
                if ($newname === NULL) {
                    showError('PCRE pattern error, terminating');
                    break 2;
                }
                if (!$count) {
                    continue;
                }
                // try next processor on current port
                $newlabel = preg_replace($iftable_processors[$processor_name]['pattern'], $iftable_processors[$processor_name]['label'], $iface['ifDescr'], 1, $count);
                checkPIC($iftable_processors[$processor_name]['dict_key']);
                commitAddPort($objectInfo['id'], $newname, $iftable_processors[$processor_name]['dict_key'], $newlabel, $iface['ifPhysAddress']);
                if (!$iftable_processors[$processor_name]['try_next_proc']) {
                    // done with this port
                    continue 2;
                }
            }
        }
    }
    // No failure up to this point, thus leave current tab for the "Ports" one.
    return buildRedirectURL(NULL, 'ports');
}
Exemplo n.º 4
0
function apply8021qChangeRequest($switch_id, $changes, $verbose = TRUE, $mutex_rev = NULL)
{
    global $dbxlink;
    $dbxlink->beginTransaction();
    try {
        if (NULL === ($vswitch = getVLANSwitchInfo($switch_id, 'FOR UPDATE'))) {
            throw new InvalidArgException('object_id', $switch_id, 'VLAN domain is not set for this object');
        }
        if (isset($mutex_rev) and $vswitch['mutex_rev'] != $mutex_rev) {
            throw new InvalidRequestArgException('mutex_rev', $mutex_rev, 'expired form data');
        }
        $after = $before = apply8021QOrder($vswitch['template_id'], getStored8021QConfig($vswitch['object_id'], 'desired'));
        $domain_vlanlist = getDomainVLANs($vswitch['domain_id']);
        $changes = filter8021QChangeRequests($domain_vlanlist, $before, apply8021QOrder($vswitch['template_id'], $changes));
        $desired_ports_count = count($changes);
        $changes = authorize8021QChangeRequests($before, $changes);
        if (count($changes) < $desired_ports_count) {
            showWarning(sprintf("Permission denied to change %d ports", $desired_ports_count - count($changes)));
        }
        foreach ($changes as $port_name => $port) {
            $after[$port_name] = $port;
        }
        $new_uplinks = filter8021QChangeRequests($domain_vlanlist, $after, produceUplinkPorts($domain_vlanlist, $after, $vswitch['object_id']));
        $npulled = replace8021QPorts('desired', $vswitch['object_id'], $before, $changes);
        $nsaved_uplinks = replace8021QPorts('desired', $vswitch['object_id'], $before, $new_uplinks);
        if ($npulled + $nsaved_uplinks) {
            touchVLANSwitch($vswitch['object_id']);
        }
        $dbxlink->commit();
    } catch (Exception $e) {
        $dbxlink->rollBack();
        showError(sprintf("Failed to update switchports: %s", $e->getMessage()));
        return 0;
    }
    $nsaved_downlinks = 0;
    if ($nsaved_uplinks) {
        $nsaved_downlinks = initiateUplinksReverb($vswitch['object_id'], $new_uplinks);
    }
    // instant deploy to that switch if configured
    $done = 0;
    if ($npulled + $nsaved_uplinks > 0 and getConfigVar('8021Q_INSTANT_DEPLOY') == 'yes') {
        try {
            if (FALSE === ($done = exec8021QDeploy($vswitch['object_id'], TRUE))) {
                showError("deploy was blocked due to conflicting configuration versions");
            } elseif ($verbose) {
                showSuccess(sprintf("Configuration for %u port(s) have been deployed", $done));
            }
        } catch (Exception $e) {
            showError(sprintf("Failed to deploy changes to switch: %s", $e->getMessage()));
        }
    }
    // report number of changed ports
    $total = $npulled + $nsaved_uplinks + $nsaved_downlinks;
    if ($verbose) {
        $message = sprintf('%u port(s) have been changed', $total);
        if ($total > 0) {
            showSuccess($message);
        } else {
            showNotice($message);
        }
    }
    return $total;
}
Exemplo n.º 5
0
 /**
  * VALIDATE()
  *
  * Valida dados enviados em formulários automaticamente de acordo com regras
  * descritas nos respectivos Models.
  *
  * @param mixed $data Contém os dados para validação
  * @param bool $sub Para verificar Models recursivamente, não deve ser usado
  * externamente.
  * @return bool Se validar, retorna verdadeiro
  */
 public function validate($data, $sub = false)
 {
     /**
      * @todo - verificar $sub
      * 
      * Se $this->invalidate() já foi chamado, não limpa session.
      */
     /**
      * Limpa Session
      */
     if (!$sub && !$this->invalidated) {
         unset($_SESSION["Sys"]["FormHelper"]["notValidated"]);
     }
     /**
      * Inicializa variáveis
      */
     $validationRules = $this->validation;
     $vE = array();
     if (is_array($data)) {
         foreach ($data as $model => $campos) {
             /*
              * Model principal
              */
             if ($model == get_class($this) and !empty($validationRules)) {
                 /**
                  * Campos de um formulário enviado
                  */
                 foreach ($campos as $campo => $valor) {
                     /**
                      * Se o campo possui regras de validação
                      */
                     if (array_key_exists($campo, $validationRules)) {
                         /**
                          * VALIDAÇÃO
                          */
                         $vR = $validationRules[$campo];
                         /**
                          * Uma regra somente
                          */
                         if (array_key_exists("rule", $vR)) {
                             $allRules[] = $vR;
                         } else {
                             if (is_array($vR)) {
                                 foreach ($vR as $subRule) {
                                     if (array_key_exists("rule", $subRule)) {
                                         $allRules[] = $subRule;
                                     }
                                 }
                             }
                         }
                         $paramsToValidate = array("valor" => $valor, "model" => $this, "campo" => $campo, "vR" => $vR);
                         /**
                          * Com todas as regras, faz loop validando
                          */
                         if (!empty($allRules) and is_array($allRules)) {
                             foreach ($allRules as $rule) {
                                 /**
                                  * VALIDA DE FATO
                                  *
                                  * Verifica se funções de validação existem
                                  */
                                 /**
                                  * Função de validação pré-existente
                                  */
                                 if (is_string($rule["rule"]) and method_exists("Validation", $rule["rule"])) {
                                     $result = call_user_func("Validation::" . $rule["rule"], $valor);
                                 } elseif (is_string($rule["rule"]) and method_exists($this, $rule["rule"])) {
                                     $result = $this->{$rule["rule"]}($valor);
                                 } elseif (is_array($rule["rule"]) and method_exists("Validation", reset(array_keys($rule["rule"])))) {
                                     $result = call_user_func("Validation::" . reset(array_keys($rule["rule"])), $valor, reset(array_values($rule["rule"])));
                                 } elseif (is_array($rule["rule"]) and method_exists($this, reset(array_keys($rule["rule"])))) {
                                     $result = $this->{reset(array_keys($rule["rule"]))}($valor, reset(array_values($rule["rule"])));
                                 } else {
                                     if (is_array($rule["rule"])) {
                                         $inexistentRule = reset(array_keys($rule["rule"]));
                                     } elseif (is_string($rule["rule"])) {
                                         $inexistentRule = $rule["rule"];
                                     }
                                     showError("Regra de validação <em>" . $inexistentRule . "</em> do model <em>" . get_class($this) . "</em> inexistente");
                                 }
                                 /**
                                  * [Não validou]
                                  */
                                 if (!$result) {
                                     /*
                                      * Session para formHelper
                                      */
                                     /*
                                      * Pega mensagem
                                      */
                                     if (!empty($rule["message"])) {
                                         $message = $rule["message"];
                                     } else {
                                         if (!empty($rule["m"])) {
                                             $message = $rule["m"];
                                         } else {
                                             if (isDebugMode()) {
                                                 showWarning("Mensagem de validação do campo " . $campo . " não especificada");
                                             }
                                             $message = "Not validated!";
                                         }
                                     }
                                     /**
                                      * Caso seja um model-filho no
                                      * relacionamento de models
                                      */
                                     if ($sub) {
                                         $vE[$campo] = '1';
                                     } else {
                                         $vE[$model][$campo] = '1';
                                     }
                                     $_SESSION["Sys"]["FormHelper"]["notValidated"][$model][$campo]["message"] = $message;
                                 }
                                 // fim [não validou]
                             }
                         }
                         unset($allRules);
                     }
                 }
                 // fim foreach($campos)
             } elseif (empty($validationRules)) {
                 /*
                  * Não faz nada :)
                  */
             } else {
                 if (!$this->{$model}->validate(array($model => $campos), true)) {
                     $vE[$model] = 0;
                 }
             }
         }
     }
     /**
      * $vE: Validations Errors
      */
     /* se já houve invalidações manuais com $this->invalidate() */
     if ($this->invalidated) {
         return false;
     }
     /**
      * Se validou, retorna true
      */
     if (!empty($vE)) {
         return false;
     } else {
         return true;
     }
 }
Exemplo n.º 6
0
function snmpgeneric_list($object_id)
{
    global $sg_create_noconnector_ports, $sg_known_sysObjectIDs, $sg_portoifoptions, $sg_ifType_ignore;
    if (isset($_POST['snmpconfig'])) {
        $snmpconfig = $_POST;
    } else {
        showError("Missing SNMP Config");
        return;
    }
    //	sg_var_dump_html($snmpconfig);
    echo '<body onload="document.getElementById(\'createbutton\').focus();">';
    addJS('function setchecked(classname) { var boxes = document.getElementsByClassName(classname);
				 var 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'] == "v3") {
        $snmpdev->setSecurity($snmpconfig['sec_level'], $snmpconfig['auth_protocol'], $snmpconfig['auth_passphrase'], $snmpconfig['priv_protocol'], $snmpconfig['priv_passphrase']);
    }
    $snmpdev->init();
    if ($snmpdev->getErrno()) {
        showError($snmpdev->getError());
        return;
    }
    /* SNMP connect successfull */
    showSuccess("SNMP " . $snmpconfig['version'] . " connect to {$snmpconfig['host']} successfull");
    echo '<form name=CreatePorts method=post action=' . $_SERVER['REQUEST_URI'] . '&module=redirect&op=create>';
    echo "<strong>System Informations</strong>";
    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 title=\"" . $snmpdev->lastgetoid . "\" align=\"right\">{$shortoid}: </td><td>{$value}</td></tr>";
    }
    unset($shortoid);
    echo "</table>";
    /* sysObjectID Attributes and Ports */
    $sysObjectID['object'] =& $object;
    /* get sysObjectID */
    $sysObjectID['raw_value'] = $snmpdev->sysObjectID;
    //$sysObjectID['raw_value'] = 'NET-SNMP-MIB::netSnmpAgentOIDs.10';
    $sysObjectID['value'] = preg_replace('/^.*enterprises\\.([\\.[:digit:]]+)$/', '\\1', $sysObjectID['raw_value']);
    /* try snmptranslate to numeric */
    if (preg_match('/[^\\.0-9]+/', $sysObjectID['value'])) {
        $numeric_value = $snmpdev->translatetonumeric($sysObjectID['value']);
        if (!empty($numeric_value)) {
            showSuccess("sysObjectID: " . $sysObjectID['value'] . " translated to {$numeric_value}");
            $sysObjectID['value'] = preg_replace('/^.1.3.6.1.4.1.([\\.[:digit:]]+)$/', '\\1', $numeric_value);
        }
    }
    /* array_merge doesn't work with numeric keys !! */
    $sysObjectID['attr'] = array();
    $sysObjectID['port'] = array();
    $sysobjid = $sysObjectID['value'];
    $count = 1;
    while ($count) {
        if (isset($sg_known_sysObjectIDs[$sysobjid])) {
            $sysObjectID = $sysObjectID + $sg_known_sysObjectIDs[$sysobjid];
            if (isset($sg_known_sysObjectIDs[$sysobjid]['attr'])) {
                $sysObjectID['attr'] = $sysObjectID['attr'] + $sg_known_sysObjectIDs[$sysobjid]['attr'];
            }
            if (isset($sg_known_sysObjectIDs[$sysobjid]['port'])) {
                $sysObjectID['port'] = $sysObjectID['port'] + $sg_known_sysObjectIDs[$sysobjid]['port'];
            }
            if (isset($sg_known_sysObjectIDs[$sysobjid]['text'])) {
                showSuccess("found sysObjectID ({$sysobjid}) " . $sg_known_sysObjectIDs[$sysobjid]['text']);
            }
        }
        $sysobjid = preg_replace('/\\.[[:digit:]]+$/', '', $sysobjid, 1, $count);
        /* add default sysobjectid */
        if ($count == 0 && $sysobjid != 'default') {
            $sysobjid = 'default';
            $count = 1;
        }
    }
    $sysObjectID['vendor_number'] = $sysobjid;
    /* device pf */
    if (isset($sysObjectID['pf'])) {
        foreach ($sysObjectID['pf'] as $function) {
            if (function_exists($function)) {
                /* call device pf */
                $function($snmpdev, $sysObjectID, NULL);
            } else {
                showWarning("Missing processor function " . $function . " for device {$sysobjid}");
            }
        }
    }
    /* sort attributes maintain numeric keys */
    ksort($sysObjectID['attr']);
    /* DEBUG */
    //sg_var_dump_html($sysObjectID['attr'], "Before processing");
    /* needs PHP >= 5 foreach call by reference */
    /* php 5.1.6 doesn't seem to work */
    //foreach($sysObjectID['attr'] as $attr_id => &$attr)
    foreach ($sysObjectID['attr'] as $attr_id => $value) {
        $attr =& $sysObjectID['attr'][$attr_id];
        if (isset($object['attr'][$attr_id])) {
            if (array_key_exists('key', $object['attr'][$attr_id])) {
                $attr['key'] = $object['attr'][$attr_id]['key'];
            }
            switch (TRUE) {
                case isset($attr['pf']):
                    if (function_exists($attr['pf'])) {
                        $attr['pf']($snmpdev, $sysObjectID, $attr_id);
                    } else {
                        showWarning("Missing processor function " . $attr['pf'] . " for attribute {$attr_id}");
                    }
                    break;
                case isset($attr['oid']):
                    $attrvalue = $snmpdev->get($attr['oid']);
                    if (isset($attr['regex'])) {
                        $regex = $attr['regex'];
                        if (isset($attr['replacement'])) {
                            $replacement = $attr['replacement'];
                            $attrvalue = preg_replace($regex, $replacement, $attrvalue);
                        } else {
                            if (!preg_match($regex, $attrvalue)) {
                                if (!isset($attr['uncheck'])) {
                                    $attr['uncheck'] = "regex doesn't match";
                                }
                            } else {
                                unset($attr['uncheck']);
                            }
                        }
                    }
                    $attr['value'] = $attrvalue;
                    break;
                case isset($attr['value']):
                    break;
                default:
                    showError("Error handling attribute id: {$attr_id}");
            }
        } else {
            showWarning("Object has no attribute id: {$attr_id}");
            unset($sysObjectID['attr'][$attr_id]);
        }
    }
    unset($attr_id);
    /* sort again in case there where attribs added ,maintain numeric keys */
    ksort($sysObjectID['attr']);
    /* print 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>';
    /* DEBUG */
    //sg_var_dump_html($sysObjectID['attr'], "After processing");
    foreach ($sysObjectID['attr'] as $attr_id => &$attr) {
        $attr['id'] = $attr_id;
        if (isset($object['attr'][$attr_id]) && isset($attr['value'])) {
            if ($attr['value'] == $object['attr'][$attr_id]['value']) {
                $attr['uncheck'] = 'Current = new value';
            }
            if (isset($attr['key']) && isset($object['attr'][$attr_id]['key'])) {
                if ($attr['key'] == $object['attr'][$attr_id]['key']) {
                    $attr['uncheck'] = 'Current = new key';
                }
            }
            $value = $attr['value'];
            $val_key = isset($object['attr'][$attr_id]['key']) ? ' (' . $object['attr'][$attr_id]['key'] . ')' : '';
            $comment = '';
            if (isset($attr['comment'])) {
                if (!empty($attr['comment'])) {
                    $comment = $attr['comment'];
                }
            }
            if (isset($attr['uncheck'])) {
                $checked = '';
                $comment .= ', ' . $attr['uncheck'];
            } else {
                $checked = ' checked="checked"';
            }
            $updateattrcheckbox = '<b style="background-color:#00ff00">' . '<input style="background-color:#00ff00" class="attribute" type="checkbox" name="updateattr[' . $attr_id . ']" value="' . $value . '"' . $checked . '></b>';
            $comment = trim($comment, ', ');
            echo "<tr><td>{$updateattrcheckbox}</td><td title=\"id: {$attr_id}\">" . $object['attr'][$attr_id]['name'] . '</td><td style="background-color:#d8d8d8">' . $object['attr'][$attr_id]['value'] . $val_key . '</td><td>' . $value . '</td>' . '<td style="color:#888888">' . $comment . '</td></tr>';
        }
    }
    unset($attr_id);
    echo '</table>';
    $object['breed'] = sg_detectDeviceBreedByObject($sysObjectID);
    if (!empty($object['breed'])) {
        echo "Found Breed: " . $object['breed'] . "<br>";
    }
    /* ports */
    /* get ports */
    amplifyCell($object);
    /* set array key to lowercase port name */
    foreach ($object['ports'] as $key => $values) {
        $object['ports'][strtolower(shortenIfName($values['name'], $object['breed']))] = $values;
        unset($object['ports'][$key]);
    }
    $newporttypeoptions = getNewPortTypeOptions();
    //	sg_var_dump_html($sysObjectID['port']);
    if (!empty($sysObjectID['port'])) {
        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></tr>';
        foreach ($sysObjectID['port'] as $name => $port) {
            if (array_key_exists(strtolower($name), $object['ports'])) {
                $disableport = TRUE;
            } else {
                $disableport = FALSE;
            }
            $comment = '';
            if (isset($port['comment'])) {
                if (!empty($port['comment'])) {
                    $comment = $port['comment'];
                }
            }
            if (isset($port['uncheck'])) {
                $checked = '';
                $comment .= ', ' . $port['uncheck'];
            } else {
                $checked = ' checked="checked"';
            }
            $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) . '></b>';
            $formfield = '<input type="hidden" name="ifName[' . $name . ']" value="' . $name . '">';
            echo "<tr>{$formfield}<td>{$portcreatecheckbox}</td><td>{$name}</td>";
            if (isset($port['disabled'])) {
                $disabledselect = array('disabled' => "disabled");
            } else {
                $disabledselect = array();
            }
            foreach ($port as $key => $value) {
                if ($key == 'uncheck' || $key == 'comment') {
                    continue;
                }
                /* TODO iif_name */
                if ($key == 'porttypeid') {
                    $displayvalue = getNiftySelect($newporttypeoptions, array('name' => "porttypeid[{$name}]") + $disabledselect, $value);
                } else {
                    $displayvalue = $value;
                }
                $formfield = '<input type="hidden" name="' . $key . '[' . $name . ']" value="' . $value . '">';
                echo "{$formfield}<td>{$displayvalue}</td>";
            }
            $comment = trim($comment, ', ');
            echo "<td style=\"color:#888888\">{$comment}</td></tr>";
        }
        unset($name);
        unset($port);
        echo '</table>';
    }
    /* snmp ports */
    $ifsnmp = new ifSNMP($snmpdev);
    // needed for shortenIfName()
    $ifsnmp->object_breed = $object['breed'];
    /* ip spaces */
    $ipspace = NULL;
    foreach ($ifsnmp->ipaddress as $ifindex => $ipaddresses) {
        foreach ($ipaddresses as $ipaddr => $value) {
            $addrtype = $value['addrtype'];
            $netaddr = $value['net'];
            $maskbits = $value['maskbits'];
            $netid = NULL;
            $linklocal = FALSE;
            //echo "<br> - DEBUG: ipspace $ipaddr - $netaddr - $addrtype - $maskbits<br>";
            /* check for ip space */
            switch ($addrtype) {
                case 'ipv4':
                case 'ipv4z':
                    if ($maskbits == 32) {
                        $netid = 'host';
                    } else {
                        $netid = getIPv4AddressNetworkId(ip_parse($ipaddr));
                    }
                    break;
                case 'ipv6':
                    if (ip_checkparse($ipaddr) === false) {
                        /* format ipaddr for ip6_parse */
                        $ipaddr = preg_replace('/((..):(..))/', '\\2\\3', $ipaddr);
                        $ipaddr = preg_replace('/%.*$/', '', $ipaddr);
                    }
                    if (ip_checkparse($ipaddr) === false) {
                        continue 2;
                    }
                    // 2 because of switch
                    $ip6_bin = ip6_parse($ipaddr);
                    $ip6_addr = ip_format($ip6_bin);
                    $netid = getIPv6AddressNetworkId($ip6_bin);
                    $node = constructIPRange($ip6_bin, $maskbits);
                    $netaddr = $node['ip'];
                    $linklocal = substr($ip6_addr, 0, 5) == "fe80:";
                    //echo "<br> - DEBUG: ipspace $ipaddr - $addrtype - $maskbits - $netaddr - >$linklocal<<br>";
                    break;
                case 'ipv6z':
                    /* link local */
                    $netid = 'ignore';
                    break;
                default:
            }
            if (empty($netid) && $netaddr != '::1' && $netaddr != '127.0.0.1' && $netaddr != '127.0.0.0' && $netaddr != '0.0.0.0' && !$linklocal) {
                $netaddr .= "/{$maskbits}";
                $ipspace[$netaddr] = array('addrtype' => $addrtype, 'checked' => $maskbits > 0 ? true : false);
            }
        }
        unset($ipaddr);
        unset($value);
        unset($addrtype);
    }
    unset($ifindex);
    unset($ipaddresses);
    /* print ip spaces table */
    if (!empty($ipspace)) {
        echo '<br><br>Create IP Spaces';
        echo '<table><tr><th><input type="checkbox" id="ipspace" onclick="setchecked(this.id)" checked=\\"checked\\"></th>';
        echo '<th>Type</th><th>prefix</th><th>name</th><th width=150 title="reserve network and router addresses">reserve network / router addresses</th></tr>';
        $i = 1;
        foreach ($ipspace as $prefix => $ipspace) {
            $netcreatecheckbox = '<b style="background-color:#00ff00">' . '<input class="ipspace" style="background-color:#00ff00" type="checkbox" name="netcreate[' . $i . ']" value="' . $ipspace['addrtype'] . '"' . ($ipspace['checked'] ? ' checked=\\"checked\\"' : '') . '></b>';
            $netprefixfield = '<input type="text" size=50 name="netprefix[' . $i . ']" value="' . $prefix . '">';
            $netnamefield = '<input type="text" name="netname[' . $i . ']">';
            $netreservecheckbox = '<input type="checkbox" name="netreserve[' . $i . ']" checked="checked">';
            echo "<tr><td>{$netcreatecheckbox}</td><td style=\"color:#888888\">{$ipspace['addrtype']}</td><td>{$netprefixfield}</td><td>{$netnamefield}</td><td>{$netreservecheckbox}</td></tr>";
            $i++;
        }
        unset($prefix);
        unset($addrtype);
        unset($i);
        echo '</table>';
    }
    echo "<br><br>ifNumber: " . $ifsnmp->ifNumber . "<br>indexcount: " . $ifsnmp->indexcount . "<br><table><tbody valign=\"top\">";
    $portcompat = getPortInterfaceCompat();
    $ipnets = array();
    $ifsnmp->printifInfoTableHeader("<th>add ip</th><th>add port</th><th>upd label</th><th title=\"update mac\">upd mac</th><td>upd port type</th><th>porttypeid</th><th>comment</th></tr>");
    echo '<tr><td colspan="11"></td>
		<td><input type="checkbox" id="ipaddr" onclick="setchecked(this.id);" checked="checked">IPv4<br>
		<input type="checkbox" id="ipv6addr" onclick="setchecked(this.id);" checked="checked">IPv6</td>
		<td><input type="checkbox" id="ports" onclick="setchecked(this.id)"></td>
		<td><input type="checkbox" id="label" onclick="setchecked(this.id);" checked="checked"></td>
		<td><input type="checkbox" id="mac" onclick="setchecked(this.id);" checked="checked"></td>
		<td><input type="checkbox" id="porttype" onclick="setchecked(this.id);"></td></tr>';
    foreach ($ifsnmp as $if) {
        $createport = TRUE;
        $disableport = FALSE;
        $ignoreport = FALSE;
        $port_info = NULL;
        $updatelabel = false;
        $updateporttype = false;
        $updatemaccheckbox = '';
        $hrefs = array();
        $comment = "";
        if (trim($ifsnmp->ifName($if)) == '') {
            $comment .= "no ifName";
            $createport = FALSE;
        } else {
            if (array_key_exists($ifsnmp->ifName($if), $object['ports'])) {
                $port_info =& $object['ports'][$ifsnmp->ifName($if)];
                $comment .= "Name exists";
                /* ifalias change */
                if ($port_info['label'] != $ifsnmp->ifAlias($if)) {
                    $updatelabel = true;
                }
                $createport = FALSE;
                $disableport = TRUE;
            }
        }
        if ($ifsnmp->ifPhysAddress($if) != '') {
            $ifPhysAddress = $ifsnmp->ifPhysAddress($if);
            $l2port = sg_checkL2Address($ifPhysAddress);
            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;
                $updatemaccheckbox = '';
            }
            $disablemac = true;
            if ($disableport) {
                if ($port_info !== NULL) {
                    if (str_replace(':', '', $port_info['l2address']) != $ifPhysAddress) {
                        $disablemac = false;
                    } else {
                        $disablemac = true;
                    }
                }
            } else {
                /* port create always updates mac */
                $updatemaccheckbox = '<b style="background-color:#00ff00">' . '<input style="background-color:' . '#00ff00" type="checkbox"' . ' checked="checked"' . ' disabled=\\"disabled\\"></b>';
            }
            if (!$disablemac) {
                $updatemaccheckbox = '<b style="background-color:' . ($disablemac ? '#ff0000' : '#00ff00') . '">' . '<input class="mac" style="background-color:' . ($disablemac ? '#ff0000' : '#00ff00') . '" type="checkbox" name="updatemac[' . $if . ']" value="' . $object['ports'][$ifsnmp->ifName($if)]['id'] . '" checked="checked"' . ($disablemac ? ' disabled=\\"disabled\\"' : '') . '></b>';
            }
        }
        $porttypeid = guessRToif_id($ifsnmp->ifType($if), $ifsnmp->ifDescr($if));
        if (in_array($ifsnmp->ifType($if), $sg_ifType_ignore)) {
            $comment .= ", ignore if type";
            $createport = FALSE;
            $ignoreport = TRUE;
        } else {
            if ($port_info) {
                $ptid = $port_info['iif_id'] . "-" . $port_info['oif_id'];
                if ($porttypeid != $ptid) {
                    $comment .= ", Update Type {$ptid} -> {$porttypeid}";
                    $updateporttype = true;
                }
            }
        }
        /* ignore ports without an Connector */
        if (!$sg_create_noconnector_ports && $ifsnmp->ifConnectorPresent($if) == 2) {
            $comment .= ", no Connector";
            $createport = FALSE;
        }
        /* Allocate IPs ipv4 and ipv6 */
        $ipaddresses = $ifsnmp->ipaddress($if);
        if (!empty($ipaddresses)) {
            $ipaddrcell = '<table>';
            foreach ($ipaddresses as $ipaddr => $value) {
                $createipaddr = FALSE;
                $disableipaddr = FALSE;
                $ipaddrhref = '';
                $linklocal = FALSE;
                $addrtype = $value['addrtype'];
                $maskbits = $value['maskbits'];
                $bcast = $value['bcast'];
                //echo "<br> - DEBUG: ip $ipaddr - $addrtype - $maskbits - $bcast<br>";
                switch ($addrtype) {
                    case 'ipv4z':
                    case 'ipv4':
                        if ($maskbits == 32) {
                            $bcast = "host";
                        }
                        $inputname = 'ip';
                        break;
                    case 'ipv6z':
                        $disableipaddr = TRUE;
                    case 'ipv6':
                        $inputname = 'ipv6';
                        if (ip_checkparse($ipaddr) === false) {
                            /* format ipaddr for ip6_parse */
                            $ipaddr = preg_replace('/((..):(..))/', '\\2\\3', $ipaddr);
                            $ipaddr = preg_replace('/%.*$/', '', $ipaddr);
                        }
                        if (ip_checkparse($ipaddr) === false) {
                            continue 2;
                        }
                        // 2 because of switch
                        /* ip_parse throws exception on parse errors */
                        $ip6_bin = ip_parse($ipaddr);
                        $ipaddr = ip_format($ip6_bin);
                        $node = constructIPRange($ip6_bin, $maskbits);
                        $linklocal = $node['ip'] == 'fe80::';
                        $createipaddr = FALSE;
                        break;
                }
                //switch
                $address = getIPAddress(ip_parse($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' => $ipobject_id, 'hl_ipv4_addr' => $ipaddr));
                }
                /* reserved addresses */
                if ($address['reserved'] == 'yes') {
                    $comment .= ', ' . $address['ip'] . ' reserved ' . $address['name'];
                    $createipaddr = FALSE;
                    //	$disableipaddr = TRUE;
                }
                if ($ipaddr == '127.0.0.1' || $ipaddr == '0.0.0.0' || $ipaddr == '::1' || $ipaddr == '::' || $linklocal) {
                    $createipaddr = FALSE;
                    $disableipaddr = TRUE;
                }
                if ($ipaddr === $bcast) {
                    $comment .= ", {$ipaddr} broadcast";
                    $createipaddr = FALSE;
                    $disableipaddr = TRUE;
                }
                if (!$disableipaddr) {
                    $ipaddrcheckbox = '<b style="background-color:' . ($disableipaddr ? '#ff0000' : '#00ff00') . '"><input class="' . $inputname . 'addr" style="background-color:' . ($disableipaddr ? '#ff0000' : '#00ff00') . '" type="checkbox" name="' . $inputname . 'addrcreate[' . $ipaddr . ']" value="' . $if . '"' . ($disableipaddr ? ' disabled="disabled"' : '') . ($createipaddr ? ' checked="checked"' : '') . '></b>';
                } else {
                    $ipaddrcheckbox = '';
                }
                $ipaddrcell .= "<tr><td>{$ipaddrcheckbox}</td>";
                if (!empty($ipaddrhref)) {
                    $ipaddrcell .= "<td><a href={$ipaddrhref}>{$ipaddr}/{$maskbits}</a></td></tr>";
                } else {
                    $ipaddrcell .= "<td>{$ipaddr}/{$maskbits}</td></tr>";
                }
            }
            // foreach
            unset($ipaddr);
            unset($value);
            $ipaddrcell .= '</table>';
            // if(!empty($ipaddresses))
        } else {
            $ipaddrcreatecheckbox = '';
            $ipaddrcell = '';
        }
        /* checkboxes for add port and add ip */
        /* FireFox needs <b style=..>, IE and Opera work with <td style=..> */
        if (!$disableport) {
            $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>';
        } else {
            $portcreatecheckbox = '';
        }
        /* port type id */
        /* add port type to newporttypeoptions if missing */
        if (strpos(serialize($newporttypeoptions), $porttypeid) === FALSE) {
            $portids = explode('-', $porttypeid);
            $oif_name = $sg_portoifoptions[$portids[1]];
            $newporttypeoptions['auto'] = array($porttypeid => "*{$oif_name}");
        }
        $selectoptions = array('name' => "porttypeid[{$if}]");
        if ($disableport && !$updateporttype) {
            $selectoptions['disabled'] = "disabled";
        }
        $updateporttypecheckbox = "";
        if ($updateporttype) {
            $updateporttypecheckbox = '<b style="background-color:#00ff00;">' . '<input class="porttype" style="background-color:#00ff00;" type="checkbox" name="updateporttype[' . $if . ']" value="' . $port_info['id'] . '"></b>';
        }
        $porttypeidselect = getNiftySelect($newporttypeoptions, $selectoptions, $porttypeid);
        $updatelabelcheckbox = "";
        if ($updatelabel) {
            $updatelabelcheckbox = '<b style="background-color:#00ff00;">' . '<input class="label" style="background-color:#00ff00;" type="checkbox" name="updatelabel[' . $if . ']" value="' . $port_info['id'] . ($updatelabel ? '" checked="checked"' : '') . '></b>';
        }
        $comment = trim($comment, ', ');
        $ifsnmp->printifInfoTableRow($if, "<td>{$ipaddrcell}</td><td>{$portcreatecheckbox}</td><td>{$updatelabelcheckbox}</td><td>{$updatemaccheckbox}</td><td>{$updateporttypecheckbox}</td><td>{$porttypeidselect}</td><td nowrap=\"nowrap\">{$comment}</td>", $hrefs);
    }
    unset($if);
    /* preserve snmpconfig */
    foreach ($_POST as $key => $value) {
        echo '<input type=hidden name=' . $key . ' value=' . $value . ' />';
    }
    unset($key);
    unset($value);
    echo '<tr><td colspan=15 align="right"><p><input id="createbutton" type=submit value="Create Ports and IPs" onclick="return confirm(\'Create selected items?\')"></p></td></tr></tbody></table></form>';
}
Exemplo n.º 7
0
function handlePackageError($error)
{
    showWarning($error['description']);
    $actionList = $error['actions'];
    $actionList = getExtraActions($actionList);
    showPackageActions($actionList);
    $actions = array_keys($actionList);
    $actions = '[' . implode('], [', $actions) . ']';
    $userInput = getUserInput("    Plese choose one of the following actions( {$actions} ): ");
    return $userInput;
}
Exemplo n.º 8
0
            postInstallAdminSiteaccessINIUpdate($params);
            postInstallUserSiteaccessINIUpdate($params);
            createTranslationSiteAccesses($params);
            // updateTemplateLookClassAttributes() and updateTemplateLookObjectAttributes();
            $classIdentifier = 'template_look';
            $newAttributeIdArr = expandClass($classIdentifier);
            foreach ($newAttributeIdArr as $id) {
                updateObject($classIdentifier, $id);
            }
            $templateLookData = templateLookObjectData($params);
            $siteInstaller->updateContentObjectAttributes(array('object_id' => $webinInstaller->setting('template_look_object_id'), 'attributes_data' => $templateLookData));
            $siteInstaller->swapNodes(array('src_node' => array('name' => "eZ Publish"), 'dst_node' => array('name' => "Home")));
            $siteInstaller->removeContentObject(array('name' => 'eZ Publish'));
            $webinInstaller->postInstall();
        }
        //
        // Output installation status.
        //
        showMessage2('Installation complete.');
        showMessage('URLs to access eZWebin sites:');
        foreach ($siteaccessUrls as $siteaccessType => $siteaccessInfo) {
            showMessage("  {$siteaccessType}:");
            foreach ($siteaccessInfo as $siteaccessName => $urlInfo) {
                showMessage("    {$siteaccessName}: " . $urlInfo['url']);
            }
        }
    } else {
        showWarning("Unable to find installation script dir.");
    }
}
$script->shutdown(0, 'Done');
Exemplo n.º 9
0
function queryTerminal($object_id, $commands, $tolerate_remote_errors = TRUE)
{
    $objectInfo = spotEntity('object', $object_id);
    $endpoints = findAllEndpoints($object_id, $objectInfo['name']);
    if (count($endpoints) == 0) {
        throw new RTGatewayError('no management address set');
    }
    if (count($endpoints) > 1) {
        throw new RTGatewayError('cannot pick management address');
    }
    // telnet prompt and mode specification
    switch ($breed = detectDeviceBreed($object_id)) {
        case 'ios12':
        case 'fdry5':
        case 'ftos8':
            $protocol = 'netcat';
            // default is netcat mode
            $prompt = '^(Login|Username|Password): $|^\\S+[>#]$';
            // set the prompt in case user would like to specify telnet protocol
            break;
        case 'air12':
            $protocol = 'telnet';
            # Aironet IOS is broken
            $prompt = '^(Username|Password): $|^\\S+[>#]$';
            break;
        case 'vrp53':
        case 'vrp55':
            $protocol = 'telnet';
            $prompt = '^\\[[^[\\]]+\\]$|^<[^<>]+>$|^(Username|Password):$|(?:\\[Y\\/N\\]|\\(Y\\/N\\)\\[[YN]\\]):?$';
            break;
        case 'nxos4':
            $protocol = 'telnet';
            $prompt = '(^([Ll]ogin|[Pp]assword):|[>#]) $';
            break;
        case 'xos12':
            $protocol = 'telnet';
            $prompt = ': $|\\.\\d+ # $|\\?\\s*\\([Yy]\\/[Nn]\\)\\s*$';
            break;
        case 'jun10':
            $protocol = 'telnet';
            $prompt = '^login: $|^Password:$|^\\S+@\\S+[>#] $';
            break;
        case 'eos4':
            $protocol = 'telnet';
            # strict RFC854 implementation, netcat won't work
            $prompt = '^(\\xf2?login|Username|Password): $|^\\S+[>#]$';
            break;
        case 'ros11':
            $protocol = 'netcat';
            # see ftos8 case
            $prompt = '^(User Name|\\rPassword):$|^\\r?\\S+# $';
            break;
        case 'iosxr4':
            $protocol = 'telnet';
            $prompt = '^\\r?(Login|Username|Password): $|^\\r?\\S+[>#]$';
            break;
        case 'ucs':
            $protocol = 'ucssdk';
            break;
        default:
            $protocol = 'netcat';
            $prompt = NULL;
    }
    // set the default settings before calling user-defined callback
    $settings = array('hostname' => $endpoints[0], 'protocol' => $protocol, 'port' => NULL, 'prompt' => $prompt, 'username' => NULL, 'password' => NULL, 'timeout' => 15, 'connect_timeout' => 2, 'prompt_delay' => 0.001, 'sudo_user' => NULL, 'identity_file' => NULL);
    if (is_callable('terminal_settings')) {
        call_user_func('terminal_settings', $objectInfo, array(&$settings));
    }
    // override settings
    if (!isset($settings['port']) and $settings['protocol'] == 'netcat') {
        $settings['port'] = 23;
    }
    $params = array($settings['hostname']);
    $params_from_settings = array();
    switch ($settings['protocol']) {
        case 'telnet':
        case 'netcat':
            // prepend command list with vendor-specific disabling pager command
            switch ($breed) {
                case 'ios12':
                    $commands = "terminal length 0\n" . $commands;
                    break;
                case 'nxos4':
                case 'air12':
                case 'ftos8':
                    $commands = "terminal length 0\nterminal no monitor\n" . $commands;
                    break;
                case 'xos12':
                    $commands = "disable clipaging\n" . $commands;
                    break;
                case 'vrp55':
                    $commands = "screen-length 0 temporary\n" . $commands;
                    break;
                case 'fdry5':
                    $commands = "skip-page-display\n" . $commands;
                    break;
                case 'jun10':
                    $commands = "set cli screen-length 0\n" . $commands;
                    break;
                case 'eos4':
                    $commands = "enable\nno terminal monitor\nterminal length 0\n" . $commands;
                    break;
                case 'ros11':
                    $commands = "terminal datadump\n" . $commands;
                    $commands .= "\n\n";
                    # temporary workaround for telnet server
                    break;
                case 'iosxr4':
                    $commands = "terminal length 0\nterminal monitor disable\n" . $commands;
                    break;
                case 'dlink':
                    $commands = "disable clipaging\n" . $commands;
                    break;
            }
            // prepend telnet commands by credentials
            if (isset($settings['password'])) {
                $commands = $settings['password'] . "\n" . $commands;
            }
            if (isset($settings['username'])) {
                $commands = $settings['username'] . "\n" . $commands;
            }
            // command-line options are specific to client: telnet or netcat
            switch ($settings['protocol']) {
                case 'telnet':
                    $params_from_settings['port'] = 'port';
                    $params_from_settings['prompt'] = 'prompt';
                    $params_from_settings['connect-timeout'] = 'connect_timeout';
                    $params_from_settings['timeout'] = 'timeout';
                    $params_from_settings['prompt-delay'] = 'prompt_delay';
                    break;
                case 'netcat':
                    $params_from_settings['p'] = 'port';
                    $params_from_settings['w'] = 'timeout';
                    $params_from_settings['b'] = 'ncbin';
                    break;
            }
            break;
        case 'ssh':
            $params_from_settings['port'] = 'port';
            $params_from_settings['proto'] = 'proto';
            $params_from_settings['username'] = '******';
            $params_from_settings['i'] = 'identity_file';
            $params_from_settings['sudo-user'] = '******';
            $params_from_settings['connect-timeout'] = 'connect_timeout';
            break;
        case 'ucssdk':
            # remote XML through a Python backend
            $params = array();
            # reset
            # UCS in its current implementation besides the terminal_settings() provides
            # an additional username/password feed through the HTML from. Whenever the
            # user provides the credentials through the form, use these instead of the
            # credentials [supposedly] set by terminal_settings().
            if ($script_mode != TRUE && !isCheckSet('use_terminal_settings')) {
                genericAssertion('ucs_login', 'string');
                genericAssertion('ucs_password', 'string');
                $settings['username'] = $_REQUEST['ucs_login'];
                $settings['password'] = $_REQUEST['ucs_password'];
            }
            foreach (array('hostname', 'username', 'password') as $item) {
                if (empty($settings[$item])) {
                    throw new RTGatewayError("{$item} not available, check terminal_settings()");
                }
            }
            $commands = "login {$settings['hostname']} {$settings['username']} {$settings['password']}\n" . $commands;
            break;
        default:
            throw RTGatewayError("Invalid terminal protocol '{$settings['protocol']}' specified");
    }
    foreach ($params_from_settings as $param_name => $setting_name) {
        if (isset($settings[$setting_name])) {
            if (is_int($param_name)) {
                $params[] = $settings[$setting_name];
            } else {
                $params[$param_name] = $settings[$setting_name];
            }
        }
    }
    callHook('alterTerminalParams', $object_id, $tolerate_remote_errors, array(&$settings['protocol']), array(&$params));
    $ret_code = callScript($settings['protocol'], $params, $commands, $out, $errors);
    if ($settings['protocol'] != 'ssh' || !$tolerate_remote_errors) {
        if (!empty($errors)) {
            throw new RTGatewayError("{$settings['protocol']} error: " . rtrim($errors));
        } elseif ($ret_code !== 0) {
            throw new RTGatewayError("{$settings['protocol']} error: result code {$ret_code}");
        }
    } elseif (!empty($errors)) {
        // ssh and tolerate and non-empty $errors
        foreach (explode("\n", $errors) as $line) {
            if (strlen($line)) {
                showWarning("{$settings['protocol']} {$settings['hostname']}: {$line}");
            }
        }
    }
    return strtr($out, array("\r" => ""));
    // cut ^M symbols
}
Exemplo n.º 10
0
<?php

$timeStart = microtime(true);
session_start();
ob_start();
if (empty($_SESSION)) {
    exit(header("Location: ../../index.php"));
}
require_once $_SESSION['File_Root'] . '/Kernel/Include.php';
require_once $_SESSION['File_Root'] . '/HTML/Header.php';
require_once 'Functions/SQL.php';
redirectToLogin($accountID, $linkRoot);
redirectToBattle($verifyBattle, $linkRoot);
?>

<br>
	<div class="panel panel-warning"> 
		<div class="panel-heading"></div>
		<div class="panel-body">
		<?php 
if ($totalWarning > 0) {
    showWarning($bdd, $accountID);
} else {
    echo $warning2;
}
?>
		</div>
	</div>

<?php 
require_once $_SESSION['File_Root'] . '/HTML/Footer.php';
Exemplo n.º 11
0
function queryTerminal($object_id, $commands, $tolerate_remote_errors = TRUE)
{
    $objectInfo = spotEntity('object', $object_id);
    $endpoints = findAllEndpoints($object_id, $objectInfo['name']);
    if (count($endpoints) == 0) {
        throw new RTGatewayError('no management address set');
    }
    if (count($endpoints) > 1) {
        throw new RTGatewayError('cannot pick management address');
    }
    // telnet prompt and mode specification
    switch ($breed = detectDeviceBreed($object_id)) {
        case 'ios12':
        case 'ftos8':
            $protocol = 'netcat';
            // default is netcat mode
            $prompt = '^(Login|[Uu]sername|Password): $|^\\S+[>#]$|\\[[^][]*\\]\\? $';
            // set the prompt in case user would like to specify telnet protocol
            $commands = "terminal length 0\nterminal no monitor\n" . $commands;
            break;
        case 'air12':
            $protocol = 'telnet';
            # Aironet IOS is broken
            $prompt = '^(Username|Password): $|^\\S+[>#]$';
            $commands = "terminal length 0\nterminal no monitor\n" . $commands;
            break;
        case 'fdry5':
            $protocol = 'netcat';
            // default is netcat mode
            $prompt = '^(Login|Username|Password): $|^\\S+[>#]$';
            // set the prompt in case user would like to specify telnet protocol
            $commands = "skip-page-display\n" . $commands;
            break;
        case 'vrp55':
        case 'vrp85':
            $commands = "screen-length 0 temporary\n" . $commands;
            /* fall-through */
        /* fall-through */
        case 'vrp53':
            $protocol = 'telnet';
            $prompt = '^\\[[^[\\]]+\\]$|^<[^<>]+>$|^(Username|Password):$|\\[[Yy][^\\[\\]]*\\]\\s*:?\\s*$';
            break;
        case 'nxos4':
            $protocol = 'telnet';
            $prompt = '(^([Ll]ogin|[Pp]assword):|[>#]) $';
            $commands = "terminal length 0\nterminal no monitor\n" . $commands;
            break;
        case 'xos12':
            $protocol = 'telnet';
            $prompt = ': $|\\.\\d+ # $|\\?\\s*\\([Yy]\\/[Nn]\\)\\s*$';
            $commands = "disable clipaging\n" . $commands;
            break;
        case 'jun10':
            $protocol = 'telnet';
            $prompt = '^login: $|^Password:$|^\\S+@\\S+[>#] $';
            $commands = "set cli screen-length 0\n" . $commands;
            break;
        case 'eos4':
            $protocol = 'telnet';
            # strict RFC854 implementation, netcat won't work
            $prompt = '^\\xf2?(login|Username|Password): $|^\\S+[>#]$';
            $commands = "enable\nno terminal monitor\nterminal length 0\n" . $commands;
            break;
        case 'ros11':
            $protocol = 'netcat';
            # see ftos8 case
            $prompt = '^(User Name|\\rPassword):$|^\\r?\\S+# $';
            $commands = "terminal datadump\n" . $commands;
            $commands .= "\n\n";
            # temporary workaround for telnet server
            break;
        case 'iosxr4':
            $protocol = 'telnet';
            $prompt = '^\\r?(Login|Username|Password): $|^\\r?\\S+[>#]$';
            $commands = "terminal length 0\nterminal monitor disable\n" . $commands;
            break;
        case 'ucs':
            $protocol = 'ucssdk';
            break;
        case 'dlink':
            $protocol = 'netcat';
            $commands = "disable clipaging\n" . $commands;
            break;
    }
    if (!isset($protocol)) {
        $protocol = 'netcat';
    }
    if (!isset($prompt)) {
        $prompt = NULL;
    }
    // set the default settings before calling user-defined callback
    $settings = array('hostname' => $endpoints[0], 'protocol' => $protocol, 'port' => NULL, 'prompt' => $prompt, 'username' => NULL, 'password' => NULL, 'timeout' => 15, 'connect_timeout' => 2, 'prompt_delay' => 0.001, 'sudo_user' => NULL, 'identity_file' => NULL);
    // override default settings
    if (is_callable('terminal_settings')) {
        call_user_func('terminal_settings', $objectInfo, array(&$settings));
    }
    // make gateway-specific CLI params out of settings
    $params = callHook('makeGatewayParams', $object_id, $tolerate_remote_errors, array(&$settings), array(&$commands));
    // call gateway
    $ret_code = callScript($settings['protocol'], $params, $commands, $out, $errors);
    if ($settings['protocol'] != 'ssh' || !$tolerate_remote_errors) {
        if (!empty($errors)) {
            throw new RTGatewayError("{$settings['protocol']} error: " . rtrim($errors));
        } elseif ($ret_code !== 0) {
            throw new RTGatewayError("{$settings['protocol']} error: result code {$ret_code}");
        }
    } elseif (!empty($errors)) {
        // ssh and tolerate and non-empty $errors
        foreach (explode("\n", $errors) as $line) {
            if (strlen($line)) {
                showWarning("{$settings['protocol']} {$settings['hostname']}: {$line}");
            }
        }
    }
    return strtr($out, array("\r" => ""));
    // cut ^M symbols
}
Exemplo n.º 12
0
    mkdir($sessdir, 0777);
}
ini_set('session.save_path', $sessdir);
function ae_nocache()
{
    header("Expires: Tue, 03 Jul 2001 06:00:00 GMT");
    header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
    header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
    header("Cache-Control: post-check=0, pre-check=0", false);
    header("Pragma: no-cache");
}
ae_nocache();
session_start();
ini_set('display_errors', 1);
require_once "../auth.lib.php";
require_once "../mysql.inc.php";
mysqlConnect();
if (!checkSessionAuth()) {
    showWarning(1);
    exit(1);
}
if (isLevelCompleted($LEVELNAME)) {
    showWarning(2);
    exit(1);
}
$USERLOGGEDIN = true;
updateUserAttempt($LEVELNAME);
$LEVELPOINTS = getLevelPoints($LEVELNAME);
?>

Exemplo n.º 13
0
 function _printportlink($src_port_id, $dst_port_id, &$dst_link, $back = FALSE)
 {
     global $lm_multilink_port_types;
     $multilink = LM_MULTILINK;
     if (!isset($this->list[$dst_port_id])) {
         /* get port not in list */
         //	echo "<td>AHHH $src_port_id $dst_port_id --> $back</td>";
         //	echo "<td>load".$this->var_dump_html($dst_link)." tree</td>";
         //		echo "<td>".$dst_link['cable']." ".$dst_link['name']."</td><td>not displayed</td>";
         if ($back) {
             echo "<td>></td>";
         }
         // TODO check if multilink is needed here
         $this->printport($dst_link, $multilink && in_array($dst_link['type'], $lm_multilink_port_types));
         echo "<td>...</td>";
         return TRUE;
         //	$this->_getportlist($this->list[$src_port_id], $back, !$back);
     }
     $dst_port = $this->list[$dst_port_id];
     $object_id = $dst_port['object_id'];
     $obj_name = $dst_port['obj_name'];
     if ($obj_name == NULL) {
         $tmpobj = spotEntity('object', $dst_port['object_id']);
         $dst_port['obj_name'] = $tmpobj['dname'];
         $obj_name = $tmpobj['dname'];
     }
     $loop = FALSE;
     $edgeport = $dst_link == NULL || empty($dst_port['front']) || empty($dst_port['back']);
     if ($back) {
         $linktype = 'back';
     } else {
         $linktype = 'front';
     }
     $sameobject = FALSE;
     if (isset($dst_link['loop'])) {
         $loop = TRUE;
     }
     if ($dst_link != NULL) {
         $src_object_id = $this->list[$src_port_id]['object_id'];
         if (!$this->allback && $object_id == $src_object_id && $back) {
             $sameobject = TRUE;
         } else {
             $this->printlink($src_port_id, $dst_link, $linktype);
         }
     } else {
         $this->_printlinkportsymbol($dst_port_id, $linktype);
         $edgeport = true;
         if (!$back) {
             $this->printcomment($dst_port);
         }
     }
     if ($back) {
         if (!$sameobject) {
             $this->printobject($object_id, $obj_name);
         }
         echo "<td>></td>";
         /* align ports nicely */
         if ($dst_port['id'] == $this->port_id) {
             echo '</td></tr></table id=printportlink1></td><td><table align=left><tr>';
         }
     }
     /* print [portname] */
     // TODO check multilink symbols front/back edgeports
     $this->printport($dst_port, $multilink && in_array($dst_port['type'], $lm_multilink_port_types));
     if ($loop) {
         echo '<td bgcolor=#ff9966>LOOP</td>';
     }
     if (!$back) {
         /* align ports nicely */
         if ($dst_port['id'] == $this->port_id) {
             echo '</td></tr></table id=printportlink2></td><td><table align=left><tr>';
         }
         echo "<td><</td>";
         $this->printobject($object_id, $obj_name);
         if (empty($dst_port['back'])) {
             $this->_printlinkportsymbol($dst_port_id, 'back');
         }
     } else {
         if (empty($dst_port['front'])) {
             $this->printcomment($dst_port);
             $this->_printlinkportsymbol($dst_port_id, 'front');
         }
     }
     if ($loop) {
         if (isset($dst_link['loopmaxcount'])) {
             $reason = " (MAX LOOP COUNT reached)";
         } else {
             $reason = '';
         }
         showWarning("Possible Loop on Port ({$linktype}) " . $dst_port['name'] . $reason);
         return FALSE;
     }
     return TRUE;
 }
Exemplo n.º 14
0
        $ver = trim($recent['version']);
        $uri = trim($recent['uri']);
        $msg = trim($recent['message']);
        if ($pretty) {
            $out .= '<ul>
			<li>Your version: <strong>' . $version . '</strong></li>
			<li>Latest version: <strong>' . $ver . '</strong></li>
			<li>&nbsp;</li>';
            if ($recent['is_testing']) {
                $out .= '<li><strong>There is a newer testing version of Froxlor available, please update.</strong></li>';
            } else {
                $out .= '<li><strong>There is a newer version of Froxlor available, please update.</strong></li>';
            }
            if ($uri != '') {
                $out .= '<li>&nbsp;</li>
				<li><a href="' . $uri . '">' . $uri . '</a></li>';
            }
            if ($msg != '') {
                $out .= '<li>&nbsp;</li>
				<li>Info: ' . $msg . '</li>';
            }
            $out .= '</ul>';
            showWarning($out);
        } else {
            echo $ver . '|' . $uri . '|' . $msg;
        }
    }
}
if ($pretty) {
    echo htmlFooter();
}
Exemplo n.º 15
0
<?php

/****************************************************************************
* Name:        about.php
* Author:      Ben Barnes
* Date:        2016-02-20
* Purpose:     About page
*****************************************************************************/
getGlobals_about($getPage_connection2);
showTitle("About");
compileMenu($getPage_connection2, "about");
showWarning($getPage_connection2);
showPageTitle($getPage_connection2, "About", false);
showAboutInfo($getPage_connection2);
require "section4.txt";
resetSession(true);
Exemplo n.º 16
0
function renderDiscoveredNeighbors($object_id)
{
    global $tabno;
    $opcode_by_tabno = array('livecdp' => 'getcdpstatus', 'livelldp' => 'getlldpstatus');
    try {
        $neighbors = queryDevice($object_id, $opcode_by_tabno[$tabno]);
        $neighbors = sortPortList($neighbors);
    } catch (RTGatewayError $e) {
        showWarning($e->getMessage());
        return;
    }
    $mydevice = spotEntity('object', $object_id);
    amplifyCell($mydevice);
    // reindex by port name
    $myports = array();
    foreach ($mydevice['ports'] as $port) {
        if (mb_strlen($port['name'])) {
            $myports[$port['name']][] = $port;
        }
    }
    // scroll to selected port
    if (isset($_REQUEST['hl_port_id'])) {
        assertUIntArg('hl_port_id');
        $hl_port_id = intval($_REQUEST['hl_port_id']);
        addAutoScrollScript("port-{$hl_port_id}");
    }
    switchportInfoJS($object_id);
    // load JS code to make portnames interactive
    printOpFormIntro('importDPData');
    echo '<br><table cellspacing=0 cellpadding=5 align=center class=widetable>';
    echo '<tr><th colspan=2>local port</th><th></th><th>remote device</th><th colspan=2>remote port</th><th><input type="checkbox" checked id="cb-toggle"></th></tr>';
    $inputno = 0;
    foreach ($neighbors as $local_port => $remote_list) {
        $initial_row = TRUE;
        // if port has multiple neighbors, the first table row is initial
        // array of local ports with the name specified by DP
        $local_ports = isset($myports[$local_port]) ? $myports[$local_port] : array();
        foreach ($remote_list as $dp_neighbor) {
            $error_message = NULL;
            $link_matches = FALSE;
            $portinfo_local = NULL;
            $portinfo_remote = NULL;
            $variants = array();
            do {
                // once-cyle fake loop used only to break out of it
                if (!empty($local_ports)) {
                    $portinfo_local = $local_ports[0];
                }
                // find remote object by DP information
                $dp_remote_object_id = searchByMgmtHostname($dp_neighbor['device']);
                if (!$dp_remote_object_id) {
                    $dp_remote_object_id = lookupEntityByString('object', $dp_neighbor['device']);
                }
                if (!$dp_remote_object_id) {
                    $error_message = "No such neighbor <i>{$dp_neighbor['device']}</i>";
                    break;
                }
                $dp_remote_object = spotEntity('object', $dp_remote_object_id);
                amplifyCell($dp_remote_object);
                // get port list which names match CDP portname
                $remote_ports = array();
                // list of remote (by DP info) ports
                foreach ($dp_remote_object['ports'] as $port) {
                    if ($port['name'] == $dp_neighbor['port']) {
                        $portinfo_remote = $port;
                        $remote_ports[] = $port;
                    }
                }
                // check if ports with such names exist on devices
                if (empty($local_ports)) {
                    $error_message = "No such local port <i>{$local_port}</i>";
                    break;
                }
                if (empty($remote_ports)) {
                    $error_message = "No such port on " . formatPortLink($dp_remote_object['id'], $dp_remote_object['name'], NULL, NULL);
                    break;
                }
                // determine match or mismatch of local link
                foreach ($local_ports as $portinfo_local) {
                    if ($portinfo_local['remote_id']) {
                        if ($portinfo_local['remote_object_id'] == $dp_remote_object_id and $portinfo_local['remote_name'] == $dp_neighbor['port']) {
                            // set $portinfo_remote to corresponding remote port
                            foreach ($remote_ports as $portinfo_remote) {
                                if ($portinfo_remote['id'] == $portinfo_local['remote_id']) {
                                    break;
                                }
                            }
                            $link_matches = TRUE;
                            unset($error_message);
                        } elseif ($portinfo_local['remote_object_id'] != $dp_remote_object_id) {
                            $error_message = "Remote device mismatch - port linked to " . formatLinkedPort($portinfo_local);
                        } else {
                            // ($portinfo_local['remote_name'] != $dp_neighbor['port'])
                            $error_message = "Remote port mismatch - port linked to " . formatPortLink($portinfo_local['remote_object_id'], NULL, $portinfo_local['remote_id'], $portinfo_local['remote_name']);
                        }
                        break 2;
                    }
                }
                // no local links found, try to search for remote links
                foreach ($remote_ports as $portinfo_remote) {
                    if ($portinfo_remote['remote_id']) {
                        $remote_link_html = formatLinkedPort($portinfo_remote);
                        $remote_port_html = formatPortLink($portinfo_remote['object_id'], NULL, $portinfo_remote['id'], $portinfo_remote['name']);
                        $error_message = "Remote port {$remote_port_html} is already linked to {$remote_link_html}";
                        break 2;
                    }
                }
                // no links found on both sides, search for a compatible port pair
                $port_types = array();
                foreach (array('left' => $local_ports, 'right' => $remote_ports) as $side => $port_list) {
                    foreach ($port_list as $portinfo) {
                        $tmp_types = $portinfo['iif_id'] == 1 ? array($portinfo['oif_id'] => $portinfo['oif_name']) : getExistingPortTypeOptions($portinfo['id']);
                        foreach ($tmp_types as $oif_id => $oif_name) {
                            $port_types[$side][$oif_id][] = array('id' => $oif_id, 'name' => $oif_name, 'portinfo' => $portinfo);
                        }
                    }
                }
                foreach ($port_types['left'] as $left_id => $left) {
                    foreach ($port_types['right'] as $right_id => $right) {
                        if (arePortTypesCompatible($left_id, $right_id)) {
                            foreach ($left as $left_port) {
                                foreach ($right as $right_port) {
                                    $variants[] = array('left' => $left_port, 'right' => $right_port);
                                }
                            }
                        }
                    }
                }
                if (!count($variants)) {
                    // no compatible ports found
                    $error_message = "Incompatible port types";
                }
            } while (FALSE);
            // do {
            $tr_class = $link_matches ? 'trok' : (isset($error_message) ? 'trerror' : 'trwarning');
            echo "<tr class=\"{$tr_class}\">";
            if ($initial_row) {
                $count = count($remote_list);
                $td_class = '';
                if (isset($hl_port_id) and $hl_port_id == $portinfo_local['id']) {
                    $td_class = "class='border_highlight'";
                }
                echo "<td rowspan=\"{$count}\" {$td_class} NOWRAP>" . ($portinfo_local ? formatPortLink($mydevice['id'], NULL, $portinfo_local['id'], $portinfo_local['name'], 'interactive-portname port-menu') : "<a class='interactive-portname port-menu nolink'>{$local_port}</a>") . ($count > 1 ? "<br> ({$count} neighbors)" : '') . '</td>';
                $initial_row = FALSE;
            }
            echo "<td>" . ($portinfo_local ? formatPortIIFOIF($portinfo_local) : '&nbsp') . "</td>";
            echo "<td>" . formatIfTypeVariants($variants, "ports_{$inputno}") . "</td>";
            echo "<td>{$dp_neighbor['device']}</td>";
            echo "<td>" . ($portinfo_remote ? formatPortLink($dp_remote_object_id, NULL, $portinfo_remote['id'], $portinfo_remote['name']) : $dp_neighbor['port']) . "</td>";
            echo "<td>" . ($portinfo_remote ? formatPortIIFOIF($portinfo_remote) : '&nbsp') . "</td>";
            echo "<td>";
            if (!empty($variants)) {
                echo "<input type=checkbox name=do_{$inputno} class='cb-makelink'>";
                $inputno++;
            }
            echo "</td>";
            if (isset($error_message)) {
                echo "<td style=\"background-color: white; border-top: none\">{$error_message}</td>";
            }
            echo "</tr>";
        }
    }
    if ($inputno) {
        echo "<input type=hidden name=nports value={$inputno}>";
        echo '<tr><td colspan=7 align=center>' . getImageHREF('CREATE', 'import selected', TRUE) . '</td></tr>';
    }
    echo '</table></form>';
    addJS(<<<END
\$(document).ready(function () {
\t\$('#cb-toggle').click(function (event) {
\t\tvar list = \$('.cb-makelink');
\t\tfor (var i in list) {
\t\t\tvar cb = list[i];
\t\t\tcb.checked = event.target.checked;
\t\t}
\t}).triggerHandler('click');
});
END
, TRUE);
}
Exemplo n.º 17
0
if ($autoMode != 'off') {
    $autoMode = 'on';
    $importDir = eZPackage::repositoryPath() . "/{$packageRepository}";
    showWarning("Processing in auto-mode: \n" . "- packages will be downloaded to '{$packageDir}';\n" . "- packages will be imported to '{$importDir}';\n" . "- installing of existing classes will be skipped;\n" . "- all files(extesion, design, downloaded and imported packages) will be overwritten;");
    $action = getUserInput("Continue? [y/n]: ");
    if (strpos($action, 'y') !== 0) {
        $script->shutdown(0, 'Done');
    }
}
/**************************************************************
* do the work                                                 *
***************************************************************/
if (downloadPackages($packageList, $packageURL, $packageDir, $packageRepository)) {
    // install
    installPackages($packageList);
}
if (file_exists(installScriptDir($packageRepository, 'ezwebin_site'))) {
    include_once installScriptDir($packageRepository, 'ezwebin_site') . "/settings/ezwebininstaller.php";
    include_once installScriptDir($packageRepository, 'ezwebin_site') . "/settings/ini-site.php";
    include_once installScriptDir($packageRepository, 'ezwebin_site') . "/settings/ini-common.php";
    showMessage2("Updating content classes...");
    execUpdateFunction("updateClasses", $toVersion);
    showMessage2("Updating content objects...");
    execUpdateFunction("updateObjects", $toVersion);
    showMessage2("Updating INI-files...");
    execUpdateFunction("updateINI", $toVersion);
} else {
    showWarning("no data for updating content classes, objects, roles, ini");
}
showMessage2("Upgrade complete");
$script->shutdown(0);
Exemplo n.º 18
0
function setSwitchVLANs($object_id = 0, $setcmd)
{
    global $remote_username;
    $objectInfo = spotEntity('object', $object_id);
    $endpoints = findAllEndpoints($object_id, $objectInfo['name']);
    if (count($endpoints) == 0) {
        throw new RTGatewayError('no management address set');
    }
    if (count($endpoints) > 1) {
        throw new RTGatewayError('cannot pick management address');
    }
    $hwtype = $swtype = 'unknown';
    foreach (getAttrValues($object_id) as $record) {
        if ($record['name'] == 'SW type' && strlen($record['o_value'])) {
            $swtype = strtr(execGMarker($record['o_value']), ' ', '+');
        }
        if ($record['name'] == 'HW type' && strlen($record['o_value'])) {
            $hwtype = strtr(execGMarker($record['o_value']), ' ', '+');
        }
    }
    $endpoint = str_replace(' ', '+', $endpoints[0]);
    $data = queryGateway('switchvlans', array("connect {$endpoint} {$hwtype} {$swtype} {$remote_username}", $setcmd));
    // Finally we can parse the response into message array.
    foreach (explode(';', substr($data[1], strlen('OK!'))) as $text) {
        $message = 'gw: ' . substr($text, 2);
        if (strpos($text, 'I!') === 0) {
            showSuccess($message);
        } elseif (strpos($text, 'W!') === 0) {
            showWarning($message);
        } elseif (strpos($text, 'E!') === 0) {
            showError($message);
        } else {
            // All improperly formatted messages must be treated as error conditions.
            showError('unexpected line from gw: ' . $text);
        }
    }
}
Exemplo n.º 19
0
function cleanupUCS()
{
    global $ucsproductmap;
    $oinfo = spotEntity('object', getBypassValue());
    $contents = getObjectContentsList($oinfo['id']);
    $clear = TRUE;
    foreach ($contents as $item_id) {
        $o = spotEntity('object', $item_id);
        $attrs = getAttrValues($item_id);
        # use HW type to decide if the object was produced by autoPopulateUCS()
        if (!array_key_exists(2, $attrs) or !in_array($attrs[2]['key'], $ucsproductmap)) {
            showWarning('Contained object ' . mkA($o['dname'], 'object', $item_id) . ' is not an automatic UCS object');
            $clear = FALSE;
        }
    }
    if (!$clear) {
        showNotice('nothing was deleted');
        return;
    }
    $done = 0;
    foreach ($contents as $item_id) {
        commitDeleteObject($item_id);
        $done++;
    }
    showSuccess("Removed {$done} items from UCS Domain '{$oinfo['name']}'");
}
/**
* NOTE: What if other data is also in the db? Either we do not convert it and
*       have it most likely corrupted, or we convert it - and leave to the client
*       for the other apps to set up NLS_LANG correctly to keep working.
*
*       We could use the csalter script iff we where sure that db version was > 9...
*
*       Oracle 9 exp exports data using the DB charset
*
* From http://www.experts-exchange.com/Database/Oracle/Q_22836430.html

May be the best procedure is the following one:
On PROD Database:
1. export full=y rows=n file=export_db_structure.dmp
2. export full=y file=export_db_date.dmp
On TEST Database:
1. create tablespaces with the same name on PROD
2. import full=y file=export_db_structure.dmp ignore=y
Now we have users of PROD, on TEST database. SYSTEM user is not imported, because already exists.
3. import fromuser=user1,user2,user3 touser=user1,user2,user3  file=export_db_data.dmp ignore=y
now we have user1..3 data on their tables...

*       Unfortunately even if we do that, Oracle will nto let us convert a db from
*       latin1 to utf8 charsets. The only way is to drop the db and creater it
*       from scratch. Since we have no clue about db storage, we will let the admin
*       take care of that part, and only do the export/import parts.
*
* @todo oracle servers might use UTF8 charset instead of AL32UTF8: check before executing!
*
* @todo using dbname as file name does not work with easy conection naming
*
* @todo log somewhere results of imp, exp commands for better understanding of errors
*/
function changeDBCharsetORACLE($charset, $collation)
{
    global $db, $oracleDbaAccount, $oracleHome, $eZDir;
    //$db = eZDB::instance( false, array( 'user' => $oracleDbaAccount['user'], 'password' => $oracleDbaAccount['password'] ), true );
    // since we are here, we should be connected with a dba account (extra conditions check did it)
    $oracleCharset = $db->arrayQuery("select value from nls_database_parameters where parameter = 'NLS_CHARACTERSET'");
    $oracleCharset = $oracleCharset[0]['value'];
    //$oracleLocale = $db->arrayQuery("select language||'_'||territory as locale from (select value as language from nls_database_parameters where parameter = 'NLS_LANGUAGE'), (select value as territory from nls_database_parameters where parameter = 'NLS_TERRITORY')");
    //$oracleLocale = $oracleLocale[0]['locale'];
    /*$users = $db->arrayQuery("select username from all_users where username not in ('SYS', 'SYSTEM')");
      $oracleUsers = array();
      foreach( $users as $row )
      {
          $oracleUsers[] = $row['username'];
      }*/
    if ($oracleCharset == 'AL32UTF8') {
        // lucky case: client was configued to use another charset, but db was internally utf8 already!
        showMessage3("  database charset is already UTF8: skipping.");
    } else {
        // get database name
        $dbName = $db->DB;
        //$dbversion = $db->databaseServerVersion();
        // get connection params
        //$host = $db->Server;
        //$port = $db->Port;
        //$user = $db->User;
        //$pass = $db->Password;
        $connectionParams = $oracleDbaAccount['user'] . '/' . $oracleDbaAccount['password'] . "@{$dbName}";
        // get temporary dir to store dumps
        $ini = eZINI::instance();
        $dumpDir = $ini->variable('FileSettings', 'TemporaryDir') . basename(__FILE__, '.php');
        $dumpFile1 = $dbName . "_structure_export.dmp";
        $dumpPath1 = "{$dumpDir}/{$dumpFile1}";
        $dumpFile2 = $dbName . "_full_export.dmp";
        $dumpPath2 = "{$dumpDir}/{$dumpFile2}";
        $commandPath = "{$dumpDir}/{$dbName}" . "_cmd.sql";
        $logPath = "{$dumpDir}/{$dbName}" . "_cmd.log";
        $users = implode(',', $oracleUsers);
        //$ora_charset = "";
        // prepare utility commands
        $exe = eZSys::osType() == 'win32' ? '.exe' : '';
        $exec = eZSys::osType() == 'win32' ? '' : './';
        $expdb1 = "{$exec}exp{$exe} {$connectionParams} CONSISTENT=Y FULL=Y ROWS=N  FILE={$dumpPath1}";
        $expdb2 = "{$exec}exp{$exe} {$connectionParams} CONSISTENT=Y FULL=Y FILE={$dumpPath2}";
        $impdb1 = "{$exec}imp{$exe} {$connectionParams} FULL=Y IGNORE=Y BUFFER=30960 FILE={$dumpPath1}";
        $impdb2 = "{$exec}imp{$exe} {$connectionParams} FROMUSER={$users} TOUSER={$users} IGNORE=Y BUFFER=30960 FILE={$dumpPath2}";
        /*
        $alterdb = "SET ECHO ON
        SPOOL $logPath;
        WHENEVER SQLERROR EXIT FAILURE;
        WHENEVER OSERROR EXIT FAILURE;";
        if ( $dbversion['string'][0] == '8' )
        {
            /// @todo: check if using oracle < 8.1.5: we have touse svrmgrl then, as sqlplus was not good enough yet
            $sqlplus = "{$exec}sqlplus{$exe} $connectionParams";
            $alterdb .= "
        CONNECT $connectionParams AS SYSDBA";
        }
        else
        {
            $sqlplus = "{$exec}sqlplus{$exe} -L $connectionParams as sysdba";
        }
        
        //$dropdb = "dropdb $connectionParams";
        //$createdb = "createdb $connectionParams";
        foreach( $oracleUsers as $user )
        {
            $alterdb .= "
        DROP USER $user CASCADE;";
        }
        $alterdb .= "
        SHUTDOWN IMMEDIATE;
        STARTUP MOUNT;
        ALTER SYSTEM ENABLE RESTRICTED SESSION;
        ALTER SYSTEM SET JOB_QUEUE_PROCESSES=0;
        ALTER SYSTEM SET AQ_TM_PROCESSES=0;
        ALTER DATABASE OPEN;
        ALTER DATABASE CHARACTER SET AL32UTF8;
        SHUTDOWN IMMEDIATE; -- or SHUTDOWN NORMAL;
        STARTUP;
        EXIT;
        ";
        */
        // finalizing changes. Note that since we asked for admin connection before,
        // disconnecting and reconnecting, this is surely a NOOP
        //showMessage3( 'finalizing current changes' );
        //$db->commit();
        /// @todo add a database logfile switch or checkpoint here? it would be nice...
        // close current connection
        $db->close();
        showMessage3('  sleeping..');
        sleep(5);
        // dump db
        showMessage3("  taking the db dump, tmp storage is '{$dumpPath1}', '{$dumpPath2}'");
        eZDir::mkdir($dumpDir, false, true);
        chdir($oracleHome . '/bin');
        eZExecuteShellCommand($expdb1, "failed to dump db schema. tried command '{$expdb1}'", true, true);
        eZExecuteShellCommand($expdb2, "failed to dump db data. tried command '{$expdb2}'", true, true);
        chdir($eZDir);
        // verify that dump files exist
        if (!file_exists($dumpPath1) || !file_exists($dumpPath2)) {
            showError("DB Dump files cannot be found. Aborting...");
        }
        /*
        showMessage3( "altering db with charset '$charset'" );
        $command = $sqlplus . " @$commandPath";
        file_put_contents( $commandPath, $alterdb );
        eZExecuteShellCommand( $command, "failed to alter db. tried command '$command'");
        */
        showMessage3('');
        showMessage3("Now you will have to alter the database character set.");
        showMessage3("The recommended way is to create a new database from scratch");
        showMessage3("using AL32UTF8 as character set (THIS IS VERY IMPORTANT),");
        showMessage3("and delete the existing one.");
        showMessage3("The new database should be empty (all schemas will be recreated by this script)");
        showMessage3("and have the same DBA account as the old one.");
        showMessage3("It should also use the same connect identifier as the old one.");
        showMessage3('');
        showMessage3("PLEASE do not terminate this php script while doing that,");
        showMessage3("use a different command line shell.");
        showMessage3('');
        $continue = eZGetUserInput("Press Y when you are ready to continue... ");
        if ($continue != 'y' && $continue != 'Y') {
            showError("Aborting");
        }
        // connect to new db with dba account, check that charset is OK
        while (true) {
            $db = eZDB::instance(false, array('user' => $oracleDbaAccount['user'], 'password' => $oracleDbaAccount['password']), true);
            if (!$db->isConnected()) {
                showWarning("Cannot connect to the new database.\n" . "Please check that it is up and running before continuing");
            } else {
                $oracleCharset = $db->arrayQuery("select value from nls_database_parameters where parameter = 'NLS_CHARACTERSET'");
                $oracleCharset = $oracleCharset[0]['value'];
                $db->close();
                if ($oracleCharset == 'AL32UTF8') {
                    break;
                } else {
                    showWarning("The new database uses the {$oracleCharset} character set instead of AL32UTF8.\n" . "Please recreate the database using AL32UTF8 before continuing");
                }
            }
            $continue = eZGetUserInput("Press Y when you are ready to continue. Any other letter to abort ");
            if ($continue != 'y' && $continue != 'Y') {
                showError("Aborting");
            }
        }
        // restore dump into newly created db
        showMessage3("  restoring db dump");
        chdir($oracleHome . '/bin');
        eZExecuteShellCommand($impdb1, "failed to restore db dump. tried command '{$impdb1}'");
        eZExecuteShellCommand($impdb2, "failed to restore db dump. tried command '{$impdb2}'");
        chdir($eZDir);
        showMessage3("  cleaning up");
        // clean up
        eZDir::recursiveDelete($dumpPath1);
        eZDir::recursiveDelete($dumpPath2);
    }
    // re-initialize db interface, *** this time in UTF8 - with the standard user ***
    $db = eZDB::instance(false, array('charset' => 'utf8'), true);
    if (!$db->isConnected()) {
        showError("Cannot reconnect to DB. Aborting...");
    }
    //$db->begin();
}
Exemplo n.º 21
0
 if ($data['user_location']) {
     echo "<br /><span class='small'><strong>" . $locale['fb500'] . ":</strong> " . stripslash($data['user_location']) . "</span>\n";
 }
 if ($data['user_birthdate'] !== "0000-00-00") {
     $birthday = explode("-", $data['user_birthdate']);
     $age = strftime("%Y") - $birthday[0];
     if (strftime("%m") < $birthday[1]) {
         $age--;
     } elseif (strftime("%m") == $birthday[1]) {
         if (strftime("%d") < $birthday[2]) {
             $age--;
         }
     }
     echo "<br /><span class='small'><strong>" . $locale['fb512'] . "</strong> {$age}</span>\n";
 }
 echo showWarning($data['user_id']);
 echo "<br /></td>";
 echo "<td valign='top' class='tbl2' style='height:1px; margin-top:2px; padding:10px;' colspan='2'><div style='float:right' class='small'><a href='#post_" . $data['post_id'] . "' name='post_" . $data['post_id'] . "' id='post_" . $data['post_id'] . "'>#" . ($current_row + $_GET['rowstart']) . "</a></div>\n";
 echo "<span style='font-size:18px; font-weight:bold;'><a href='" . BASEDIR . "profile.php?lookup=" . $data['user_id'] . "'>" . showLabel($data['user_id'], false, "post") . "</a>";
 renderAwards($data['user_id']);
 echo "</span>";
 echo $title;
 renderMods(false, true);
 echo "</span>";
 echo "</td></tr><tr><td class='tbl1' colspan='2' valign='top' style='padding:8px;'>\n";
 if (iMOD) {
     echo "<div style='float:right'><input type='checkbox' name='delete_post[]' value='" . $data['post_id'] . "' /></div>\n";
 }
 if (isset($_GET['highlight'])) {
     $words = explode(" ", urldecode($_GET['highlight']));
     $message = parseubb(highlight_words($words, $message));
Exemplo n.º 22
0
function doSwitchSNMPmining($objectInfo, $device)
{
    global $known_switches, $iftable_processors;
    if (FALSE === ($sysObjectID = $device->snmpget('sysObjectID.0'))) {
        return showFuncMessage(__FUNCTION__, 'ERR3');
    }
    // // fatal SNMP failure
    $sysObjectID = preg_replace('/^.*(enterprises\\.|joint-iso-ccitt\\.)([\\.[:digit:]]+)$/', '\\2', $sysObjectID);
    $sysName = substr($device->snmpget('sysName.0'), strlen('STRING: '));
    $sysDescr = substr($device->snmpget('sysDescr.0'), strlen('STRING: '));
    $sysDescr = str_replace(array("\n", "\r"), " ", $sysDescr);
    // Make it one line
    $ifDescr_tablename = isset($known_switches[$sysObjectID]['ifDescrOID']) ? $known_switches[$sysObjectID]['ifDescrOID'] : 'ifDescr';
    if (!isset($known_switches[$sysObjectID])) {
        return showFuncMessage(__FUNCTION__, 'ERR4', array($sysObjectID));
    }
    // unknown OID
    showSuccess($known_switches[$sysObjectID]['text']);
    foreach (array_keys($known_switches[$sysObjectID]['processors']) as $pkey) {
        if (!array_key_exists($known_switches[$sysObjectID]['processors'][$pkey], $iftable_processors)) {
            showWarning('processor "' . $known_switches[$sysObjectID]['processors'][$pkey] . '" not found');
            unset($known_switches[$sysObjectID]['processors'][$pkey]);
        }
    }
    updateStickerForCell($objectInfo, 2, $known_switches[$sysObjectID]['dict_key']);
    updateStickerForCell($objectInfo, 3, $sysName);
    switch (1) {
        case preg_match('/^9\\.1\\./', $sysObjectID):
            // Catalyst w/one AC port
            $exact_release = preg_replace('/^.*, Version ([^ ]+), .*$/', '\\1', $sysDescr);
            $major_line = preg_replace('/^([[:digit:]]+\\.[[:digit:]]+)[^[:digit:]].*/', '\\1', $exact_release);
            $ios_codes = array('12.0' => 244, '12.1' => 251, '12.2' => 252);
            updateStickerForCell($objectInfo, 5, $exact_release);
            if (array_key_exists($major_line, $ios_codes)) {
                updateStickerForCell($objectInfo, 4, $ios_codes[$major_line]);
            }
            $sysChassi = $device->snmpget('1.3.6.1.4.1.9.3.6.3.0');
            if ($sysChassi !== FALSE or $sysChassi !== NULL) {
                updateStickerForCell($objectInfo, 1, str_replace('"', '', substr($sysChassi, strlen('STRING: '))));
            }
            checkPIC('1-29');
            commitAddPort($objectInfo['id'], 'con0', '1-29', 'console', '');
            // RJ-45 RS-232 console
            if (preg_match('/Cisco IOS Software, C2600/', $sysDescr)) {
                commitAddPort($objectInfo['id'], 'aux0', '1-29', 'auxillary', '');
            }
            // RJ-45 RS-232 aux port
            if ($sysObjectID == '9.1.956') {
                // models with two AC inputs
                checkPIC('1-16');
                commitAddPort($objectInfo['id'], 'AC-in-1', '1-16', 'AC1', '');
                commitAddPort($objectInfo['id'], 'AC-in-2', '1-16', 'AC2', '');
            } elseif ($sysObjectID != '9.1.749' and $sysObjectID != '9.1.920') {
                // assume the rest have one AC input, but exclude blade devices
                checkPIC('1-16');
                // AC input
                commitAddPort($objectInfo['id'], 'AC-in', '1-16', '', '');
            }
            break;
        case preg_match('/^9\\.6\\.1\\./', $sysObjectID):
            // Cisco SF series
            checkPIC('1-681');
            commitAddPort($objectInfo['id'], 'con0', '1-681', 'console', '');
            // DB-9 RS-232 console
            checkPIC('1-16');
            commitAddPort($objectInfo['id'], 'AC-in', '1-16', '', '');
            break;
        case preg_match('/^9\\.12\\.3\\.1\\.3\\./', $sysObjectID):
            // Nexus
            $exact_release = preg_replace('/^.*, Version ([^ ]+), .*$/', '\\1', $sysDescr);
            $major_line = preg_replace('/^([[:digit:]]+\\.[[:digit:]]+)[^[:digit:]].*/', '\\1', $exact_release);
            $nxos_codes = array('4.0' => 963, '4.1' => 964);
            if (array_key_exists($major_line, $nxos_codes)) {
                updateStickerForCell($objectInfo, 4, $nxos_codes[$major_line]);
            }
            updateStickerForCell($objectInfo, 5, $exact_release);
            $sysChassi = $device->snmpget('1.3.6.1.2.1.47.1.1.1.1.11.149');
            if ($sysChassi !== FALSE or $sysChassi !== NULL) {
                updateStickerForCell($objectInfo, 1, str_replace('"', '', substr($sysChassi, strlen('STRING: '))));
            }
            checkPIC('1-29');
            commitAddPort($objectInfo['id'], 'con0', '1-29', 'console', '');
            // RJ-45 RS-232 console
            checkPIC('1-16');
            // AC input
            commitAddPort($objectInfo['id'], 'AC-in-1', '1-16', 'AC1', '');
            commitAddPort($objectInfo['id'], 'AC-in-2', '1-16', 'AC2', '');
            break;
        case preg_match('/^11\\.2\\.3\\.7\\.11\\.(\\d+)$/', $sysObjectID, $matches):
            // ProCurve
            $console_per_product = array(33 => '1-29', 63 => '1-29', 78 => '1-29', 79 => '1-29', 80 => '1-29', 86 => '1-29', 87 => '1-29', 19 => '1-681');
            if (array_key_exists($matches[1], $console_per_product)) {
                checkPIC($console_per_product[$matches[1]]);
                commitAddPort($objectInfo['id'], 'console', $console_per_product[$matches[1]], 'console', '');
            }
            $oom_per_product = array(33 => '1-24');
            if (array_key_exists($matches[1], $oom_per_product)) {
                checkPIC($oom_per_product[$matches[1]]);
                commitAddPort($objectInfo['id'], 'mgmt', $oom_per_product[$matches[1]], 'mgmt', '');
            }
            checkPIC('1-16');
            commitAddPort($objectInfo['id'], 'AC-in', '1-16', '', '');
            $exact_release = preg_replace('/^.* revision ([^ ]+), .*$/', '\\1', $sysDescr);
            updateStickerForCell($objectInfo, 5, $exact_release);
            break;
        case preg_match('/^4526\\.100\\./', $sysObjectID):
            // NETGEAR
            checkPIC('1-681');
            commitAddPort($objectInfo['id'], 'console', '1-681', 'console', '');
            // DB-9 RS-232 console
            break;
        case preg_match('/^2011\\.2\\.23\\./', $sysObjectID):
            // Huawei
            detectSoftwareType($objectInfo, $sysDescr);
            checkPIC('1-681');
            commitAddPort($objectInfo['id'], 'con0', '1-681', 'console', '');
            // DB-9 RS-232 console
            break;
        case preg_match('/^2636\\.1\\.1\\.1\\.2\\.3(0|1)/', $sysObjectID):
            // Juniper EX3200/EX4200
            detectSoftwareType($objectInfo, $sysDescr);
            $sw_version = preg_replace('/^.*, kernel JUNOS ([^ ]+).*$/', '\\1', $sysDescr);
            updateStickerForCell($objectInfo, 5, $sw_version);
            // one RJ-45 RS-232 and one AC port (it could be DC, but chances are it's AC)
            checkPIC('1-29');
            commitAddPort($objectInfo['id'], 'con', '1-29', 'CON', '');
            // RJ-45 RS-232 console
            checkPIC('1-16');
            commitAddPort($objectInfo['id'], 'AC-in', '1-16', '', '');
            // Juniper uses the same sysObjectID for multiple HW models, override if necessary
            if (preg_match('/^Juniper Networks, Inc. ex3200-48t internet router/', $sysDescr)) {
                updateStickerForCell($objectInfo, 2, 902);
            }
            if (preg_match('/^Juniper Networks, Inc. ex4200-48t internet router/', $sysDescr)) {
                updateStickerForCell($objectInfo, 2, 907);
            }
            break;
        case preg_match('/^2636\\.1\\.1\\.1\\.2\\./', $sysObjectID):
            // Juniper
            detectSoftwareType($objectInfo, $sysDescr);
            checkPIC('1-681');
            commitAddPort($objectInfo['id'], 'console', '1-681', 'console', '');
            // DB-9 RS-232 console
            break;
        case preg_match('/^1991\\.1\\.3\\.45\\./', $sysObjectID):
            // snFGSFamily
        // snFGSFamily
        case preg_match('/^1991\\.1\\.3\\.46\\./', $sysObjectID):
            // snFLSFamily
        // snFLSFamily
        case preg_match('/^1991\\.1\\.3\\.54\\.2\\.4\\.1\\.1$/', $sysObjectID):
            // FCX 648
            detectSoftwareType($objectInfo, $sysDescr);
            $exact_release = preg_replace('/^.*, IronWare Version ([^ ]+) .*$/', '\\1', $sysDescr);
            updateStickerForCell($objectInfo, 5, $exact_release);
            # FOUNDRY-SN-AGENT-MIB::snChasSerNum.0
            $sysChassi = $device->snmpget('enterprises.1991.1.1.1.1.2.0');
            if ($sysChassi !== FALSE or $sysChassi !== NULL) {
                updateStickerForCell($objectInfo, 1, str_replace('"', '', substr($sysChassi, strlen('STRING: '))));
            }
            # Type of uplink module installed.
            # table: FOUNDRY-SN-AGENT-MIB::snAgentBrdMainBrdDescription
            # Possible part numbers are:
            # FGS-1XG1XGC (one fixed CX4 port)
            # FGS-2XGC (two fixed CX4 ports)
            # FGS-2XG (two XFP slots)
            # And for FLS result (which is not handled here) would be:
            # 1991.1.1.2.2.1.1.2.1 = STRING: "FLS-24G 24-port Management Module"
            # 1991.1.1.2.2.1.1.2.3 = STRING: "FLS-1XG 1-port 10G Module (1-XFP)"
            # 1991.1.1.2.2.1.1.2.4 = STRING: "FLS-1XG 1-port 10G Module (1-XFP)"
            # (assuming, that the device has 2 XFP modules in slots 3 and 4).
            foreach ($device->snmpwalkoid('enterprises.1991.1.1.2.2.1.1.2') as $module_raw) {
                if (preg_match('/^STRING: "(FGS-1XG1XGC|FGS-2XGC) /i', $module_raw)) {
                    $iftable_processors['fgs-uplinks']['dict_key'] = '1-40';
                    // CX4
                    break;
                }
            }
            # AC inputs
            # table: FOUNDRY-SN-AGENT-MIB::snChasPwrSupplyDescription
            # "Power supply 1 "
            # "Power supply 2 "
            foreach ($device->snmpwalkoid('enterprises.1991.1.1.1.2.1.1.2') as $PSU_raw) {
                $count = 0;
                $PSU_cooked = trim(preg_replace('/^string: "(.+)"$/i', '\\1', $PSU_raw, 1, $count));
                if ($count) {
                    checkPIC('1-16');
                    commitAddPort($objectInfo['id'], $PSU_cooked, '1-16', '', '');
                }
            }
            # fixed console port
            checkPIC('1-681');
            commitAddPort($objectInfo['id'], 'console', '1-681', 'console', '');
            // DB-9 RS-232 console
            break;
        case preg_match('/^1916\\.2\\./', $sysObjectID):
            // Extreme Networks Summit
            $xos_release = preg_replace('/^ExtremeXOS version ([[:digit:]]+)\\..*$/', '\\1', $sysDescr);
            $xos_codes = array('10' => 1350, '11' => 1351, '12' => 1352);
            if (array_key_exists($xos_release, $xos_codes)) {
                updateStickerForCell($objectInfo, 4, $xos_codes[$xos_release]);
            }
            checkPIC('1-681');
            commitAddPort($objectInfo['id'], 'console', '1-681', 'console', '');
            // DB-9 RS-232
            checkPIC('1-16');
            commitAddPort($objectInfo['id'], 'AC-in', '1-16', '', '');
            break;
        case preg_match('/^6027\\.1\\./', $sysObjectID):
            # Force10
            commitAddPort($objectInfo['id'], 'aux0', '1-29', 'RS-232', '');
            // RJ-45 RS-232 console
            $m = array();
            if (preg_match('/Force10 Application Software Version: ([\\d\\.]+)/', $sysDescr, $m)) {
                updateStickerForCell($objectInfo, 5, $m[1]);
                $ftos_release = preg_replace('/^([678])\\..+$/', '\\1', $m[1]);
                $ftos_codes = array('6' => 1592, '7' => 1593, '8' => 1594);
                if (array_key_exists($ftos_release, $ftos_codes)) {
                    updateStickerForCell($objectInfo, 4, $ftos_codes[$ftos_release]);
                }
            }
            # F10-S-SERIES-CHASSIS-MIB::chStackUnitSerialNumber.1
            $serialNo = $device->snmpget('enterprises.6027.3.10.1.2.2.1.12.1');
            # F10-S-SERIES-CHASSIS-MIB::chSysPowerSupplyType.1.1
            if ($device->snmpget('enterprises.6027.3.10.1.2.3.1.3.1.1') == 'INTEGER: 1') {
                checkPIC('1-16');
                commitAddPort($objectInfo['id'], 'PSU0', '1-16', 'PSU0', '');
            }
            # F10-S-SERIES-CHASSIS-MIB::chSysPowerSupplyType.1.2
            if ($device->snmpget('enterprises.6027.3.10.1.2.3.1.3.1.2') == 'INTEGER: 1') {
                checkPIC('1-16');
                commitAddPort($objectInfo['id'], 'PSU1', '1-16', 'PSU1', '');
            }
            if (strlen($serialNo)) {
                updateStickerForCell($objectInfo, 1, str_replace('"', '', substr($serialNo, strlen('STRING: '))));
            }
            break;
        case preg_match('/^202\\.20\\./', $sysObjectID):
            // SMC TigerSwitch
        // SMC TigerSwitch
        case preg_match('/^674\\.10895\\.4/', $sysObjectID):
            // Dell PowerConnect
        // Dell PowerConnect
        case preg_match('/^674\\.10895\\.300(3|4|7|9)/', $sysObjectID):
        case preg_match('/^674\\.10895\\.301(0|4|7|9)/', $sysObjectID):
        case preg_match('/^674\\.10895\\.302(0|1)/', $sysObjectID):
        case preg_match('/^3955\\.6\\.1\\.2048\\.1/', $sysObjectID):
            // Linksys
            // one DB-9 RS-232 and one AC port
            checkPIC('1-681');
            commitAddPort($objectInfo['id'], 'console', '1-681', '', '');
            // DB-9 RS-232
            checkPIC('1-16');
            commitAddPort($objectInfo['id'], 'AC-in', '1-16', '', '');
            break;
        case preg_match('/^207\\.1\\.14\\./', $sysObjectID):
            // Allied Telesyn
            // one RJ-45 RS-232 and two AC ports
            checkPIC('1-29');
            commitAddPort($objectInfo['id'], 'console', '1-29', 'console', '');
            checkPIC('1-16');
            commitAddPort($objectInfo['id'], 'AC-in-1', '1-16', 'AC1', '');
            commitAddPort($objectInfo['id'], 'AC-in-2', '1-16', 'AC2', '');
            break;
        case preg_match('/^674\\.10895\\.3000/', $sysObjectID):
            // one DB-9 RS-232, one 100Mb OOB mgmt, and one AC port
            checkPIC('1-681');
            commitAddPort($objectInfo['id'], 'console', '1-681', '', '');
            // DB-9 RS-232
            checkPIC('1-19');
            commitAddPort($objectInfo['id'], 'mgmt', '1-19', '', '');
            checkPIC('1-16');
            commitAddPort($objectInfo['id'], 'AC-in', '1-16', '', '');
            break;
        case preg_match('/^43\\.1\\.16\\.4\\.3\\.29/', $sysObjectID):
            // 3Com
            $sw_version = preg_replace('/^.* Version 3Com OS ([^ ]+).*$/', '\\1', $sysDescr);
            updateStickerForCell($objectInfo, 5, $sw_version);
            // one RJ-45 RS-232 and one AC port
            checkPIC('1-29');
            commitAddPort($objectInfo['id'], 'console', '1-29', '', '');
            // RJ-45 RS-232 console
            checkPIC('1-16');
            commitAddPort($objectInfo['id'], 'AC-in', '1-16', '', '');
            break;
        case preg_match('/^10977\\.11825\\.11833\\.97\\.25451\\.12800\\.100\\.4\\.4/', $sysObjectID):
            // Netgear
            $sw_version = preg_replace('/^.* V([^ ]+).*$/', '\\1', $sysDescr);
            updateStickerForCell($objectInfo, 5, $sw_version);
            // one AC port, no console
            checkPIC('1-16');
            commitAddPort($objectInfo['id'], 'AC-in', '1-16', '', '');
            break;
        case preg_match('/^30065\\.1\\.3011\\./', $sysObjectID):
            // Arista
            detectSoftwareType($objectInfo, $sysDescr);
            checkPIC('1-29');
            commitAddPort($objectInfo['id'], 'console', '1-29', 'IOIOI', '');
            $sw_version = preg_replace('/^Arista Networks EOS version (.+) running on .*$/', '\\1', $sysDescr);
            updateStickerForCell($objectInfo, 5, $sw_version);
            if (strlen($serialNo = $device->snmpget('mib-2.47.1.1.1.1.11.1'))) {
                # entPhysicalSerialNumber.1
                updateStickerForCell($objectInfo, 1, str_replace('"', '', substr($serialNo, strlen('STRING: '))));
            }
            break;
        default:
            // Nortel...
            break;
    }
    $ifInfo = array();
    foreach ($device->snmpwalkoid($ifDescr_tablename) as $oid => $value) {
        $randomindex = preg_replace("/^.*{$ifDescr_tablename}\\.(.+)\$/", '\\1', $oid);
        $value = trim(preg_replace('/^[^:]+: (.+)$/', '\\1', $value), '"');
        $ifInfo[$randomindex]['ifDescr'] = $value;
    }
    foreach ($device->snmpwalkoid('ifPhysAddress') as $oid => $value) {
        $randomindex = preg_replace("/^.*ifPhysAddress\\.(.+)\$/", '\\1', $oid);
        $value = trim($value);
        // NET-SNMP may return MAC addresses in one of two (?) formats depending on
        // DISPLAY-HINT internal database. The best we can do about it is to accept both.
        // Bug originally reported by Walery Wysotsky against openSUSE 11.0.
        if (preg_match('/^string: [0-9a-f]{1,2}(:[0-9a-f]{1,2}){5}/i', $value)) {
            list($dummy, $value) = explode(' ', $value);
            $addrbytes = explode(':', $value);
            foreach ($addrbytes as $bidx => $bytestr) {
                if (strlen($bytestr) == 1) {
                    $addrbytes[$bidx] = '0' . $bytestr;
                }
            }
        } elseif (preg_match('/^hex-string:( [0-9a-f]{2}){6}/i', $value)) {
            // Hex-STRING: xx yy zz xx yy zz
            $addrbytes = explode(' ', substr($value, -17));
        } elseif (preg_match('/22[0-9a-f]{12}22$/', bin2hex($value))) {
            // STRING: "??????"
            $addrbytes = array(substr(bin2hex($value), -14, 12));
        } else {
            continue;
        }
        // martian format
        $ifInfo[$randomindex]['ifPhysAddress'] = implode('', $addrbytes);
    }
    // process each interface only once regardless of how many processors we have to run
    foreach ($ifInfo as $iface) {
        foreach ($known_switches[$sysObjectID]['processors'] as $processor_name) {
            $newname = preg_replace($iftable_processors[$processor_name]['pattern'], $iftable_processors[$processor_name]['replacement'], $iface['ifDescr'], 1, $count);
            if ($newname === NULL) {
                showError('PCRE pattern error, terminating');
                break 2;
            }
            if (!$count) {
                continue;
            }
            // try next processor on current port
            $newlabel = preg_replace($iftable_processors[$processor_name]['pattern'], $iftable_processors[$processor_name]['label'], $iface['ifDescr'], 1, $count);
            checkPIC($iftable_processors[$processor_name]['dict_key']);
            commitAddPort($objectInfo['id'], $newname, $iftable_processors[$processor_name]['dict_key'], $newlabel, $iface['ifPhysAddress']);
            if (!$iftable_processors[$processor_name]['try_next_proc']) {
                // done with this port
                continue 2;
            }
        }
    }
    // No failure up to this point, thus leave current tab for the "Ports" one.
    return buildRedirectURL(NULL, 'ports');
}