コード例 #1
0
ファイル: functions_db.inc.php プロジェクト: edt82/ona
function ona_find_interface($search = "")
{
    printmsg("DEBUG => ona_find_interface({$search}) called", 3);
    // Validate input
    if ($search == "") {
        return array(1, 0, array());
    }
    // If it's numeric
    if (is_numeric($search)) {
        // It's a number - do several sql queries and see if we can get a unique match
        foreach (array('id', 'host_id', 'ip_addr') as $field) {
            list($status, $rows, $record) = ona_get_interface_record("{$field} like '{$search}'");
            // If we got it, return it
            if ($status == 0 and $rows == 1) {
                printmsg("DEBUG => ona_find_interface() found interface record by {$field}", 2);
                return array(0, $rows, $record);
            }
        }
    }
    // If it's an IP address...
    $ip = ip_mangle($search, 1);
    if ($ip != -1) {
        list($status, $rows, $record) = ona_get_interface_record("ip_addr like '{$ip}'");
        // If we got it, return it
        if ($status == 0 and $rows == 1) {
            printmsg("DEBUG => ona_find_interface() found record by IP address", 2);
            return array(0, $rows, $record);
        }
        // Otherwise return an error
        if ($rows == 0) {
            printmsg("DEBUG => No interface has the IP address: {$search}", 2);
            return array(3, $rows, array());
        }
        printmsg("DEBUG => More than one interface has the IP address: {$search}", 2);
        return array(4, $rows, array());
    }
    // If it's a MAC address
    $mac = mac_mangle($search, 1);
    if ($mac != -1) {
        // Search for it
        list($status, $rows, $record) = ona_get_interface_record(array('mac_addr' => $mac));
        // If we got it, return it
        if (!$status and $rows == 1) {
            printmsg("DEBUG => ona_find_interface() found record by MAC address", 2);
            return array(0, $rows, $record);
        }
        // Otherwise return an error
        if ($rows == 0) {
            printmsg("ERROR => No interface has the MAC address: {$search}", 2);
            return array(5, 0, array());
        }
        printmsg("DEBUG => ona_find_interface() More than one interface has the MAC address: " . mac_mangle($mac, 1), 0);
        return array(6, 0, array());
    }
    // We didn't find it - return and error code, 0 matches, and an empty record.
    printmsg("DEBUG => ona_find_interface() couldn't find a unique interface record with specified search criteria", 1);
    return array(2, 0, array());
}
コード例 #2
0
ファイル: list_interfaces.inc.php プロジェクト: edt82/ona
function ws_display_list($window_name, $form = '')
{
    global $conf, $self, $onadb;
    global $images, $color, $style;
    $html = '';
    $js = '';
    // If the user supplied an array in a string, build the array and store it in $form
    $form = parse_options_string($form);
    // Find the "tab" we're on
    $tab = $_SESSION['ona'][$form['form_id']]['tab'];
    // Build js to refresh this list
    $refresh = "xajax_window_submit('{$window_name}', xajax.getFormValues('{$form['form_id']}'), 'display_list');";
    // If this is the display_host screen that called, add refresh for DNS records too
    if ($form['content_id'] == 'display_host_list_interfaces') {
        $refresh .= "xajax_window_submit('list_records', xajax.getFormValues('list_records_filter_form'), 'display_list');";
    }
    // If it's not a new query, load the previous query from the session
    // into $form and save the current page and filter in the session.
    // Also find/set the "page" we're viewing
    $page = 1;
    if ($form['page'] and is_numeric($form['page'])) {
        $form = array_merge($form, (array) $_SESSION['ona'][$form['form_id']][$tab]['q']);
        $_SESSION['ona'][$form['form_id']][$tab]['page'] = $page = $form['page'];
        $_SESSION['ona'][$form['form_id']][$tab]['filter'] = $form['filter'];
    }
    // Calculate the SQL query offset (based on the page being displayed)
    $offset = $conf['search_results_per_page'] * ($page - 1);
    if ($offset == 0) {
        $offset = -1;
    }
    // Search results go in here
    $results = array();
    $count = 0;
    // Start building the "where" clause for the sql query to find the interfaces to display
    $where = "";
    $and = "";
    // HOST ID
    if ($form['host_id']) {
        $where .= $and . "host_id = " . $onadb->qstr($form['host_id']) . " OR id in (select interface_id from interface_clusters where host_id = " . $onadb->qstr($form['host_id']) . ")";
        $and = " AND ";
    }
    // Do the SQL Query
    $filter = '';
    if ($form['filter']) {
        $form['filter'] = ip_mangle($form['filter']);
        $filter = $and . ' ip_addr LIKE ' . $onadb->qstr('%' . $form['filter'] . '%');
    }
    list($status, $rows, $results) = db_get_records($onadb, 'interfaces', $where . $filter, "ip_addr ASC", $conf['search_results_per_page'], $offset);
    // If we got less than serach_results_per_page, add the current offset to it
    // so that if we're on the last page $rows still has the right number in it.
    if ($rows > 0 and $rows < $conf['search_results_per_page']) {
        $rows += $conf['search_results_per_page'] * ($page - 1);
    }
    // Re-Count only "internal" interfaces, not nat interfaces
    list($status, $rows, $records) = db_get_records($onadb, 'interfaces', 'nat_interface_id = \'0\' and ' . $where . $filter, "", 0);
    $count = $rows;
    $html .= <<<EOL
        <!-- Interface List -->
        <table id="{$form['form_id']}_interface_list" class="list-box" cellspacing="0" border="0" cellpadding="0">

            <!-- Table Header -->
            <tr>

                <td colspan="2" class="list-header" align="center" style="{$style['borderR']};">Interface</td>
                <td class="list-header" align="center" style="{$style['borderR']};">Subnet</td>
                <td class="list-header" align="center" style="{$style['borderR']};">MAC</td>
                <td class="list-header" align="center" style="{$style['borderR']};">Name</td>
                <td class="list-header" align="center" style="{$style['borderR']};">Description</td>
                <td class="list-header" align="center" style="{$style['borderR']};">Last Response</td>
                <td class="list-header" align="center">&nbsp;</td>
            </tr>
EOL;
    // Loop and display each record
    foreach ($results as $record) {
        // Get additional info about each host record //
        // Check if this interface has an external NAT
        unset($extnatint, $extnatdisplay, $extnatdisplay, $extnatsubdisplay);
        if ($record['nat_interface_id'] > 0) {
            list($status, $rows, $extnatint) = ona_get_interface_record(array('id' => $record['nat_interface_id']));
            // GDO: get the subnet object of the NATing interface, display it in both Interface and Subnet columns
            list($status, $rows, $extnatintsub) = ona_get_subnet_record(array('id' => $extnatint['subnet_id']));
            $extnatint['ip_addr'] = ip_mangle($extnatint['ip_addr'], 'dotted');
            //$extnatdisplay = "<span title='Interface is NATed to {$extnatint['ip_addr']}'> &nbsp;&nbsp;=> &nbsp;{$extnatint['ip_addr']}</span>";
            $extnatdisplay = "<span title='Interface is NATed to {$extnatint['ip_addr']} (on {$extnatintsub['name']})'> &nbsp;&nbsp;=> &nbsp;{$extnatint['ip_addr']}</span>";
            $extnatsubdisplay = " => <a title=\"View NATed subnet. ID: {$extnatintsub['id']}\"\n                                            class=\"nav\"\n                                            onClick=\"xajax_window_submit('work_space', 'xajax_window_submit(\\'display_subnet\\', \\'subnet_id=>{$extnatintsub['id']}\\', \\'display\\')');\"\n                                         >{$extnatintsub['name']}</a>";
        }
        // Check if this interface is an external NAT for another interface
        list($isnatstatus, $isnatrows, $isnat) = db_get_records($onadb, 'interfaces', "nat_interface_id = {$record['id']}", '', 0);
        // If the current interface is external NAT for another, dont display it in the list.
        if ($isnatrows > 0) {
            continue;
        }
        list($status, $intclusterrows, $intcluster) = db_get_records($onadb, 'interface_clusters', "interface_id = {$record['id']}");
        // Grab some info from the associated subnet record
        list($status, $rows, $subnet) = ona_get_subnet_record(array('id' => $record['subnet_id']));
        $record['ip_mask'] = $subnet['ip_mask'];
        $record['subnet_id'] = $subnet['id'];
        $record['subnet_description'] = $subnet['name'];
        // Convert IP and Netmask to a presentable format
        $record['ip_addr'] = ip_mangle($record['ip_addr'], 'dotted');
        $record['ip_mask'] = ip_mangle($record['ip_mask'], 'dotted');
        $record['ip_mask_cidr'] = ip_mangle($record['ip_mask'], 'cidr');
        if ($record['mac_addr']) {
            $record['mac_addr'] = mac_mangle($record['mac_addr']);
        }
        $record['description_short'] = truncate($record['description'], 40);
        // Escape data for display in html
        foreach (array_keys($record) as $key) {
            $record[$key] = htmlentities($record[$key], ENT_QUOTES, $conf['php_charset']);
        }
        // Format the date and colorize if its older than 2 months
        if ($record['last_response']) {
            $record['last_response_fmt'] = date($conf['date_format'], strtotime($record['last_response']));
            if (strtotime($record['last_response']) < strtotime('-2 month')) {
                $record['last_response_fmt'] = "<span style=\"color: red;\">" . $record['last_response_fmt'] . "</style>";
            }
        }
        $html .= <<<EOL
            <tr onMouseOver="this.className='row-highlight'" onMouseOut="this.className='row-normal'">

                <td nowrap="true" class="list-row" style="padding: 0px;" width="16px">
EOL;
        // Display cluster related information
        $clusterhtml = '&nbsp;';
        $clusterstyle = '';
        $clusterscript = '';
        if ($intclusterrows > 0) {
            $clusterstyle = 'font-weight: bold';
            $clusterscript = "onMouseOver=\"wwTT(this, event,\n                        'id', 'tt_interface_cluster_list_{$record['id']}',\n                        'type', 'velcro',\n                        'styleClass', 'wwTT_niceTitle',\n                        'direction', 'south',\n                        'javascript', 'xajax_window_submit(\\'tooltips\\', \\'tooltip=>interface_cluster_list,id=>tt_interface_cluster_list_{$record['id']},interface_id=>{$record['id']}\\');'\n                        );\"";
            $clusterhtml .= <<<EOL
                    <img src="{$images}/silk/sitemap.png" border="0" {$clusterscript} />
EOL;
        }
        $html .= $clusterhtml;
        $html .= <<<EOL
                </td>

                <td class="list-row">
EOL;
        // MP: Disabling the display_interface link. I dont think this will be needed
        if (1 < 0) {
            $html .= <<<EOL
                    <a title="View interface. ID: {$record['id']}"
                       class="nav"
                       onClick="xajax_window_submit('work_space', 'xajax_window_submit(\\'display_interface\\',\\'interface_id=>{$record['id']}\\', \\'display\\')');">
                        {$record['ip_addr']}
                        </a>
EOL;
        } else {
            $html .= "<span style='{$clusterstyle}' {$clusterscript}>{$record['ip_addr']}</span>";
        }
        $html .= <<<EOL
                    <span style="{$clusterstyle}" title="{$record['ip_mask']}">/{$record['ip_mask_cidr']}</span> {$extnatdisplay}
                </td>

                <td class="list-row" align="left">
                    <a title="View subnet. ID: {$subnet['id']}"
                       class="nav"
                       onClick="xajax_window_submit('work_space', 'xajax_window_submit(\\'display_subnet\\', \\'subnet_id=>{$subnet['id']}\\', \\'display\\')');"
                    >{$record['subnet_description']}</a> {$extnatsubdisplay}
                </td>

                <td class="list-row" align="right">
                    {$record['mac_addr']}&nbsp;
                </td>

                <td class="list-row" align="left">
                    {$record['name']}&nbsp;
                </td>

                <td class="list-row" align="left" title="{$record['description']}">
                    {$record['description_short']}&nbsp;
                </td>

                <td class="list-row" align="left" title="{$record['last_response']}">
                    {$record['last_response_fmt']}&nbsp;
                </td>

                <td class="list-row" align="right">
                    <form id="{$form['form_id']}_list_interface_{$record['id']}"
                        ><input type="hidden" name="interface_id" value="{$record['id']}"
                        ><input type="hidden" name="js" value="{$refresh}"
                    ></form>&nbsp;
EOL;
        if (auth('interface_modify')) {
            $html .= <<<EOL

                    <a title="Interface Menu"
                       id="int_menu_button_{$record['id']}"
                       class="act"
                       onmouseover="wwTT(this, event,
                                            'id', 'tt_quick_interface_menu_{$record['id']}',
                                            'type', 'velcro',
                                            'delay', 0,
                                            'styleClass', 'wwTT_int_menu',
                                            'lifetime', 1000,
                                            'direction', 'west',
                                            'javascript', 'xajax_window_submit(\\'tooltips\\', \\'tooltip=>quick_interface_menu,id=>tt_quick_interface_menu_{$record['id']},interface_id=>{$record['id']},ip_addr=>{$record['ip_addr']},orig_host=>{$record['host_id']},form_id=>{$form['form_id']}_list_interface_{$record['id']},subnet_id=>{$subnet['id']},natip=>{$record['nat_interface_id']}\\');'
                                           );"
                    ><img src="{$images}/silk/add.png" border="0"></a>&nbsp;
EOL;
        }
        if (auth('interface_modify')) {
            $html .= <<<EOL

                    <a title="Edit interface. ID: {$record['id']}"
                       class="act"
                       onClick="xajax_window_submit('edit_interface', xajax.getFormValues('{$form['form_id']}_list_interface_{$record['id']}'), 'editor');"
                    ><img src="{$images}/silk/page_edit.png" border="0"></a>&nbsp;
EOL;
        }
        if (auth('interface_del')) {
            $html .= <<<EOL

                    <a title="Delete interface"
                       class="act"
                       onClick="xajax_window_submit('edit_interface', xajax.getFormValues('{$form['form_id']}_list_interface_{$record['id']}'), 'delete');"
                    ><img src="{$images}/silk/delete.png" border="0"></a>&nbsp;
EOL;
        }
        $html .= <<<EOL
                </td>

            </tr>
EOL;
    }
    if ($count == 0 and $form['host_id'] and !$form['filter']) {
        $html .= <<<EOL
     <tr><td colspan="99" align="center" style="color: red;">Please add an interface to this host, or delete the host</td></tr>
EOL;
    }
    $html .= <<<EOL
    </table>
EOL;
    // Build page links if there are any
    $html .= get_page_links($page, $conf['search_results_per_page'], $count, $window_name, $form['form_id']);
    // Insert the new html into the content div specified
    // Instantiate the xajaxResponse object
    $response = new xajaxResponse();
    $response->addAssign("{$form['form_id']}_{$tab}_count", "innerHTML", "({$count})");
    $response->addAssign($form['content_id'], "innerHTML", $html);
    if ($js) {
        $response->addScript($js);
    }
    return $response->getXML();
}
コード例 #3
0
ファイル: functions_gui.inc.php プロジェクト: edt82/ona
function get_mac_suggestions($q, $max_results = 10)
{
    $formatted = $results = array();
    $q = strtoupper($q);
    //if (preg_match('/[^\%\:\.\-0-9A-F]/', $q)) return(array()); // It's not a mac address ;)
    // MP: I added the %3A line because some searches were coming through with the : replaced.
    $q = preg_replace('/\\%3A/', '', $q);
    // Discard characters that aren't stored in the db
    $q = preg_replace('/[\\:\\.\\-]/', '', $q);
    // Discard characters that aren't stored in the db
    $results = get_text_suggestions($q . '%', 'interfaces', 'mac_addr', $max_results);
    foreach ($results as $result) {
        $formatted[] = mac_mangle($result, 2);
    }
    return $formatted;
}
コード例 #4
0
ファイル: search_results.inc.php プロジェクト: edt82/ona
function quick_search($q)
{
    global $conf, $self;
    //
    // *** Quick Search ***
    //
    //     If it's an IP or MAC address (string or numeric):
    //         Look for an interface and display associated host record
    //         Look for the subnet that IP is on and display a single subnet record
    //     If it's a string:
    //         Look for a hostname
    //         Look for an alias name (and display associated hosts)
    //         Look for a subnet name
    printmsg("DEBUG => quick_search({$q}) called", 3);
    // Check to see if it is a MAC.. do it here instead of in the next interface section
    // so that we can properly find multiple hosts with the same mac
    $mac = mac_mangle($q, 1);
    if ($mac != -1) {
        printmsg("DEBUG => quick_search() Looks like a MAC, Returning mac = {$q}", 3);
        return array('hosts', array('mac' => $q));
    }
    // See if $q identifies an interface record (by IP, MAC, etc)
    list($status, $rows, $record) = ona_find_interface($q);
    // If it was, display the associated host record
    if ($rows) {
        printmsg("DEBUG => quick_search() returning host match (ID={$record['host_id']})", 3);
        return array('hosts', array('host_id' => $record['host_id']));
    }
    // See if $q identifies a subnet record (by IP, ID, or Description)
    list($status, $rows, $record) = ona_find_subnet($q);
    // If it was, display the associated subnet record
    if ($rows) {
        printmsg("DEBUG => quick_search() returning subnet match (ID={$record['id']})", 3);
        return array('subnets', array('subnet_id' => $record['id']));
    }
    // Well, I guess we'll assume $q is a hostname/alias search
    printmsg("DEBUG => quick_search() found no subnet or host match. Returning hostname = {$q}", 3);
    return array('hosts', array('hostname' => $q));
}
コード例 #5
0
function build_hosts($server_id = 0)
{
    global $self;
    global $onadb;
    global $dhcp_entry_options;
    printmsg("DEBUG => build_hosts() Processing hosts for server: {$server_id}", 3);
    // ipv6: for now we are going to skip over any v6 address space
    //       need to pass in if we want v6 or not
    // For the given server, select all host entries that have mac addresses
    // This is to build the static, mac based, host entries
    // NOTE: I use the concat and inet_ntoa functions.. not sure how portable they really are.
    $q = "\n        SELECT  H.id,\n                concat(D.name,'.',Z.name) primary_dns_name,\n                inet_ntoa(I.IP_ADDR) ip_addr,\n                UPPER(I.MAC_ADDR) mac,\n                B.ID dhcp_entry_id\n        FROM    hosts H,\n                dns D,\n                domains Z,\n                interfaces I LEFT OUTER JOIN dhcp_option_entries B ON I.host_id = B.host_id\n        WHERE   I.mac_addr NOT like ''\n        AND     I.host_id = H.id\n        AND     D.domain_id = Z.id\n        AND     D.id = H.primary_dns_id\n        AND     (\n                 ( I.subnet_id IN (\n                        SELECT  subnet_id\n                        FROM    dhcp_server_subnets\n                        WHERE   host_id = {$server_id}\n                        AND     ip_addr < 4294967295)\n                 )\n                 OR\n                 ( I.subnet_id IN (\n                        SELECT  subnet_id\n                        FROM    dhcp_pools\n                        WHERE   dhcp_failover_group_id IN (\n                                SELECT id\n                                FROM dhcp_failover_groups\n                                WHERE   primary_server_id = {$server_id}\n                                OR      secondary_server_id = {$server_id}))\n                 )\n                )\n        ORDER BY I.ip_addr";
    // exectue the query
    $rs = $onadb->Execute($q);
    if ($rs === false or !$rs->RecordCount()) {
        $self['error'] = 'ERROR => build_hosts(): SQL query failed: ' . $onadb->ErrorMsg();
        printmsg($self['error'], 0);
        $exit += 1;
    }
    $rows = $rs->RecordCount();
    // print the opening host comment with row count
    if ($rows) {
        $text = "\n# --------HOSTS (count={$rows})--------\n\n";
    }
    // Loop through the record set
    $last_host = 0;
    while ($host = $rs->FetchRow()) {
        printmsg('DEBUG => build_host() Processing host: ' . $host['primary_dns_name'], 5);
        // print closing brace only if this is a new host, AND it is not the first row
        if ($last_host != $host['ip_addr'] && $last_host != 0) {
            $text .= "}\n\n";
        }
        if ($last_host != $host['ip_addr']) {
            $text .= "host {$host['ip_addr']} {  # {$host['primary_dns_name']}\n";
            // TODO: ipv6 may be fun here
            // https://lists.isc.org/pipermail/dhcp-users/2009-February/008463.html
            // https://lists.isc.org/pipermail/dhcp-users/2009-March/008678.html
            // http://www.ietf.org/mail-archive/web/dhcwg/current/msg12455.html
            $text .= "    fixed-address {$host['ip_addr']};\n";
            // Currently we are not supporting other hardware types available
            // tokenring and fddi are other options than ethernet here,
            // if it is needed.. use the hardware type option. possible TODO to fix this
            $text .= "    hardware ethernet " . mac_mangle($host['mac']) . ";\n";
            // hostname option does not seem to be found in the "dhcp handbook" so I'm leaving it out for now
            //$text .= "    option hostname \"{$host['fqdn']}\";\n";
        }
        // process any dhcp options
        if ($host['dhcp_entry_id']) {
            list($status, $rows, $dhcp_entry) = ona_get_dhcp_option_entry_record(array('id' => $host['dhcp_entry_id']));
            if (!$rows) {
                break;
            }
            if ($status) {
                $exit++;
                break;
            }
            // format the tag appropriatly
            list($status, $formatted_entry) = format_tag($dhcp_entry);
            if ($formatted_entry != '') {
                $text .= "    option {$dhcp_entry['name']} {$formatted_entry};\n";
            } else {
                $exit++;
                break;
            }
        }
        // increment the host anchor to determine if we are dealing with a new host in the next loop
        $last_host = $host['ip_addr'];
    }
    // print the final closing brace
    if ($rows) {
        $text .= "}\n\n";
    }
    // close the record set
    $rs->Close();
    // return host config text
    return array($exit, $text);
}
コード例 #6
0
ファイル: edit_host.inc.php プロジェクト: edt82/ona
function ws_editor($window_name, $form = '')
{
    global $conf, $self, $onadb;
    global $font_family, $color, $style, $images;
    $window = array();
    // Check permissions
    if (!(auth('host_modify') or auth('host_add'))) {
        $response = new xajaxResponse();
        $response->addScript("alert('Permission denied!');");
        return $response->getXML();
    }
    // If an array in a string was provided, build the array and store it in $form
    $form = parse_options_string($form);
    // Load an existing host record (and associated info) if $form is a host_id
    $host = array('fqdn' => '.', 'domain_fqdn' => $conf['dns_defaultdomain']);
    $interface = array();
    if (is_numeric($form['host_id'])) {
        list($status, $rows, $host) = ona_get_host_record(array('id' => $form['host_id']));
        if ($rows) {
            // Load associated INTERFACE record(s)
            list($status, $interfaces, $interface) = ona_get_interface_record(array('host_id' => $host['id']));
            list($status, $rows, $subnet) = ona_get_subnet_record(array('id' => $interface['subnet_id']));
            $interface['ip_addr'] = ip_mangle($interface['ip_addr'], 'dotted');
            if ($interface['mac_addr']) {
                $interface['mac_addr'] = mac_mangle($interface['mac_addr'], 2);
            }
            //FIXME: (PK) should not use numeric format specifier here!
        }
    } else {
        if (strlen($form['ip_addr']) > 1) {
            $interface['ip_addr'] = $form['ip_addr'];
        }
        if (strlen($form['hostname']) > 1) {
            $host['name'] = $form['hostname'];
        }
    }
    // Set the default security level if there isn't one
    if (!array_key_exists('lvl', $host)) {
        $host['lvl'] = $conf['ona_lvl'];
    }
    // Load a subnet record if we got passed a subnet_id
    if ($form['subnet_id']) {
        list($status, $rows, $subnet) = ona_get_subnet_record(array('id' => $form['subnet_id']));
    }
    // Load a domain record if we got passed a domain_id
    if ($form['domain_id']) {
        list($status, $rows, $domain) = ona_get_domain_record(array('id' => $form['domain_id']));
        $host['domain_fqdn'] = $domain['fqdn'];
    }
    // If we dont have a domain_fqdn yet.. lets use the system default domain
    if (!$host['domain_fqdn']) {
        $host['domain_fqdn'] = $conf['dns_defaultdomain'];
    }
    // Build a device_types list
    list($status, $rows, $records) = db_get_records($onadb, 'device_types', 'id >= 1');
    $device_types = array();
    foreach ($records as $type) {
        list($status, $rows, $model) = ona_get_model_record(array('id' => $type['model_id']));
        list($status, $rows, $role) = ona_get_role_record(array('id' => $type['role_id']));
        list($status, $rows, $manufacturer) = ona_get_manufacturer_record(array('id' => $model['manufacturer_id']));
        $device_types[$type['id']] = "{$manufacturer['name']} {$model['name']} ({$role['name']})";
    }
    asort($device_types);
    list($status, $rows, $device) = ona_get_device_record(array('id' => $host['device_id']));
    list($status, $rows, $location) = ona_get_location_record(array('id' => $device['location_id']));
    $host['location'] = $location['reference'];
    $device_model_list = "<option value=\"\"></option>\n";
    foreach (array_keys((array) $device_types) as $id) {
        $device_types[$id] = htmlentities($device_types[$id]);
        $selected = '';
        if ($id == $device['device_type_id']) {
            $selected = 'SELECTED';
        }
        $device_model_list .= "<option value=\"{$id}\" {$selected}>{$device_types[$id]}</option>\n";
    }
    unset($device_types, $device, $manufacturer, $role, $model, $records);
    //Get the list of DNS views
    if ($conf['dns_views']) {
        list($status, $rows, $dnsviews) = db_get_records($onadb, 'dns_views', 'id >= 0', 'name');
        foreach ($dnsviews as $entry) {
            $selected = '';
            //$dnsviews['name'] = htmlentities($dnsviews['name']);
            // If this entry matches the record you are editing, set it to selected
            if ($host['id'] and $entry['id'] == $host['dns_view_id']) {
                $selected = "SELECTED=\"selected\"";
                $dns_view_name = $entry['name'] . '/';
            } elseif (!$host['id'] and $entry['id'] == 0) {
                // Otherwise use the default record if we are adding a new entry
                $selected = "SELECTED=\"selected\"";
                $dns_view_name = $entry['name'] . '/';
            }
            $dns_view_list .= "<option {$selected} value=\"{$entry['id']}\">{$entry['name']}</option>\n";
        }
    }
    // Escape data for display in html
    foreach (array_keys((array) $host) as $key) {
        $host[$key] = htmlentities($host[$key], ENT_QUOTES, $conf['php_charset']);
    }
    foreach (array_keys((array) $subnet) as $key) {
        $subnet[$key] = htmlentities($subnet[$key], ENT_QUOTES, $conf['php_charset']);
    }
    foreach (array_keys((array) $interface) as $key) {
        $interface[$key] = htmlentities($interface[$key], ENT_QUOTES, $conf['php_charset']);
    }
    // Set the window title:
    $window['title'] = "Add Host";
    if ($host['id']) {
        $window['title'] = "Edit Host";
    } else {
        unset($dns_view_name);
    }
    // Javascript to run after the window is built
    $window['js'] = <<<EOL
        /* Put a minimize icon in the title bar */
        el('{$window_name}_title_r').innerHTML =
            '&nbsp;<a onClick="toggle_window(\\'{$window_name}\\');" title="Minimize window" style="cursor: pointer;"><img src="{$images}/icon_minimize.gif" border="0" /></a>' +
            el('{$window_name}_title_r').innerHTML;

        /* Put a help icon in the title bar */
        el('{$window_name}_title_r').innerHTML =
            '&nbsp;<a href="{$_ENV['help_url']}{$window_name}" target="null" title="Help" style="cursor: pointer;"><img src="{$images}/silk/help.png" border="0" /></a>' +
            el('{$window_name}_title_r').innerHTML;

        suggest_setup('set_domain_{$window_name}',    'suggest_set_domain_{$window_name}');
        suggest_setup('set_location_{$window_name}',  'suggest_set_location_{$window_name}');

        /* Setup the Quick Find location icon */

        var _button = el('qf_location_{$window_name}');
        _button.style.cursor = 'pointer';
        _button.onclick =
            function(ev) {
                if (!ev) ev = event;
                /* Create the popup div */
                wwTT(this, ev,
                     'id', 'tt_qf_location_{$window_name}',
                     'type', 'static',
                     'direction', 'south',
                     'delay', 0,
                     'styleClass', 'wwTT_qf',
                     'javascript',
                     "xajax_window_submit('tooltips', '" +
                         "tooltip=>qf_location," +
                         "id=>tt_qf_location_{$window_name}," +
                         "input_id=>set_location_{$window_name}');"
                );
            };

    el('set_host').focus();
EOL;
    // If we are modifying do not allow them to edit/change dns names.  this should only be done when creating a new host
    $hideit = '';
    if ($host['id']) {
        $hideit = 'style="display: none;"';
    }
    // Define the window's inner html
    $window['html'] = <<<EOL

    <!-- Host Edit Form -->
    <form id="{$window_name}_edit_form" onSubmit="return false;">
    <input type="hidden" name="host" value="{$dns_view_name}{$host['fqdn']}">
    <input type="hidden" name="interface" value="{$interface['id']}">
    <input type="hidden" name="js" value="{$form['js']}">
    <table cellspacing="0" border="0" cellpadding="0" style="background-color: {$color['window_content_bg']}; padding-left: 20px; padding-right: 20px; padding-top: 5px; padding-bottom: 5px;">

        <!-- HOST RECORD -->
        <tr>
            <td align="left" nowrap="true">
                <b><u>Host Record</u></b>&nbsp;
            </td>
            <td class="padding" align="left" width="100%">
                &nbsp;
            </td>
        </tr>
EOL;
    // Print a dns view selector
    if ($conf['dns_views']) {
        $window['html'] .= <<<EOL
        <tr {$hideit}>
            <td align="right" nowrap="true">
                DNS View
            </td>
            <td class="padding" align="left" width="100%">
                <select
                    id="dns_view_select"
                    name="set_view"
                    alt="DNS View"
                    class="edit"
                >{$dns_view_list}</select>
            </td>
        </tr>

EOL;
    }
    $window['html'] .= <<<EOL
        <tr {$hideit}>
            <td class="input_required" align="right" nowrap="true">
                DNS Name
            </td>
            <td class="padding" align="left" width="100%">
                <input
                    id="set_host"
                    name="set_host"
                    alt="Hostname"
                    value="{$host['name']}"
                    class="edit"
                    type="text"
                    size="20" maxlength="64"
                >
            </td>
        </tr>

        <tr {$hideit}>
            <td class="input_required" align="right" nowrap="true">
                Domain
            </td>
            <td class="padding" align="left" width="100%">
                <input
                    id="set_domain_{$window_name}"
                    name="set_domain"
                    alt="Domain name"
                    value="{$host['domain_fqdn']}"
                    class="edit"
                    type="text"
                    size="25" maxlength="64"
                >
                <div id="suggest_set_domain_{$window_name}" class="suggest"></div>
            </td>
        </tr>

        <tr>
            <td class="input_required" align="right" nowrap="true">
                Device type
            </td>
            <td class="padding" align="left" width="100%">
                <select
                    name="set_type"
                    alt="Device type"
                    class="edit"
                >{$device_model_list}</select>
            </td>
        </tr>

        <tr>
            <td align="right" nowrap="true">
                Notes
            </td>
            <td class="padding" align="left" width="100%">
                <textarea name="set_notes" class="edit" cols="40" rows="1">{$host['notes']}</textarea>
            </td>
        </tr>
        <tr>
            <td align="right" nowrap="true">
                Location
            </td>
            <td class="padding" align="left" width="100%">
                <input
                    id="set_location_{$window_name}"
                    name="set_location"
                    alt="Location"
                    value="{$host['location']}"
                    class="edit"
                    type="text"
                    size="7" maxlength="10"
                >
                <div id="suggest_set_location_{$window_name}" class="suggest"></div>
                <span id="qf_location_{$window_name}" title="Location Quick Search"><img src="{$images}/silk/find.png" border="0"/></span>
            </td>
        </tr>
EOL;
    // Display an interface edit section if it's a new host or there were exactly one interface.
    if (!$interfaces) {
        $window['js'] .= <<<EOL

        /* Setup the Quick Find for available IPs */
        var _button = el('qf_free_ip_{$window_name}');
        _button.style.cursor = 'pointer';
        _button.onclick =
            function(ev) {
                if (!ev) ev = event;
                /* Create the popup div */
                wwTT(this, ev,
                     'id', 'tt_qf_free_ip_{$window_name}',
                     'type', 'static',
                     'direction', 'south',
                     'delay', 0,
                     'styleClass', 'wwTT_qf',
                     'javascript',
                     "xajax_window_submit('tooltips', '" +
                         "tooltip=>qf_free_ip," +
                         "id=>tt_qf_free_ip_{$window_name}," +
                         "text_id=>associated_subnet_{$window_name}," +
                         "text_value=>" + el('associated_subnet_{$window_name}').innerHTML + "," +
                         "input_id=>set_ip_{$window_name}');"
                );
            };

EOL;
        $window['html'] .= <<<EOL

        <!-- FIRST INTERFACE -->
        <tr>
            <td align="left" nowrap="true">
                <b><u>Interface</u></b>&nbsp;
            </td>
            <td class="padding" align="left" width="100%">
                &nbsp;
            </td>
        </tr>

        <tr>
            <td align="right" nowrap="true">
                Subnet
            </td>
            <td class="padding" align="left" width="100%" nowrap="true">
                <span id="associated_subnet_{$window_name}"
                >{$subnet['name']}</span>
            </td>
        </tr>

        <tr>
            <td class="input_required" align="right" nowrap="true">
                IP Address
            </td>
            <td class="padding" align="left" width="100%">
                <input
                    id="set_ip_{$window_name}"
                    name="set_ip"
                    alt="IP Address"
                    value="{$interface['ip_addr']}"
                    class="edit"
                    type="text"
                    size="25" maxlength="64"
                >
                <span id="qf_free_ip_{$window_name}" title="Available IP Quick Search"><img src="{$images}/silk/find.png" border="0"/></span>
                <div id="suggest_set_ip_{$window_name}" class="suggest"></div>
            </td>
        </tr>

        <tr>
            <td align="right" nowrap="true">
                MAC Address
            </td>
            <td class="padding" align="left" width="100%">
                <input
                    name="set_mac"
                    alt="MAC Address"
                    value="{$interface['mac_addr']}"
                    class="edit"
                    type="text"
                    size="17" maxlength="17"
                >
                <a class="nav" onClick="this.style.display = 'none'; el('force_{$window_name}').style.display = browser.isIE ? 'block' : 'table-row';">More >></a>
            </td>
        </tr>

        <tr id="force_{$window_name}" style="display: none;">
            <td align="right" nowrap="true">
                &nbsp;
            </td>
            <td class="padding" align="left" width="100%">
                <input
                    name="force"
                    alt="Allow duplicate MAC addresses"
                    type="checkbox"
                > Allow duplicate MAC addresses
            </td>
        </tr>

        <tr>
            <td align="right" nowrap="true">
                Interface name
            </td>
            <td class="padding" align="left" width="100%">
                <input
                    name="set_name"
                    alt="Interface name"
                    value="{$interface['name']}"
                    class="edit"
                    type="text"
                    size="17" maxlength="255"
                >
            </td>
        </tr>

        <tr>
            <td align="right" nowrap="true">
                Interface description
            </td>
            <td class="padding" align="left" width="100%">
                <input
                    name="set_description"
                    alt="Interface description"
                    value="{$interface['description']}"
                    class="edit"
                    type="text"
                    size="25" maxlength="255"
                >
            </td>
        </tr>
EOL;
    }
    if (!$host['id']) {
        $window['html'] .= <<<EOL
        <td align="right" nowrap="true">
            Auto create PTR
        </td>
        <td class="padding" align="left" width="100%" nowrap>
            <input
                id="set_addptr"
                name="set_addptr"
                alt="Automaticaly create PTR record"
                type="checkbox"
                checked="1"
            />
        </td>
        <tr>
            <td align="right" nowrap="true">
                &nbsp;
            </td>
            <td class="padding" align="left" width="100%">
                <input
                    name="keepadding"
                    alt="Keep adding more hosts"
                    type="checkbox"
                > Keep adding more hosts
            </td>
        </tr>

        <tr>
            <td colspan="2" class="padding" align="center" width="100%">
            <span id="statusinfo_{$window_name}" style="color: green;" ></span>
            </td>
        </tr>

EOL;
    }
    $window['html'] .= <<<EOL

        <tr>
            <td align="right" valign="top" nowrap="true">
                &nbsp;
            </td>
            <td class="padding" align="right" width="100%">
                <input class="edit" type="button" name="cancel" value="Cancel" onClick="removeElement('{$window_name}');">
                <input class="edit" type="button"
                    name="submit"
                    value="Save"
                    accesskey=" "
                    onClick="xajax_window_submit('{$window_name}', xajax.getFormValues('{$window_name}_edit_form'), 'save');"
                >
            </td>
        </tr>

    </table>
    </form>
EOL;
    return window_open($window_name, $window);
}
コード例 #7
0
ファイル: functions_general.inc.php プロジェクト: edt82/ona
function format_array($array = array())
{
    $text = '';
    foreach (array_keys($array) as $key) {
        // Make some data look pretty
        if ($key == 'ip_addr') {
            $array[$key] = ip_mangle($array[$key], 'dotted');
        } else {
            if ($key == 'ip_addr_start') {
                $array[$key] = ip_mangle($array[$key], 'dotted');
            } else {
                if ($key == 'ip_addr_end') {
                    $array[$key] = ip_mangle($array[$key], 'dotted');
                } else {
                    if ($key == 'ip_mask') {
                        $array[$key] = ip_mangle($array[$key]) . '  (/' . ip_mangle($array[$key], 'cidr') . ')';
                    } else {
                        if ($key == 'mac_addr') {
                            $array[$key] = mac_mangle($array[$key]);
                            if ($array[$key] == -1) {
                                $array[$key] = '';
                            }
                        } else {
                            if ($key == 'host_id') {
                                list($status, $rows, $host) = ona_find_host($array[$key]);
                                if ($host['id']) {
                                    $array[$key] = str_pad($array[$key], 20) . strtolower("({$host['fqdn']})");
                                }
                            } else {
                                if ($key == 'server_id') {
                                    list($status, $rows, $server) = ona_get_server_record(array('id' => $array[$key]));
                                    list($status, $rows, $host) = ona_find_host($server['host_id']);
                                    if ($host['id']) {
                                        $array[$key] = str_pad($array[$key], 20) . strtolower("({$host['fqdn']})");
                                    }
                                } else {
                                    if ($key == 'subnet_id') {
                                        list($status, $rows, $subnet) = ona_get_subnet_record(array('id' => $array[$key]));
                                        if ($subnet['id']) {
                                            $array[$key] = str_pad($array[$key], 20) . strtoupper("({$subnet['name']})");
                                        }
                                    } else {
                                        if ($key == 'domain_id' or $key == 'primary_dns_domain_id') {
                                            list($status, $rows, $domain) = ona_get_domain_record(array('id' => $array[$key]));
                                            $array[$key] = str_pad($array[$key], 20) . strtolower("({$domain['fqdn']})");
                                        } else {
                                            if ($key == 'interface_id') {
                                                list($status, $rows, $interface) = ona_get_interface_record(array('id' => $array[$key]));
                                                $array[$key] = str_pad($array[$key], 20) . '(' . ip_mangle($interface['ip_addr'], 'dotted') . ')';
                                            } else {
                                                if ($key == 'device_type_id') {
                                                    list($status, $rows, $devtype) = ona_get_device_type_record(array('id' => $array[$key]));
                                                    if ($devtype['id']) {
                                                        list($status, $rows, $model) = ona_get_model_record(array('id' => $devtype['model_id']));
                                                        list($status, $rows, $role) = ona_get_role_record(array('id' => $devtype['role_id']));
                                                        list($status, $rows, $manu) = ona_get_manufacturer_record(array('id' => $model['manufacturer_id']));
                                                        $array[$key] = str_pad($array[$key], 20) . "({$manu['name']}, {$model['name']} ({$role['name']}))";
                                                    }
                                                } else {
                                                    if ($key == 'custom_attribute_type_id') {
                                                        list($status, $rows, $ca) = ona_get_custom_attribute_type_record(array('id' => $array[$key]));
                                                        if ($ca['id']) {
                                                            $array[$key] = str_pad($array[$key], 20) . "({$ca['name']})";
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        // Align columns
        if ($array[$key]) {
            $text .= str_pad("  {$key}", 30) . $array[$key] . "\n";
        }
    }
    // Return a nice string :)
    return $text;
}
コード例 #8
0
ファイル: edit_interface.inc.php プロジェクト: edt82/ona
function ws_editor($window_name, $form = '')
{
    global $conf, $self, $onadb;
    global $font_family, $color, $style, $images, $interface;
    $window = array();
    // Check permissions
    if (!auth('interface_modify')) {
        $response = new xajaxResponse();
        $response->addScript("alert('Permission denied!');");
        return $response->getXML();
    }
    // If an array in a string was provided, build the array and store it in $form
    $form = parse_options_string($form);
    // If $form is a number, it's an alias record ID- so we transform $form into an array
    if (is_numeric($form)) {
        $form = array('interface_id' => $form);
    }
    // Load an existing record (and associated info) if we're editing
    if (is_numeric($form['interface_id'])) {
        list($status, $rows, $interface) = ona_get_interface_record(array('id' => $form['interface_id']));
        if ($rows) {
            list($status, $rows, $host) = ona_find_host($interface['host_id']);
            list($status, $rows, $subnet) = ona_get_subnet_record(array('id' => $interface['subnet_id']));
            list($status, $rows_nat, $extnatint) = ona_get_interface_record(array('id' => $record['nat_interface_id']));
            $interface['ip_addr'] = ip_mangle($interface['ip_addr'], 'dotted');
            if ($interface['mac_addr']) {
                $interface['mac_addr'] = mac_mangle($interface['mac_addr']);
            }
            if ($rows_nat > 0) {
                $interface['natip_addr'] = ip_mangle($extnatint['ip_addr'], 'dotted');
            }
        }
    } else {
        // Maybe we didn't get an interface record, but we got a host record (adding an interface)
        // Set it in $interface so it's available below.
        if (is_numeric($form['host_id'])) {
            $interface['host_id'] = $form['host_id'];
        }
        if (is_numeric($form['subnet_id'])) {
            list($status, $rows, $subnet) = ona_get_subnet_record(array('id' => $form['subnet_id']));
        }
        // allow various default items to be set during an add that are passed in from the form
        if (isset($form['ip_addr'])) {
            $interface['ip_addr'] = $form['ip_addr'];
        }
        if (isset($form['name'])) {
            $interface['name'] = $form['name'];
        }
        if (isset($form['description'])) {
            $interface['description'] = $form['description'];
        }
        if (isset($form['mac_addr'])) {
            $interface['mac_addr'] = $form['mac_addr'];
        }
        if (isset($form['natip_addr'])) {
            $interface['natip_addr'] = $form['natip_addr'];
        }
    }
    // Load the host record for display
    if ($interface['host_id']) {
        list($status, $rows, $host) = ona_find_host($interface['host_id']);
    }
    //Get the list of DNS views
    if ($conf['dns_views']) {
        list($status, $rows, $dnsviews) = db_get_records($onadb, 'dns_views', 'id >= 0', 'name');
        foreach ($dnsviews as $entry) {
            $selected = '';
            $dnsviews['name'] = htmlentities($dnsviews['name']);
            // If this entry matches the record you are editing, set it to selected
            if ($dns_record['id'] and $entry['id'] == $dns_record['dns_view_id']) {
                $selected = "SELECTED=\"selected\"";
            } elseif (!$dns_record['id'] and $entry['id'] == 0) {
                // Otherwise use the default record if we are adding a new entry
                $selected = "SELECTED=\"selected\"";
            }
            $dns_view_list .= "<option {$selected} value=\"{$entry['id']}\">{$entry['name']}</option>\n";
        }
    }
    // Escape data for display in html
    foreach (array_keys((array) $interface) as $key) {
        $interface[$key] = htmlentities($interface[$key], ENT_QUOTES, $conf['php_charset']);
    }
    foreach (array_keys((array) $subnet) as $key) {
        $subnet[$key] = htmlentities($subnet[$key], ENT_QUOTES, $conf['php_charset']);
    }
    foreach (array_keys((array) $host) as $key) {
        $host[$key] = htmlentities($host[$key], ENT_QUOTES, $conf['php_charset']);
    }
    // Set the window title:
    $window['title'] = "Add Interface";
    if ($interface['id']) {
        $window['title'] = "Edit Interface";
    }
    // Javascript to run after the window is built
    $window['js'] = <<<EOL
        /* Put a minimize icon in the title bar */
        el('{$window_name}_title_r').innerHTML =
            '&nbsp;<a onClick="toggle_window(\\'{$window_name}\\');" title="Minimize window" style="cursor: pointer;"><img src="{$images}/icon_minimize.gif" border="0" /></a>' +
            el('{$window_name}_title_r').innerHTML;

        /* Put a help icon in the title bar */
        el('{$window_name}_title_r').innerHTML =
            '&nbsp;<a href="{$_ENV['help_url']}{$window_name}" target="null" title="Help" style="cursor: pointer;"><img src="{$images}/silk/help.png" border="0" /></a>' +
            el('{$window_name}_title_r').innerHTML;

        /* Setup the Quick Find FREE IP icon */
        var _button = el('qf_free_ip_{$window_name}');
        _button.style.cursor = 'pointer';
        _button.onclick =
            function(ev) {
                if (!ev) ev = event;
                /* Create the popup div */
                wwTT(this, ev,
                     'id', 'tt_qf_free_ip_{$window_name}',
                     'type', 'static',
                     'direction', 'south',
                     'delay', 0,
                     'styleClass', 'wwTT_qf',
                     'javascript',
                     "xajax_window_submit('tooltips', '" +
                         "tooltip=>qf_free_ip," +
                         "id=>tt_qf_free_ip_{$window_name}," +
                         "text_id=>associated_subnet_{$window_name}," +
                         "text_value=>" + el('associated_subnet_{$window_name}').innerHTML + "," +
                         "input_id=>set_ip_{$window_name}');"
                );
            };

        suggest_setup('hostname',  'suggest_int_hostname');
        el('hostname').focus();
EOL;
    // Define the window's inner html
    $window['html'] = <<<EOL

    <!-- Interface Edit Form -->
    <form id="{$window_name}_edit_form" onSubmit="return false;">
    <input type="hidden" name="interface_id" value="{$interface['id']}">
EOL;
    if ($host['fqdn']) {
        $window['html'] .= <<<EOL
       <input type="hidden" name="host" value="{$interface['host_id']}">
       <input type="hidden" name="hostfqdn" value="{$host['fqdn']}">
EOL;
    }
    $window['html'] .= <<<EOL
    <input type="hidden" name="js" value="{$form['js']}">
    <table cellspacing="0" border="0" cellpadding="0" style="background-color: {$color['window_content_bg']}; padding-left: 20px; padding-right: 20px; padding-top: 5px; padding-bottom: 5px;">

        <!-- INTERFACE RECORD -->
        <tr>
            <td align="left" nowrap="true"><b><u>Interface Record</u></b>&nbsp;</td>
            <td class="padding" align="left" width="100%">&nbsp;</td>
        </tr>

        <tr>

EOL;
    if ($host['fqdn']) {
        $window['html'] .= <<<EOL
            <td align="right" nowrap="true">
                Host:
            </td>
            <td class="padding" align="left" width="100%">
                {$host['fqdn']}&nbsp;
            </td>
EOL;
    } else {
        $window['html'] .= <<<EOL
            <td class="input_required" align="right" nowrap="true">
                Existing Host
            </td>
            <td class="padding" align="left" width="100%">
                <input
                    id="hostname"
                    name="host"
                    alt="Hostname"
                    value="{$host['name']}"
                    class="edit"
                    type="text"
                    size="20" maxlength="64"
                >
                <div id="suggest_int_hostname" class="suggest"></div>
            </td>
EOL;
    }
    $window['html'] .= <<<EOL
        </tr>

        <tr>
            <td align="right" nowrap="true">
                Subnet:
            </td>
            <td class="padding" align="left" width="100%" nowrap="true">
                <span id="associated_subnet_{$window_name}"
                >{$subnet['name']}</span>
            </td>
        </tr>

        <tr>
            <td class="input_required" align="right" nowrap="true">
                IP Address
            </td>
            <td class="padding" align="left" width="100%" nowrap="true">
                <input
                    id="set_ip_{$window_name}"
                    name="set_ip"
                    alt="IP Address"
                    value="{$interface['ip_addr']}"
                    class="edit"
                    type="text"
                    size="25" maxlength="64"
                >
                <span id="qf_free_ip_{$window_name}" title="Available IP Quick Search"><img src="{$images}/silk/find.png" border="0"/></span>
                <div id="suggest_set_ip_{$window_name}" class="suggest"></div>
            </td>
        </tr>
        <tr>
            <td align="right" nowrap="true">
                MAC Address
            </td>
            <td class="padding" align="left" width="100%">
                <input
                    id="set_mac"
                    name="set_mac"
                    alt="MAC Address"
                    value="{$interface['mac_addr']}"
                    class="edit"
                    type="text"
                    size="17" maxlength="17"
                >
                <a class="nav" onClick="this.style.display = 'none'; el('force_{$window_name}').style.display = browser.isIE ? 'block' : 'table-row';">More >></a>
            </td>
        </tr>

        <tr id="force_{$window_name}" style="display: none;">
            <td align="right" nowrap="true">
                &nbsp;
            </td>
            <td nowrap class="padding" align="left" width="100%">
                <input
                    name="force"
                    alt="Allow duplicate MAC addresses"
                    type="checkbox"
                > Allow duplicate MAC addresses
            </td>
        </tr>

        <tr>
            <td align="right" nowrap="true">
                Interface name
            </td>
            <td class="padding" align="left" width="100%">
                <input
                    name="set_name"
                    alt="Interface name"
                    value="{$interface['name']}"
                    class="edit"
                    type="text"
                    size="17" maxlength="255"
                >
            </td>
        </tr>

        <tr>
            <td align="right" nowrap="true">
                Interface description
            </td>
            <td class="padding" align="left" width="100%">
                <input
                    name="set_description"
                    alt="Interface description"
                    value="{$interface['description']}"
                    class="edit"
                    type="text"
                    size="25" maxlength="255"
                >
            </td>
        </tr>
EOL;
    // Show a "keep adding" checkbox if they are adding records
    if (!isset($interface['id'])) {
        // Print a dns view selector
        if ($conf['dns_views']) {
            $window['html'] .= <<<EOL
        <tr>
            <td align="right" nowrap="true">
                DNS View for PTR
            </td>
            <td class="padding" align="left" width="100%">
                <select
                    id="dns_view_select"
                    name="set_view"
                    alt="DNS View"
                    class="edit"
                >{$dns_view_list}</select>
            </td>
        </tr>

EOL;
        }
        $window['html'] .= <<<EOL
        <td align="right" nowrap="true">
            Auto create PTR
        </td>
        <td class="padding" align="left" width="100%" nowrap>
            <input
                id="set_addptr"
                name="set_addptr"
                alt="Automaticaly create PTR record"
                type="checkbox"
                checked="1"
            />
        </td>


        <tr>
            <td align="right" nowrap="true">
                &nbsp;
            </td>
            <td nowrap class="padding" align="left" width="100%">
                <input
                    name="keepadding"
                    alt="Keep adding more interfaces"
                    type="checkbox"
                > Keep adding more interfaces
            </td>
        </tr>

        <tr>
            <td colspan="2" class="padding" align="center" width="100%">
            <span id="statusinfo_{$window_name}" style="color: green;" ></span>
            </td>
        </tr>

EOL;
    }
    $window['html'] .= <<<EOL
        <tr>
            <td align="right" valign="top" nowrap="true">
                &nbsp;
            </td>
            <td class="padding" align="right" width="100%">
                <input class="edit" type="button" name="cancel" value="Cancel" onClick="removeElement('{$window_name}');">
                <input class="edit" type="button"
                    name="submit"
                    value="Save"
                    accesskey=" "
                    onClick="xajax_window_submit('{$window_name}', xajax.getFormValues('{$window_name}_edit_form'), 'save');"
                >
            </td>
        </tr>

    </table>
    </form>
EOL;
    return window_open($window_name, $window);
}
コード例 #9
0
ファイル: interface.inc.php プロジェクト: edt82/ona
function interface_modify($options = "")
{
    global $conf, $self, $onadb;
    printmsg("DEBUG => interface_modify({$options}) called", 3);
    // Version - UPDATE on every edit!
    $version = '1.11';
    // Parse incoming options string to an array
    $options = parse_options($options);
    // Set options[use_primary] to N if they're not set
    $options['use_primary'] = sanitize_YN($options['use_primary'], 'N');
    // Set options[force] to N if it's not set
    $options['force'] = sanitize_YN($options['force'], 'N');
    // Return the usage summary if we need to
    if ($options['help'] or !$options['interface'] and !$options['host'] or !$options['set_ip'] and !$options['set_mac'] and !$options['set_description'] and !$options['set_last_response'] and !$options['set_name']) {
        // NOTE: Help message lines should not exceed 80 characters for proper display on a console
        $self['error'] = 'ERROR => Insufficient parameters';
        return array(1, <<<EOM

interface_modify-v{$version}
Modify an interface record

  Synopsis: interface_modify [KEY=VALUE] ...

  Required:
    interface=ID or IP or MAC     interface ID or IP address
     or
    host=NAME[.DOMAIN] or ID      find interface by hostname or host_id

    set_ip=IP                     change IP address (numeric or dotted format)
    set_mac=ADDRESS               change the mac address (most formats ok)
    set_name=NAME                 interface name (i.e. "FastEthernet0/1.100")
    set_description=TEXT          description (i.e. "VPN link to building 3")
    set_last_response=DATE        date ip was last seen

  Optional:
    use_primary[=Y]               use the host's primary interface (only applies
                                  when "host" option is used!). NOTE: dcm.pl
                                  requires a value ("Y").


EOM
);
    }
    // They provided a interface ID, IP address, interface name, or MAC address
    if ($options['interface']) {
        // Find an interface record by something in that interface's record
        list($status, $rows, $interface) = ona_find_interface($options['interface']);
    } else {
        if ($options['host']) {
            // Find a host by the user's input
            list($status, $rows, $host) = ona_find_host($options['host']);
            if (!$host['id']) {
                printmsg("DEBUG => Host not found ({$options['host']})!", 3);
                $self['error'] = "ERROR => Host not found ({$options['host']})!";
                return array(2, $self['error'] . "\n");
            }
            // If we got one, load an associated interface
            // ... or the primary interface, if the use_primary option is present
            if ($options['use_primary'] == 'Y') {
                list($status, $rows, $interface) = ona_get_interface_record(array('id' => $host['primary_interface_id']));
            } else {
                list($status, $rows, $interface) = ona_get_interface_record(array('host_id' => $host['id']));
                if ($rows > 1) {
                    printmsg("DEBUG => Specified host ({$options['host']}) has more than one interface!", 3);
                    $self['error'] = "ERROR => Specified host ({$options['host']}) has more than one interface!";
                    return array(3, $self['error'] . "\n");
                }
            }
        }
    }
    // If we didn't get a record then exit
    if (!$interface or !$interface['id']) {
        printmsg("DEBUG => Interface not found ({$options['interface']})!", 3);
        $self['error'] = "ERROR => Interface not found ({$options['interface']})!";
        return array(4, $self['error'] . "\n");
    }
    // This array will contain the updated info we'll insert into the DB
    $SET = array();
    // Setting an IP address?
    if ($options['set_ip']) {
        $options['set_ip'] = trim($options['set_ip']);
        $orig_ip = $options['set_ip'];
        $options['set_ip'] = ip_mangle($options['set_ip'], 'numeric');
        if ($options['set_ip'] == -1) {
            printmsg("DEBUG => Invalid IP address ({$orig_ip})", 3);
            $self['error'] = "ERROR => Invalid IP address ({$orig_ip})";
            return array(5, $self['error'] . "\n");
        }
        // Validate that there isn't already another interface with the same IP address
        list($status, $rows, $record) = ona_get_interface_record("ip_addr = {$options['set_ip']}");
        if ($rows and $record['id'] != $interface['id']) {
            printmsg("DEBUG => IP conflict: That IP address (" . ip_mangle($orig_ip, 'dotted') . ") is already in use!", 3);
            $self['error'] = "ERROR => IP conflict: specified IP (" . ip_mangle($orig_ip, 'dotted') . ") is already in use!";
            return array(6, $self['error'] . "\nINFO => Conflicting interface record ID: {$record['ID']}\n");
        }
        // Since the IP seems available, let's double check and make sure it's not in a DHCP address pool
        list($status, $rows, $pool) = ona_get_dhcp_pool_record("ip_addr_start <= '{$options['set_ip']}' AND ip_addr_end >= '{$options['set_ip']}'");
        if ($status or $rows) {
            printmsg("DEBUG => IP conflict: That IP address (" . ip_mangle($orig_ip, 'dotted') . ") falls within a DHCP address pool!", 3);
            $self['error'] = "ERROR => IP conflict: That IP address (" . ip_mangle($orig_ip, 'dotted') . ") falls within a DHCP address pool!";
            return array(5, $self['error'] . "\n" . "INFO => Conflicting DHCP pool record ID: {$pool['id']}\n");
        }
        // Find the Subnet (network) ID to use from the IP address
        list($status, $rows, $subnet) = ona_find_subnet(ip_mangle($options['set_ip'], 'dotted'));
        if ($status or !$rows) {
            printmsg("DEBUG => That IP address (" . ip_mangle($orig_ip, 'dotted') . ") is not inside a defined subnet!", 3);
            $self['error'] = "ERROR => That IP address (" . ip_mangle($orig_ip, 'dotted') . ") is not inside a defined subnet!";
            return array(7, $self['error'] . "\n");
        }
        // Validate that the IP address supplied isn't the base or broadcast of the subnet
        if (is_ipv4($options['set_ip']) && $options['set_ip'] == $subnet['ip_addr'] || !is_ipv4($options['set_ip']) && !gmp_cmp(gmp_init($options['set_ip']), gmp_init($subnet['ip_addr']))) {
            printmsg("DEBUG => IP address (" . ip_mangle($orig_ip, 'dotted') . ") can't be a subnet's base address!", 3);
            $self['error'] = "ERROR => IP address (" . ip_mangle($orig_ip, 'dotted') . ") can't be a subnet's base address!";
            return array(8, $self['error'] . "\n");
        }
        if (is_ipv4($options['set_ip']) && $options['set_ip'] == 4294967295 - $subnet['ip_mask'] + $subnet['ip_addr'] || !is_ipv4($options['set_ip']) && !gmp_cmp(gmp_init($options['set_ip']), gmp_add(gmp_init($subnet['ip_addr']), gmp_sub("340282366920938463463374607431768211455", $subnet['ip_mask'])))) {
            printmsg("DEBUG => IP address (" . ip_mangle($orig_ip, 'dotted') . ") can't be a subnet's broadcast address!", 3);
            $self['error'] = "ERROR => IP address (" . ip_mangle($orig_ip, 'dotted') . ") can't be the subnet broadcast address!";
            return array(9, $self['error'] . "\n");
        }
        // Allow some overrides.
        if ($options['force'] != 'Y') {
            // Search for any existing interfaces on the same subnet
            //            list($status, $rows, $record) = ona_get_interface_record(array('subnet_id' => $subnet['id'],
            //                                                                            'host_id'    => $interface['host_id']));
            // Check to be sure we don't exceed maximum lengths
            if (strlen($options['name']) > 255) {
                $self['error'] = "ERROR => 'name' exceeds maximum length of 255 characters.";
                return array(2, $self['error'] . "\n" . "NOTICE => You may ignore this error and add the interface anyway with the \"force=yes\" option.\n");
            }
            if (strlen($options['description']) > 255) {
                $self['error'] = "ERROR => 'description' exceeds maximum length of 255 characters.";
                return array(2, $self['error'] . "\n" . "NOTICE => You may ignore this error and add the interface anyway with the \"force=yes\" option.\n");
            }
        }
        // Make sure we update the ptr record domain if needed.
        // MP: TODO: would it be better to run the dns_modify module vs doing a direct db_update_record???
        $ipflip = ip_mangle($options['set_ip'], 'flip');
        $octets = explode(".", $ipflip);
        if (count($octets) > 4) {
            $arpa = '.ip6.arpa';
            $octcount = 31;
        } else {
            $arpa = '.in-addr.arpa';
            $octcount = 3;
        }
        // Find a pointer zone for this record to associate with.
        list($status, $prows, $ptrdomain) = ona_find_domain($ipflip . $arpa);
        if (isset($ptrdomain['id'])) {
            list($status, $rows, $dnsrec) = ona_get_dns_record(array('type' => 'PTR', 'interface_id' => $interface['id']));
            // If the new ptrdomain does not match an existing ptr records domain then we need to change it.
            if ($rows > 0 and $dnsrec['domain_id'] != $ptrdomain['id']) {
                list($status, $rows) = db_update_record($onadb, 'dns', array('id' => $dnsrec['id']), array('domain_id' => $ptrdomain['id'], 'ebegin' => date('Y-m-j G:i:s')));
                if ($status or !$rows) {
                    $self['error'] = "ERROR => interface_modify() PTR record domain update failed: " . $self['error'];
                    printmsg($self['error'], 0);
                    return array(14, $self['error'] . "\n");
                }
            }
        }
        // TRIGGER: Since we are changing the IP of an interface that dns records may point to, we need to loop through them all
        if ($interface['ip_addr'] != $options['set_ip']) {
            // Get all the DNS records using this interface ID
            list($status, $rows, $records) = db_get_records($onadb, 'dns', array('interface_id' => $interface['id']));
            // Loop them and set their domains for rebuild
            foreach ($records as $record) {
                list($status, $rows) = db_update_record($onadb, 'dns_server_domains', array('domain_id' => $record['domain_id']), array('rebuild_flag' => 1));
                if ($status) {
                    $self['error'] = "ERROR => dns_record_add() Unable to update rebuild flags for domain.: {$self['error']}";
                    printmsg($self['error'], 0);
                    return array(7, $self['error'] . "\n");
                }
            }
        }
        // Check permissions
        //         if (!authlvl($subnet['LVL'])) {
        //             $self['error'] = "Permission denied!";
        //             printmsg($self['error'], 0);
        //             return(array(13, $self['error'] . "\n"));
        //         }
        // Everything looks ok, add it to $SET
        if ($interface['subnet_id'] != $subnet['id']) {
            $SET['subnet_id'] = $subnet['id'];
        }
        if ($interface['ip_addr'] != $options['set_ip']) {
            $SET['ip_addr'] = $options['set_ip'];
        }
    }
    // Setting an MAC address?
    if (array_key_exists('set_mac', $options)) {
        if ($options['set_mac']) {
            // allow null mac addresses (to unset one for example)
            $options['set_mac'] = trim($options['set_mac']);
            $orig_mac = $options['set_mac'];
            $options['set_mac'] = mac_mangle($options['set_mac'], 1);
            if ($options['set_mac'] == -1) {
                printmsg("DEBUG => The MAC address specified ({$orig_mac}) is invalid!", 3);
                $self['error'] = "ERROR => The MAC address specified ({$orig_mac}) is invalid!";
                return array(11, $self['error'] . "\n");
            }
            // Unless they have opted to allow duplicate mac addresses ...
            if ($options['force'] != 'Y') {
                // Validate that there isn't already another interface with the same MAC address on another host
                // Assume duplicate macs on the same host are ok
                list($status, $rows, $record) = db_get_record($onadb, 'interfaces', "mac_addr LIKE '{$options['set_mac']}' AND host_id != {$interface['host_id']}");
                if ($rows and $record['id'] != $interface['id'] or $rows > 1) {
                    printmsg("DEBUG => MAC conflict: That MAC address ({$options['set_mac']}) is already in use on another host!", 3);
                    $self['error'] = "ERROR => MAC conflict: That MAC address ({$options['set_mac']}) is already in use on another host!";
                    return array(12, $self['error'] . "\n" . "NOTICE => You may ignore this error and update the interface anyway with the \"force=yes\" option.\n" . "INFO => Conflicting interface record ID: {$record['id']}\n");
                }
            }
        }
        if ($interface['mac_addr'] != $options['set_mac']) {
            $SET['mac_addr'] = $options['set_mac'];
        }
    }
    // Check the date formatting etc
    if (isset($options['set_last_response'])) {
        // format the time that was passed in for the database
        $SET['last_response'] = date('Y-m-j G-i-s', strtotime($options['set_last_response']));
    }
    // Set options[set_name]?
    if (array_key_exists('set_name', $options) && $interface['name'] != $options['set_name']) {
        $SET['name'] = trim($options['set_name']);
    }
    // Set options[set_description]?
    if (array_key_exists('set_description', $options) && $interface['description'] != $options['set_description']) {
        $SET['description'] = $options['set_description'];
    }
    // Check permissions
    list($status, $rows, $host) = ona_find_host($interface['host_id']);
    if (!auth('interface_modify')) {
        $self['error'] = "Permission denied!";
        printmsg($self['error'], 0);
        return array(13, $self['error'] . "\n");
    }
    // Get the interface record before updating (logging)
    list($status, $rows, $original_interface) = ona_get_interface_record(array('id' => $interface['id']));
    // Update the interface record
    if (count($SET) > 0) {
        list($status, $rows) = db_update_record($onadb, 'interfaces', array('id' => $interface['id']), $SET);
        if ($status or !$rows) {
            $self['error'] = "ERROR => interface_modify() SQL Query failed: " . $self['error'];
            printmsg($self['error'], 0);
            return array(14, $self['error'] . "\n");
        }
    }
    // Get the interface record after updating (logging)
    list($status, $rows, $new_interface) = ona_get_interface_record(array('id' => $interface['id']));
    list($status, $rows, $new_int) = ona_find_interface($interface['id']);
    // Return the success notice
    $text = format_array($SET);
    $self['error'] = "INFO => Interface UPDATED:{$interface['id']}: {$new_int['ip_addr_text']}";
    $log_msg = "INFO => Interface UPDATED:{$interface['id']}:{$new_int['ip_addr_text']}: ";
    $more = "";
    foreach (array_keys($original_interface) as $key) {
        if ($original_interface[$key] != $new_interface[$key]) {
            $log_msg .= $more . $key . "[" . $original_interface[$key] . "=>" . $new_interface[$key] . "]";
            $more = ";";
        }
    }
    // only print to logfile if a change has been made to the record
    if ($more != '') {
        printmsg($log_msg, 0);
    }
    return array(0, $self['error'] . "\n{$text}\n");
}