Ejemplo n.º 1
0
function mangle_ip($options)
{
    global $conf, $self;
    printmsg('DEBUG => mangle_ip(' . $options . ') called', 3);
    // Version - UPDATE on every edit!
    $version = '1.00';
    // Parse incoming options string to an array
    $options = parse_options($options);
    // Return the usage summary if we need to
    if ($options['help'] or !$options['ip']) {
        $self['error'] = 'ERROR => Insufficient parameters';
        // NOTE: Help message lines should not exceed 80 characters for proper display on a console
        return array(1, <<<EOM

mangle_ip v{$version}
Converts between various IP address representations

  Synopsis: mangle_ip(OPTIONS)

  Required:
    ip=<inet_addr>  32 or 128-bit Internet address

  Optional:
    format=<specifier>  Desired output format, specified as a string
                        numeric : return ip as an integer
                        dotted  : return ip as an IPv4 address
                        cidr    : return ip as a CIDR netmask
                        binary  : return ip as a 32-bit binary string
                        bin128  : return ip as a 128-bit binary string
                        ipv6    : return ip as an IPv6 address
                        ipv6gz  : return ip as a compressed IPv6 address



EOM
);
    }
    // Now what?  We need to call ip_mangle() with our options
    if (!$options['format']) {
        $options['format'] = 'default';
    }
    $retval = ip_mangle($options['ip'], $options['format']) . "\n";
    if ($self['error'] != '') {
        return array(1, $self['error'] . "\n");
    } else {
        return array(0, $retval);
    }
}
Ejemplo n.º 2
0
function ws_display($window_name, $form = '')
{
    global $conf, $self, $onadb;
    global $images, $color, $style;
    $html = '';
    $js = '';
    $debug_val = 3;
    // used in the auth() calls to supress logging
    // If the user supplied an array in a string, build the array and store it in $form
    $form = parse_options_string($form);
    // Load the host record
    list($status, $rows, $record) = ona_get_block_record(array('id' => $form['block_id']));
    if ($status or !$rows) {
        array_pop($_SESSION['ona']['work_space']['history']);
        $html .= "<br><center><font color=\"red\"><b>Block doesn't exist!</b></font></center>";
        $response = new xajaxResponse();
        $response->addAssign("work_space_content", "innerHTML", $html);
        return $response->getXML();
    }
    // Update History Title
    $history = array_pop($_SESSION['ona']['work_space']['history']);
    $js .= "xajax_window_submit('work_space', ' ', 'rewrite_history');";
    if ($history['title'] == $window_name) {
        $history['title'] = $record['name'];
        array_push($_SESSION['ona']['work_space']['history'], $history);
    }
    // Create some javascript to refresh the current page
    $refresh = htmlentities(str_replace(array("'", '"'), array("\\'", '\\"'), $history['url']), ENT_QUOTES, $conf['php_charset']);
    $refresh = "xajax_window_submit('work_space', '{$refresh}');";
    $record['ip_addr_start'] = ip_mangle($record['ip_addr_start'], 'dotted');
    $record['ip_addr_end'] = ip_mangle($record['ip_addr_end'], 'dotted');
    $style['content_box'] = <<<EOL
        margin: 10px 20px;
        padding: 2px 4px;
        background-color: #FFFFFF;
        vertical-align: top;
EOL;
    $style['label_box'] = <<<EOL
        font-weight: bold;
        padding: 2px 4px;
        border: solid 1px {$color['border']};
        background-color: {$color['window_content_bg']};
EOL;
    // Escape data for display in html
    foreach (array_keys($record) as $key) {
        $record[$key] = htmlentities($record[$key], ENT_QUOTES, $conf['php_charset']);
    }
    $html .= <<<EOL
    <!-- FORMATTING TABLE -->
    <div style="{$style['content_box']}">
    <table cellspacing="0" border="0" cellpadding="0"><tr>

        <!-- START OF FIRST COLUMN OF SMALL BOXES -->
        <td nowrap="true" valign="top" style="padding-right: 15px;">
EOL;
    // BLOCK INFORMATION
    $html .= <<<EOL
            <table width=100% cellspacing="0" border="0" cellpadding="0" style="margin-bottom: 8px;">

                <tr><td colspan="99" nowrap="true" style="{$style['label_box']}">
                    <!-- LABEL -->
                    <form id="form_block_{$record['id']}"
                        ><input type="hidden" name="block_id" value="{$record['id']}"
                        ><input type="hidden" name="js" value="{$refresh}"
                    ></form>
EOL;
    if (auth('advanced', $debug_val)) {
        $html .= <<<EOL

                    <a title="Edit block"
                       class="act"
                       onClick="xajax_window_submit('edit_block', xajax.getFormValues('form_block_{$record['id']}'), 'editor');"
                    ><img src="{$images}/silk/page_edit.png" border="0"></a>&nbsp;

                    <a title="Delete block"
                       class="act"
                       onClick="var doit=confirm('Are you sure you want to delete this block?');
                                if (doit == true)
                                    xajax_window_submit('edit_block', xajax.getFormValues('form_block_{$record['id']}'), 'delete');"
                    ><img src="{$images}/silk/delete.png" border="0"></a>&nbsp;
EOL;
    }
    $html .= <<<EOL
                    {$record['name']}

                    &nbsp;&nbsp;<a href="?work_space={$window_name}&block_id={$record['id']}"><img title="Direct link to {$record['name']}" src="{$images}/silk/application_link.png" border="0"></a>
                </td>
                </tr>
                <tr>
                    <td align="right" nowrap="true"><b>Name</b>&nbsp;</td>
                    <td class="padding" align="left">{$record['name']}&nbsp;</td>
                </tr>

                <tr>
                    <td align="right" nowrap="true"><b>IP start</b>&nbsp;</td>
                    <td class="padding" align="left">
                        {$record['ip_addr_start']}
                        &nbsp;
                    </td>
                </tr>
                <tr>
                    <td align="right" nowrap="true"><b>IP end</b>&nbsp;</td>
                    <td class="padding" align="left">
                        {$record['ip_addr_end']}
                        &nbsp;
                    </td>
                </tr>
                <tr>
                    <td align="right" nowrap="true"><b>Notes</b>&nbsp;</td>
                    <td class="padding" align="left">
                        {$record['notes']}
                        &nbsp;
                    </td>
                </tr>


            </table>
EOL;
    // END BLOCK INFORMATION
    $html .= <<<EOL
        <!-- END OF FIRST COLUMN OF SMALL BOXES -->
        </td>

        <!-- START OF SECOND COLUMN OF SMALL BOXES -->
        <td valign="top" style="padding-right: 15px;">
EOL;
    // SMALL SUBNET MAP
    // Get the numeric IP address of our subnet (we replace the last quad with a .0)
    $ip_subnet = ip_mangle($record['ip_addr_start'], 'numeric');
    if (is_ipv4($ip_subnet)) {
        $end = '\\.\\d+$';
        $replace_end_by = '.0';
        $version = 4;
    } else {
        $end = ':[0-9A-F]{0,4}$';
        // $replace_end_by = ':0000';
        $replace_end_by = ':';
        $version = 6;
    }
    $ip = ip_mangle(preg_replace("/{$end}/", $replace_end_by, $record['ip_addr_start']), 'numeric');
    $html .= <<<EOL
            <table width=100% cellspacing="0" border="0" cellpadding="0" style="margin-bottom: 8px;">
                <tr><td colspan="99" nowrap="true">
                    <!-- LABEL -->
                    <div style="{$style['label_box']}">
                        <a title="Display full sized subnet map"
                           class="act"
                           onClick="xajax_window_submit('work_space', 'xajax_window_submit(\\'display_block_map\\', \\'ip_block_start=>{$record['ip_addr_start']},ip_block_end=>{$record['ip_addr_end']},id=>{$record['id']}\\', \\'display\\');');"
                        ><img src="{$images}/silk/shape_align_left.png" border="0"></a>&nbsp;
                        <a title="Highlight start of block"
                           class="act"
                           onClick="
                             var _el = el('{$ip_subnet}_row_label');
                             if (_el) {
                               if (_el.style.isHighlighted) {
                                 _el.style.backgroundColor = '#000000';
                                 _el.style.isHighlighted = false;
                               }
                               else {
                                 _el.style.backgroundColor = '{$color['bgcolor_map_selected']}';
                                 _el.style.isHighlighted = true;
                               }
                             }
                           "
                        ><img src="{$images}/silk/paintbrush.png" border="0"></a>&nbsp;
                        <b>Block Map</b>
                    </div>
                </td></tr>

                <tr><td colspan="99" nowrap="true">
                    <input type="hidden" id="{$window_name}_zoom" name="zoom" value="7">
                    <div id="{$window_name}_portal" style="position: relative; height: 150px; width: 355px;">
                        <span id="{$window_name}_substrate"></span>
                    </div>
                </td></tr>
            </table>
EOL;
    // Get javascript to setup the map portal mouse handlers
    // Force ip end to be less than ip start to prevent Block highlighting
    $portal_js .= get_portal_js($window_name, $ip, $version);
    //*** Send a fake mouseup event to draw the initial map view ***
    $portal_js .= "el('{$window_name}_portal').myonmouseup('fake event');";
    // END SMALL SUBNET MAP
    $html .= <<<EOL
        <!-- END OF SECOND COLUMN OF SMALL BOXES -->
        </td>

        <!-- START OF THIRD COLUMN OF SMALL BOXES -->
        <td valign="top" style="padding-right: 15px;">
EOL;
    $html .= <<<EOL
        </td>
        <!-- END OF THIRD COLUMN OF SMALL BOXES -->
    </tr></table>
    </div>
    <!-- END OF TOP SECTION -->
EOL;
    // SUBNET LIST
    $tab = 'subnets';
    $submit_window = "list_{$tab}";
    $form_id = "{$submit_window}_filter_form";
    $_SESSION['ona'][$form_id]['tab'] = $tab;
    $content_id = "{$window_name}_{$submit_window}";
    $html .= <<<EOL
    <!-- SUBNET LIST -->
    <div style="border: 1px solid {$color['border']}; margin: 10px 20px;">

        <!-- Tab & Quick Filter -->
        <table id="{$form_id}_table" cellspacing="0" border="0" cellpadding="0">
            <tr>
                <td id="{$form_id}_subnets_tab" class="table-tab-active">
                    Associated {$tab} <span id="{$form_id}_{$tab}_count"></span>
                </td>

                <td id="{$form_id}_quick_filter" class="padding" align="right" width="100%">
                    <form id="{$form_id}" onSubmit="return false;">
                    <input id="{$form_id}_page" name="page" value="1" type="hidden">
                    <input name="content_id" value="{$content_id}" type="hidden">
                    <input name="form_id" value="{$form_id}" type="hidden">
                    <input name="ip_subnet" value="{$record['ip_addr_start']}" type="hidden">
                    <input name="ip_subnet_thru" value="{$record['ip_addr_end']}" type="hidden">
                    <div id="{$form_id}_filter_overlay"
                         title="Filter"
                         style="position: relative;
                                display: inline;
                                color: #CACACA;
                                cursor: text;"
                         onClick="this.style.display = 'none'; el('{$form_id}_filter').focus();"
                    >Name</div>
                    <input
                        id="{$form_id}_filter"
                        name="filter"
                        class="filter"
                        type="text"
                        value=""
                        size="10"
                        maxlength="20"
                        alt="Quick Filter"
                        onFocus="el('{$form_id}_filter_overlay').style.display = 'none';"
                        onBlur="if (this.value == '') el('{$form_id}_filter_overlay').style.display = 'inline';"
                        onKeyUp="
                            if (typeof(timer) != 'undefined') clearTimeout(timer);
                            code = 'if ({$form_id}_last_search != el(\\'{$form_id}_filter\\').value) {' +
                                   '    {$form_id}_last_search = el(\\'{$form_id}_filter\\').value;' +
                                   '    document.getElementById(\\'{$form_id}_page\\').value = 1;' +
                                   '    xajax_window_submit(\\'{$submit_window}\\', xajax.getFormValues(\\'{$form_id}\\'), \\'display_list\\');' +
                                   '}';
                            timer = setTimeout(code, 700);"
                    >
                    </form>
                </td>

            </tr>
        </table>

        <div id='{$content_id}'>
            {$conf['loading_icon']}
        </div>

    </div>
EOL;
    $js .= <<<EOL
        /* Setup the quick filter */
        el('{$form_id}_filter_overlay').style.left = (el('{$form_id}_filter_overlay').offsetWidth + 10) + 'px';
        {$form_id}_last_search = '';

        /* Tell the browser to load/display the list */
        xajax_window_submit('{$submit_window}', xajax.getFormValues('{$form_id}'), 'display_list');
EOL;
    // Insert the new html into the window
    // Instantiate the xajaxResponse object
    $response = new xajaxResponse();
    // GDO need to use Big Int JS
    $response->addIncludeScript('include/js/bignumber.js');
    $response->addAssign("work_space_content", "innerHTML", $html);
    if ($js) {
        $response->addScript($js . $portal_js);
    }
    return $response->getXML();
}
Ejemplo n.º 3
0
function block_modify($options = "")
{
    // The important globals
    global $conf, $self, $onadb;
    // Version - UPDATE on every edit!
    $version = '1.02';
    printmsg("DEBUG => block_modify({$options}) called", 3);
    // Parse incoming options string to an array
    $options = parse_options($options);
    // Return the usage summary if we need to
    if ($options['help'] or !$options['block'] or !($options['set_name'] or $options['set_start'] or $options['set_end'] or $options['set_notes'])) {
        // NOTE: Help message lines should not exceed 80 characters for proper display on a console
        $self['error'] = 'ERROR => Insufficient parameters';
        return array(1, <<<EOM

block_modify-v{$version}
Modifies a block entry in the database

  Synopsis: block_modify [KEY=VALUE] ...

  Where:
    block=NAME or ID               block Name or ID

  Update:
    set_name=NAME                  change block name
    set_start=STRING               change block starting IP address
    set_end=STRING                 change block end
    set_notes=STRING               change block notes



EOM
);
    }
    // The formatting rule on block names is all upper and trim it
    $options['set_name'] = trim($options['set_name']);
    $options['set_name'] = preg_replace('/\\s+/', '-', $options['set_name']);
    $options['set_name'] = strtoupper($options['set_name']);
    // If the block provided is numeric, check to see if it's an block
    if (is_numeric($options['block'])) {
        // See if it's an block_id
        list($status, $rows, $block) = ona_get_block_record(array('id' => $options['block']));
        if (!$block['id']) {
            printmsg("DEBUG => Unable to find block using the ID {$options['block']}!", 3);
            $self['error'] = "ERROR => Unable to find block using the ID {$options['block']}!";
            return array(2, $self['error'] . "\n");
        }
    } else {
        list($status, $rows, $block) = ona_get_block_record(array('name' => $options['block']));
        if (!$block['id']) {
            $self['error'] = "ERROR => Unable to find block using the name {$options['block']}!";
            printmsg("DEBUG => Unable to find block using the name {$options['block']}!", 3);
            return array(2, $self['error'] . "\n");
        }
    }
    printmsg("DEBUG => Found block: {$block['name']}", 3);
    // This variable will contain the updated info we'll insert into the DB
    $SET = array();
    // If they are specifying a new name, process it.
    if ($options['set_name']) {
        // Validate that there isn't already an block with this name
        list($status, $rows, $record) = db_get_records($onadb, 'blocks', "id != {$block['id']} AND name LIKE '{$options['set_name']}'");
        if ($status or $rows) {
            printmsg("DEBUG => The block {$options['set_name']} already exists!", 3);
            $self['error'] = "ERROR => The block {$options['set_name']} already exists!";
            return array(4, $self['error'] . "\n");
        }
        $SET['name'] = $options['set_name'];
    }
    if ($options['set_start']) {
        $SET['ip_addr_start'] = ip_mangle($options['set_start'], 'numeric');
    }
    if ($options['set_end']) {
        $SET['ip_addr_end'] = ip_mangle($options['set_end'], 'numeric');
    }
    if (array_key_exists('set_notes', $options)) {
        // There is an issue with escaping '=' and '&'.  We need to avoid adding escape characters
        $options['set_notes'] = str_replace('\\=', '=', $options['set_notes']);
        $options['set_notes'] = str_replace('\\&', '&', $options['set_notes']);
        if ($options['set_notes'] != $block['notes']) {
            $SET['notes'] = $options['set_notes'];
        }
    }
    // Check permissions
    if (!auth('advanced')) {
        $self['error'] = "Permission denied!";
        printmsg($self['error'], 0);
        return array(10, $self['error'] . "\n");
    }
    // Get the block record before updating (logging)
    list($status, $rows, $original_block) = ona_get_block_record(array('id' => $block['id']));
    // Update the record
    list($status, $rows) = db_update_record($onadb, 'blocks', array('id' => $block['id']), $SET);
    if ($status or !$rows) {
        $self['error'] = "ERROR => block_modify() SQL Query failed: " . $self['error'];
        printmsg($self['error'], 0);
        return array(6, $self['error'] . "\n");
    }
    // Get the block record before updating (logging)
    list($status, $rows, $new_block) = ona_get_block_record(array('id' => $block['id']));
    if ($SET['name'] != $block['name']) {
        $new_name = " => {$SET['name']}";
    }
    // Return the success notice
    $self['error'] = "INFO => Block UPDATED:{$block['id']}: {$block['name']} {$new_name}";
    $log_msg = "INFO => Block UPDATED:{$block['id']}: ";
    $more = "";
    foreach (array_keys($original_block) as $key) {
        if ($original_block[$key] != $new_block[$key]) {
            $log_msg .= $more . $key . "[" . $original_block[$key] . "=>" . $new_block[$key] . "]";
            $more = ";";
        }
    }
    // only print to logfile if a change has been made to the record
    if ($more != '') {
        printmsg($self['error'], 0);
        printmsg($log_msg, 0);
    }
    return array(0, $self['error'] . "\n");
}
Ejemplo n.º 4
0
function ws_interface_nat_save($window_name, $form = '')
{
    global $base, $include, $conf, $self, $onadb;
    // Check permissions
    if (!auth('interface_modify')) {
        $response = new xajaxResponse();
        $response->addScript("alert('Permission denied!');");
        return $response->getXML();
    }
    $form = parse_options_string($form);
    // Instantiate the xajaxResponse object
    $response = new xajaxResponse();
    $js = '';
    $refresh = "xajax_window_submit('list_interfaces', xajax.getFormValues('list_interfaces_filter_form'), 'display_list');";
    // Validate input
    if (!$form['ip'] and !$form['natip']) {
        $response->addScript("alert('Please complete all fields to continue!');");
        return $response->getXML();
    }
    // Decide if we're deleting or adding
    $module = 'nat_add';
    if ($form['nataction'] == "delete") {
        $module = 'nat_del';
    }
    // Do a pre check of the ptr domain so we can prompt the user properly
    if ($module == 'nat_add') {
        $ipflip = ip_mangle($form['natip'], 'flip');
        $octets = explode(".", $ipflip);
        list($status, $rows, $ptrdomain) = ona_find_domain($ipflip . ".in-addr.arpa");
        if (!$ptrdomain['id']) {
            printmsg("ERROR => This operation tried to create a PTR record that is the first in the {$octets[3]}.0.0.0 class A range.  You must first create at least the following DNS domain: {$octets[3]}.in-addr.arpa", 3);
            $self['error'] = "ERROR => This operation tried to create a PTR record that is the first in the {$octets[3]}.0.0.0 class A range.  You must first create at least the following DNS domain: {$octets[3]}.in-addr.arpa.  You could also create domains for class B or class C level reverse zones.  Click OK to open add domain dialog";
            $response->addScript("alert('{$self['error']}');xajax_window_submit('edit_domain', 'newptrdomainname=>{$octets[3]}.in-addr.arpa', 'editor');");
            return $response->getXML();
        }
    }
    // Run the module
    list($status, $output) = run_module($module, $form);
    // If the module returned an error code display a popup warning
    if ($status) {
        $js .= "alert('Save failed. " . preg_replace('/[\\s\']+/', ' ', $self['error']) . "');";
    } else {
        $js .= "removeElement('{$window_name}');{$refresh}";
        if ($form['js']) {
            $js .= $form['js'];
        }
    }
    // Insert the new table into the window
    $response->addScript($js);
    return $response->getXML();
}
Ejemplo n.º 5
0
function dns_record_del($options = "")
{
    global $conf, $self, $onadb;
    printmsg("DEBUG => dns_record_del({$options}) called", 3);
    // Version - UPDATE on every edit!
    $version = '1.03';
    // Parse incoming options string to an array
    $options = parse_options($options);
    // Sanitize options[commit] (default is no)
    $options['commit'] = sanitize_YN($options['commit'], 'N');
    // Return the usage summary if we need to
    if ($options['help'] or !$options['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

dns_record_del-v{$version}
Deletes a DNS record from the database

  Synopsis: dns_record_del [KEY=VALUE] ...

  Required:
    name=NAME[.DOMAIN] or ID      hostname or ID of the record to delete
    type=TYPE                     record type (A,CNAME,PTR...)

  Optional:
    ip=ADDRESS                    ip address (numeric or dotted)
    commit=[yes|no]               commit db transaction (no)



EOM
);
    }
    /*
    thoughts on the flow of things:
    A records:
        remove any CNAMES using this A record
        remove any PTR records using this A record
        test that it is not a primary_dns_id, if it is, it must be reassigned
    should make a find_dns_record(s) function.  a find by host option would be good.
    need to do a better delete of DNS records when deleting a host.. currently its a problem.
    MP: TODO:  this delete will not handle DNS views unless you use the ID of the record to delete.  add a view option at some point.
    */
    // If the name we were passed has a leading . in it then remove the dot.
    $options['name'] = preg_replace("/^\\./", '', $options['name']);
    // FIXME: MP Fix this to use a find_dns_record function  ID only for now
    // Find the DNS record from $options['name']
    list($status, $rows, $dns) = ona_find_dns_record($options['name'], $options['type']);
    printmsg("DEBUG => dns_record_del() DNS record: {$options['name']}", 3);
    if (!$dns['id']) {
        printmsg("DEBUG => Unknown DNS record: {$options['name']} ({$options['type']})", 3);
        $self['error'] = "ERROR => Unknown DNS record: {$options['name']} ({$options['type']})";
        return array(2, $self['error'] . "\n");
    }
    // Check permissions
    if (!auth('host_del') or !authlvl($host['LVL'])) {
        $self['error'] = "Permission denied!";
        printmsg($self['error'], 0);
        return array(10, $self['error'] . "\n");
    }
    // If "commit" is yes, delete the host
    if ($options['commit'] == 'Y') {
        $text = "";
        $add_to_error = "";
        // SUMMARY:
        //   Display any associated PTR records for an A record
        //   Display any associated CNAMEs for an A record
        // Test if it is used as a primary_dns_id unless it is the host_del module calling
        if (!isset($options['delete_by_module'])) {
            list($status, $rows, $srecord) = db_get_record($onadb, 'hosts', array('primary_dns_id' => $dns['id']));
            if ($rows) {
                $self['error'] = "ERROR => dns_record_del() The DNS record, {$dns['name']}.{$dns['domain_fqdn']}[{$dns['id']}], is a primary A record for a host! You can not delete it until you associate a new primary record, or delete the host.";
                printmsg($self['error'], 0);
                return array(5, $self['error'] . "\n");
            }
        }
        // Delete related Points to records
        // get list for logging
        list($status, $rows, $records) = db_get_records($onadb, 'dns', array('dns_id' => $dns['id']));
        // do the delete
        list($status, $rows) = db_delete_records($onadb, 'dns', array('dns_id' => $dns['id']));
        if ($status) {
            $self['error'] = "ERROR => dns_record_del() Child record delete SQL Query failed: {$self['error']}";
            printmsg($self['error'], 0);
            return array(5, $self['error'] . "\n");
        }
        if ($rows) {
            // log deletions
            // FIXME: do better logging here
            printmsg("INFO => {$rows} child DNS record(s) DELETED from {$dns['fqdn']}", 0);
            $add_to_error .= "INFO => {$rows} child record(s) DELETED from {$dns['fqdn']}\n";
        }
        // TRIGGER: flag the 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_del() Unable to update rebuild flags for domain.: {$self['error']}";
                printmsg($self['error'], 0);
                return array(7, $self['error'] . "\n");
            }
        }
        // Delete the DNS record
        list($status, $rows) = db_delete_records($onadb, 'dns', array('id' => $dns['id']));
        if ($status) {
            $self['error'] = "ERROR => dns_record_del() DNS record delete SQL Query failed: {$self['error']}";
            printmsg($self['error'], 0);
            return array(5, $add_to_error . $self['error'] . "\n");
        }
        // TRIGGER: flag the current dnsrecords domain for rebuild
        list($status, $rows) = db_update_record($onadb, 'dns_server_domains', array('domain_id' => $dns['domain_id']), array('rebuild_flag' => 1));
        if ($status) {
            $self['error'] = "ERROR => dns_record_del() Unable to update rebuild flags for domain.: {$self['error']}";
            printmsg($self['error'], 0);
            return array(7, $self['error'] . "\n");
        }
        // FIXME: if it is a NS or something display a proper FQDN message here
        // Display proper PTR information
        if ($dns['type'] == 'PTR') {
            list($status, $rows, $pointsto) = ona_get_dns_record(array('id' => $dns['dns_id']), '');
            list($status, $rows, $ptrint) = ona_get_interface_record(array('id' => $dns['interface_id']), '');
            $ipflip = ip_mangle($ptrint['ip_addr'], 'flip');
            $octets = explode(".", $ipflip);
            if (count($octets) > 4) {
                $arpa = '.ip6.arpa';
                $octcount = 31;
            } else {
                $arpa = '.in-addr.arpa';
                $octcount = 3;
            }
            $dns['fqdn'] = "{$ipflip}{$arpa} -> {$pointsto['fqdn']}";
        }
        // Return the success notice
        $self['error'] = "INFO => DNS {$dns['type']} record DELETED: {$dns['fqdn']}";
        printmsg($self['error'], 0);
        return array(0, $add_to_error . $self['error'] . "\n");
    }
    //
    // We are just displaying records that would have been deleted
    //
    // SUMMARY:
    //   Display any associated PTR records for an A record
    //   Display any associated CNAMEs for an A record
    // Otherwise just display the host record for the host we would have deleted
    $text = "Record(s) NOT DELETED (see \"commit\" option)\n" . "Displaying record(s) that would have been deleted:\n";
    // Test if it is used as a primary_dns_id
    list($status, $rows, $srecord) = db_get_record($onadb, 'hosts', array('primary_dns_id' => $dns['id']));
    if ($rows) {
        $text .= "\nWARNING!  This DNS record is a primary A record for a host\n";
    }
    // Display the complete dns record
    list($status, $tmp) = dns_record_display("name={$dns['id']}&verbose=N");
    $text .= "\n" . $tmp;
    // Display associated Child records
    list($status, $rows, $records) = db_get_records($onadb, 'dns', array('dns_id' => $dns['id']));
    if ($rows) {
        $text .= "\nASSOCIATED POINTS-TO RECORDS ({$rows}):\n";
    }
    foreach ($records as $record) {
        if ($record['type'] == 'NS') {
            $record['name'] = '';
        }
        // FIXME:I could fix this but I'm lazy
        if ($record['type'] == 'PTR') {
            $record['name'] = '??';
        }
        list($status, $rows, $domain) = ona_get_domain_record(array('id' => $record['domain_id']), '');
        $text .= " {$record['type']}: {$record['name']}.{$domain['fqdn']} -> {$dns['fqdn']}\n";
    }
    return array(7, $text);
}
Ejemplo n.º 6
0
function ws_draw_block($window_name, $form = '')
{
    global $conf, $self, $ona;
    global $images, $color, $style;
    $html = '';
    $js = '';
    // Instantiate the xajaxResponse object
    $response = new xajaxResponse();
    // If the user supplied an array in a string, build the array and store it in $form
    $form = parse_options_string($form);
    // Find out if $ip is valid
    $ip = ip_mangle($form['ip'], 'numeric');
    if ($ip == -1) {
        $js .= "alert('Invalid IP address!');";
        $response->addScript($js);
        return $response->getXML();
    }
    // Build a few variables
    $label = ip_mangle($ip, 'dotted');
    if (is_ipv4($ip)) {
        $string_size = 15;
    } else {
        $string_size = 20;
    }
    $function = "get_{$form['row_type']}_html";
    $row_zoom = $form['row_zoom'];
    $row_height = $form['row_height'];
    $row_offset = $form['row_offset'];
    // This is the number of pixels to leave for the label on the left (.45 * row height, * $string_size possible characters)
    $label_width = round($form['row_height'] * 0.45 * $string_size);
    $font_height = $form['row_height'] - 2;
    // Label font-size
    if ($font_height < 8) {
        $font_height = 8;
    }
    $row_left = $label_width + 10;
    // Left offset for the block row
    // Get some html (the html that goes inside the div)
    $html = $function($ip, $row_zoom, $row_height);
    $el_name = $ip . '_row';
    // Add a row label
    $response->addCreate("{$window_name}_substrate", "div", $el_name . '_label');
    $response->addScript(<<<EOL
        var _el = el('{$el_name}_label');
        _el.style.visibility = 'hidden';
        _el.style.position = 'absolute';
        _el.style.textAlign = 'right';
        _el.style.color = '#000000';
        _el.style.fontSize = '{$font_height}px';
        _el.style.top  = '{$row_offset}px';
        _el.style.left = '2px';
        _el.style.width = '{$label_width}px';
        _el.style.overflow = 'visible';
        _el.style.whiteSpace = 'nowrap';
EOL
);
    // Add the row
    $response->addCreate("{$window_name}_substrate", "div", $el_name);
    $response->addScript(<<<EOL
        var _el = el('{$el_name}');
        _el.style.visibility = 'hidden';
        _el.style.position = 'absolute';
        _el.style.top  = '{$row_offset}px';
        _el.style.left = '{$row_left}px';
        _el.style.borderTop    = '1px solid #000000';
        _el.style.borderBottom = '1px solid #000000';
        _el.style.borderLeft   = '1px solid #000000';
        if (browser.isIE)
            _el.style.fontSize = ({$font_height} - 2) + 'px';
EOL
);
    // Fill the label and row
    $response->addAssign($el_name, "innerHTML", $html);
    $response->addAssign($el_name . '_label', "innerHTML", $label);
    // Javascript to make sure the container (row) div is the exact length to hold it's contents in one row
    $response->addScript(<<<EOL
        var nodes = _el.childNodes;
        var width = 0;
        for (var counter=0; counter < nodes.length; counter++)
            if (nodes[counter].nodeType == 1)
                width += parseInt(nodes[counter].offsetWidth);
        if (browser.isIE) width += 1; /* for the left border */
        _el.style.width = width + 'px';
EOL
);
    // Display the label and block
    $response->addScript(<<<EOL
        el('{$el_name}_label').style.visibility = 'visible';
        el('{$el_name}').style.visibility = 'visible';
        /* Tell the browser we've sent it this block so it knows it can re-request it if it needs to */
        _map_requests_['{$el_name}'] = undefined;
EOL
);
    if ($js) {
        $response->addScript($js);
    }
    return $response->getXML();
}
Ejemplo n.º 7
0
function ws_save($window_name, $form = '')
{
    global $include, $conf, $self, $onadb;
    // Check permissions
    if (!(auth('host_modify') or auth('host_add'))) {
        $response = new xajaxResponse();
        $response->addScript("alert('Permission denied!');");
        return $response->getXML();
    }
    // Instantiate the xajaxResponse object
    $response = new xajaxResponse();
    $js = '';
    // Validate input
    if ($form['set_type'] == '' or $form['host'] == '.' and $form['set_ip'] == '') {
        $response->addScript("alert('Please complete all fields to continue!');");
        return $response->getXML();
    }
    // Since we're adding two records (host and an interface)
    // we need to do a little validation here to make sure things
    // have a good chance of working!
    // Validate the "set_host" name is valid
    $form['set_host'] = sanitize_hostname(trim($form['set_host']));
    if (!$form['set_host']) {
        $response->addScript("alert('Invalid hostname!');");
        return $response->getXML();
    }
    // Validate domain is valid
    //     list($status, $rows, $domain) = ona_find_domain($form['set_domain'],0);
    //     if ($status or !$rows) {
    //         $response->addScript("alert('Invalid domain!');");
    //         return($response->getXML());
    //     }
    // Make sure the IP address specified is valid
    if ($form['host'] != '.' and $form['set_ip']) {
        $form['set_ip'] = ip_mangle($form['set_ip'], 'dotted');
        if ($form['set_ip'] == -1) {
            $response->addScript("alert('{$self['error']}');");
            return $response->getXML();
        }
    }
    if ($form['set_addptr'] == '') {
        $form['set_addptr'] = 'N';
    }
    // FIXME: If we're editing, validate the $form['host'] is valid
    // FIXME: If we're editing, validate the $form['interface'] is valid
    // FIXME: Verify that the device "type" ID is valid (not a big risk since they select from a drop-down)
    // If no location is passed, make sure the value is 0
    // if (array_key_exists('set_location', $form)) $form['set_location'] = 0;
    // Decide if we're editing or adding
    $module = 'modify';
    // If we're adding, re-map some the array names to match what the "add" module wants
    if ($form['host'] == '.') {
        $module = 'add';
        if (!auth('host_add')) {
            $response = new xajaxResponse();
            $response->addScript("alert('Permission denied!');");
            return $response->getXML();
        }
        // Device options
        $form['type'] = $form['set_type'];
        unset($form['set_type']);
        $form['location'] = $form['set_location'];
        unset($form['set_location']);
        // Host options
        $form['domain'] = $form['set_domain'];
        $form['host'] = $form['set_host'] . '.' . $form['set_domain'];
        unset($form['set_host']);
        unset($form['set_domain']);
        $form['notes'] = $form['set_notes'];
        unset($form['set_notes']);
        $form['description'] = $form['set_description'];
        unset($form['set_description']);
        $form['view'] = $form['set_view'];
        unset($form['set_view']);
        // Interface options
        $form['ip'] = $form['set_ip'];
        unset($form['set_ip']);
        $form['mac'] = $form['set_mac'];
        unset($form['set_mac']);
        $form['name'] = $form['set_name'];
        unset($form['set_name']);
        $form['addptr'] = $form['set_addptr'];
        unset($form['set_addptr']);
        // If there's no "refresh" javascript, add a command to view the new host
        if (!preg_match('/\\w/', $form['js'])) {
            $form['js'] = "xajax_window_submit('work_space', 'xajax_window_submit(\\'display_host\\', \\'host=>{$form['host']}\\', \\'display\\')');";
        }
    } else {
        $form['set_host'] .= '.' . $form['set_domain'];
    }
    // Do a pre check of the ptr domain so we can prompt the user properly
    if ($module == 'add') {
        $ipflip = ip_mangle($form['ip'], 'flip');
        $octets = explode(".", $ipflip);
        if (count($octets) > 4) {
            $arpa = '.ip6.arpa';
            $octcount = 31;
        } else {
            $arpa = '.in-addr.arpa';
            $octcount = 3;
        }
        list($status, $rows, $ptrdomain) = ona_find_domain($ipflip . $arpa);
        if (!$ptrdomain['id']) {
            printmsg("ERROR => This operation tried to create a PTR record that is the first in this IP address space.  You must first create at least the following DNS domain: {$octets[$octcount]}.in-addr.arpa", 3);
            $self['error'] = "ERROR => This operation tried to create a PTR record that is the first in this IP address space.<br>You must first create at least the following DNS domain: <b>{$octets[$octcount]}.in-addr.arpa</b>.<br>You could also create domains at deeper level reverse zones if desired.<br>We have opened the add domain dialog for you.";
            $response->addScript("alert('{$self['error']}');xajax_window_submit('edit_domain', 'newptrdomainname=>{$octets[$octcount]}{$arpa}', 'editor');");
            return $response->getXML();
        }
    }
    // Run the module to ADD the HOST AND INTERFACE, or MODIFY THE HOST.
    list($status, $output) = run_module('host_' . $module, $form);
    // If the module returned an error code display a popup warning
    if ($status) {
        $js .= "alert('Save failed.\\n" . preg_replace('/[\\s\']+/', ' ', $self['error']) . "');";
    } else {
        // Run the module to MODIFY THE INTERFACE if we need to
        if ($module == 'modify' and $form['set_ip']) {
            list($status, $output) = run_module('interface_' . $module, $form);
        }
        // If the module returned an error code display a popup warning
        if ($status and $module == 'modify' and $form['set_ip']) {
            $js .= "alert('Interface update failed.\\n" . preg_replace('/[\\s\']+/', ' ', $self['error']) . "');";
        } else {
            // if they have checked the keep adding hosts box then dont remove the window
            if (!$form['keepadding']) {
                $js .= "removeElement('{$window_name}');";
            } else {
                $js .= "el('statusinfo_{$window_name}').innerHTML = 'Previously added:<br>{$form['host']} => {$form['ip']}';";
            }
            if ($form['js']) {
                $js .= $form['js'];
            }
        }
    }
    // Insert the new table into the window
    $response->addScript($js);
    return $response->getXML();
}
Ejemplo n.º 8
0
function ws_display($window_name, $form = '')
{
    global $conf, $self, $onadb;
    global $images, $color, $style, $msgtype;
    $html = '';
    $js = '';
    $debug_val = 3;
    // used in the auth() calls to supress logging
    // If the user supplied an array in a string, build the array and store it in $form
    $form = parse_options_string($form);
    // Load the host record
    if ($form['interface_id']) {
        list($status, $rows, $record) = ona_get_interface_record(array('id' => $form['interface_id']));
    }
    $record['ip_addr'] = ip_mangle($record['ip_addr'], 'dotted');
    if ($status or !$rows) {
        array_pop($_SESSION['ona']['work_space']['history']);
        $html .= "<br><center><font color=\"red\"><b>Interface doesn't exist!</b></font></center>";
        $response = new xajaxResponse();
        $response->addAssign("work_space_content", "innerHTML", $html);
        return $response->getXML();
    }
    // Update History Title (and tell the browser to re-draw the history div)
    $history = array_pop($_SESSION['ona']['work_space']['history']);
    $js .= "xajax_window_submit('work_space', ' ', 'rewrite_history');";
    if ($history['title'] == $window_name) {
        $history['title'] = $record['ip_addr'];
        array_push($_SESSION['ona']['work_space']['history'], $history);
    }
    // Create some javascript to refresh the current page
    $refresh = htmlentities(str_replace(array("'", '"'), array("\\'", '\\"'), $history['url']), ENT_QUOTES, $conf['php_charset']);
    $refresh = "xajax_window_submit('work_space', '{$refresh}');";
    // Associated Host info
    list($status, $rows, $host) = ona_get_host_record(array('id' => $record['host_id']), '');
    // Subnet description
    list($status, $rows, $subnet) = ona_get_subnet_record(array('id' => $interface['subnet_id']));
    $record['subnet_name'] = $subnet['name'];
    $record['ip_subnet_mask'] = ip_mangle($subnet['ip_mask'], 'dotted');
    $record['ip_subnet_mask_cidr'] = ip_mangle($subnet['ip_mask'], 'cidr');
    $style['content_box'] = <<<EOL
        margin: 10px 20px;
        padding: 2px 4px;
        background-color: #FFFFFF;
        vertical-align: top;
EOL;
    $style['label_box'] = <<<EOL
        font-weight: bold;
        padding: 2px 4px;
        border: solid 1px {$color['border']};
        background-color: {$color['window_content_bg']};
EOL;
    // Escape data for display in html
    foreach (array_keys($record) as $key) {
        $record[$key] = htmlentities($record[$key], ENT_QUOTES, $conf['php_charset']);
    }
    $html .= <<<EOL

    <!-- FORMATTING TABLE -->
    <div style="{$style['content_box']}">
    <table cellspacing="0" border="0" cellpadding="0"><tr>

        <!-- START OF FIRST COLUMN OF SMALL BOXES -->
        <td nowrap="true" valign="top" style="padding-right: 15px;">

            <!-- HOST INFORMATION -->
            <table width=100% cellspacing="0" border="0" cellpadding="0" style="margin-bottom: 8px;">

                <tr><td colspan="99" nowrap="true" style="{$style['label_box']}">
                    <!-- LABEL -->
                    <form id="form_interface_{$record['id']}"
                        ><input type="hidden" name="interface_id" value="{$record['id']}"
                        ><input type="hidden" name="js" value="{$refresh}"
                    ></form>
EOL;
    if (auth('host_modify', $debug_val)) {
        $html .= <<<EOL
                    <a title="Edit interface. ID: {$record['id']}"
                       class="act"
                       onClick="xajax_window_submit('edit_interface', xajax.getFormValues('form_interface_{$record['id']}'), 'editor');"
                    ><img src="{$images}/silk/page_edit.png" border="0"></a>
EOL;
    }
    if (auth('host_del', $debug_val)) {
        $html .= <<<EOL
                    <a title="Delete interface. ID: {$record['id']}"
                       class="act"
                       onClick="var doit=confirm('Are you sure you want to delete this interface?');
                                if (doit == true)
                                    xajax_window_submit('edit_interface', xajax.getFormValues('form_interface_{$record['id']}'), 'delete');"
                    ><img src="{$images}/silk/delete.png" border="0"></a>
EOL;
    }
    $html .= <<<EOL
                     &nbsp;{$record['ip_addr']}
                </td></tr>

                <tr>
                    <td align="right" nowrap="true"><b>MAC Address</b>&nbsp;</td>
                    <td class="padding" align="left">{$record['mac_addr']}&nbsp;</td>
                </tr>

                <tr>
                    <td align="right" nowrap="true"><b>Name</b>&nbsp;</td>
                    <td class="padding" align="left">{$record['name']}&nbsp;</td>
                </tr>

                <tr>
                    <td align="right" nowrap="true"><b>Description</b>&nbsp;</td>
                    <td class="padding" align="left">{$record['description']}&nbsp;</td>
                </tr>

            </table>
EOL;
    $html .= <<<EOL
        <!-- END OF FIRST COLUMN OF SMALL BOXES -->
        </td>

        <!-- START OF SECOND COLUMN OF SMALL BOXES -->
        <td valign="top" style="padding-right: 15px;">
EOL;
    $html .= <<<EOL
        <!-- END OF SECOND COLUMN OF SMALL BOXES -->
        </td>


        <!-- START OF THIRD COLUMN OF SMALL BOXES -->
        <td valign="top">
EOL;
    $html .= <<<EOL
        </td>
        <!-- END OF THIRD COLUMN OF SMALL BOXES -->
    </tr></table>
    </div>
    <!-- END OF TOP SECTION -->

EOL;
    // record LIST
    $tab = 'records';
    $submit_window = "list_{$tab}";
    $form_id = "{$submit_window}_filter_form";
    $_SESSION['ona'][$form_id]['tab'] = $tab;
    $content_id = "{$window_name}_{$submit_window}";
    $html .= <<<EOL
    <!-- RECORD LIST -->
    <div style="border: 1px solid {$color['border']}; margin: 10px 20px;">

        <!-- Tab & Quick Filter -->
        <table id="{$form_id}_table" cellspacing="0" border="0" cellpadding="0">
            <tr>
                <td id="{$form_id}_{$tab}_tab" class="table-tab-active">
                    Associated DNS {$tab} <span id="{$form_id}_{$tab}_count"></span>
                </td>

                <td id="{$form_id}_quick_filter" class="padding" align="right" width="100%">
                    <form id="{$form_id}" onSubmit="return false;">
                    <input id="{$form_id}_page" name="page" value="1" type="hidden">
                    <input name="content_id" value="{$content_id}" type="hidden">
                    <input name="form_id" value="{$form_id}" type="hidden">
                    <input name="interface_id" value="{$record['id']}" type="hidden">
                    <div id="{$form_id}_filter_overlay"
                         style="position: relative;
                                display: inline;
                                color: #CACACA;
                                cursor: text;"
                         onClick="this.style.display = 'none'; el('{$form_id}_filter').focus();"
                    >Filter</div>
                    <input
                        id="{$form_id}_filter"
                        name="filter"
                        class="filter"
                        type="text"
                        value=""
                        size="10"
                        maxlength="20"
                        alt="Quick Filter"
                        onFocus="el('{$form_id}_filter_overlay').style.display = 'none';"
                        onBlur="if (this.value == '') el('{$form_id}_filter_overlay').style.display = 'inline';"
                        onKeyUp="
                            if (typeof(timer) != 'undefined') clearTimeout(timer);
                            code = 'if ({$form_id}_last_search != el(\\'{$form_id}_filter\\').value) {' +
                                   '    {$form_id}_last_search = el(\\'{$form_id}_filter\\').value;' +
                                   '    document.getElementById(\\'{$form_id}_page\\').value = 1;' +
                                   '    xajax_window_submit(\\'{$submit_window}\\', xajax.getFormValues(\\'{$form_id}\\'), \\'display_list\\');' +
                                   '}';
                            timer = setTimeout(code, 700);"
                    >
                    </form>
                </td>

            </tr>
        </table>

        <div id='{$content_id}'>
            {$conf['loading_icon']}
        </div>
EOL;
    if (auth('record_add', $debug_val)) {
        $html .= <<<EOL

        <!-- ADD DNS RECORD LINK -->
        <div class="act-box" style="padding: 2px 4px; border-top: 1px solid {$color['border']}">
            <form id="form_record_{$record['id']}"
                ><input type="hidden" name="interface_id" value="{$record['id']}"
                ><input type="hidden" name="js" value="{$refresh}"
            ></form>

            <a title="Add record"
               class="act"
               onClick="xajax_window_submit('edit_record', xajax.getFormValues('form_record_{$record['id']}'), 'editor');"
            ><img src="{$images}/silk/page_add.png" border="0"></a>&nbsp;

            <a title="Add record"
               class="act"
               onClick="xajax_window_submit('edit_record', xajax.getFormValues('form_record_{$record['id']}'), 'editor');"
            >Add record</a>&nbsp;
        </div>
EOL;
    }
    $html .= "    </div>";
    $js .= <<<EOL
        /* Setup the quick filter */
        el('{$form_id}_filter_overlay').style.left = (el('{$form_id}_filter_overlay').offsetWidth + 10) + 'px';
        {$form_id}_last_search = '';

        /* Tell the browser to load/display the list */
        xajax_window_submit('{$submit_window}', xajax.getFormValues('{$form_id}'), 'display_list');
EOL;
    // Insert the new html into the window
    // Instantiate the xajaxResponse object
    $response = new xajaxResponse();
    $response->addAssign("work_space_content", "innerHTML", $html);
    if ($js) {
        $response->addScript($js);
    }
    return $response->getXML();
}
Ejemplo n.º 9
0
function ws_display($window_name, $form = '')
{
    global $conf, $self, $onadb, $base;
    global $images, $color, $style, $msgtype;
    $html = '';
    $js = '';
    $debug_val = 3;
    // used in the auth() calls to supress logging
    // If the user supplied an array in a string, build the array and store it in $form
    $form = parse_options_string($form);
    // Load the host record
    if ($form['device_id']) {
        list($status, $rows, $record) = ona_get_device_record(array('id' => $form['device_id']));
    } else {
        if ($form['device']) {
            // FIXME.. no find_device yet
            list($status, $rows, $record) = ona_find_device($form['device']);
        }
    }
    if ($status or !$rows) {
        array_pop($_SESSION['ona']['work_space']['history']);
        $html .= "<br><center><font color=\"red\"><b>Device doesn't exist!</b></font></center>";
        $response = new xajaxResponse();
        $response->addAssign("work_space_content", "innerHTML", $html);
        return $response->getXML();
    }
    // Update History Title (and tell the browser to re-draw the history div)
    $history = array_pop($_SESSION['ona']['work_space']['history']);
    $js .= "xajax_window_submit('work_space', ' ', 'rewrite_history');";
    if ($history['title'] == $window_name) {
        $history['title'] = $record['name'];
        array_push($_SESSION['ona']['work_space']['history'], $history);
    }
    // Create some javascript to refresh the current page
    $refresh = htmlentities(str_replace(array("'", '"'), array("\\'", '\\"'), $history['url']), ENT_QUOTES, $conf['php_charset']);
    $refresh = "xajax_window_submit('work_space', '{$refresh}');";
    // Interface (and find out how many there are)
    list($status, $interfaces, $interface) = ona_get_interface_record(array('host_id' => $record['id']), '');
    $record['ip_address'] = ip_mangle($interface['ip_addr'], 'dotted');
    $interface_style = '';
    if ($interfaces > 1) {
        $interface_style = 'font-weight: bold;';
    }
    // Subnet description
    list($status, $rows, $subnet) = ona_get_subnet_record(array('ID' => $interface['subnet_id']));
    $record['subnet'] = $subnet['name'];
    $record['ip_subnet_mask'] = ip_mangle($subnet['ip_mask'], 'dotted');
    $record['ip_subnet_mask_cidr'] = ip_mangle($subnet['ip_mask'], 'cidr');
    // Device Description
    list($status, $rows, $device_type) = ona_get_device_type_record(array('id' => $record['device_type_id']));
    list($status, $rows, $role) = ona_get_role_record(array('id' => $device_type['role_id']));
    list($status, $rows, $model) = ona_get_model_record(array('id' => $device_type['model_id']));
    list($status, $rows, $manufacturer) = ona_get_manufacturer_record(array('id' => $model['manufacturer_id']));
    $record['devicefull'] = "{$manufacturer['name']}, {$model['name']} ({$role['name']})";
    $record['device'] = str_replace('Unknown', '?', $record['devicefull']);
    // Get location_number from the location_id
    list($status, $rows, $location) = ona_get_location_record(array('id' => $record['location_id']));
    // extra stuff to pass to ws_plugins
    $extravars['refresh'] = $refresh;
    $extravars['window_name'] = $window_name;
    $style['content_box'] = <<<EOL
        margin: 10px 20px;
        padding: 2px 4px;
        background-color: #FFFFFF;
        vertical-align: top;
EOL;
    $style['label_box'] = <<<EOL
        font-weight: bold;
        padding: 2px 4px;
        border: solid 1px {$color['border']};
        background-color: {$color['window_content_bg']};
EOL;
    // Escape data for display in html
    foreach (array_keys($record) as $key) {
        $record[$key] = htmlentities($record[$key], ENT_QUOTES, $conf['php_charset']);
    }
    // force 300px width to Notes field if the length is longer than 50 characters and put Notes at the top of the td
    $notes_width = "";
    $notes_valign = "";
    if (strlen($record['notes']) > 50) {
        $notes_width = ' style="width: 300px" ';
        $notes_valign = ' valign="top" ';
    }
    $html .= <<<EOL

    <!-- FORMATTING TABLE -->
    <div style="{$style['content_box']}">
    <table cellspacing="0" border="0" cellpadding="0"><tr>

        <!-- START OF FIRST COLUMN OF SMALL BOXES -->
        <td nowrap="true" valign="top" style="padding-right: 15px;">

            <form id="form_device_{$record['id']}"
                ><input type="hidden" name="device_id" value="{$record['id']}"
                ><input type="hidden" name="js" value="{$refresh}"
            ></form>

EOL;
    $wspl = workspace_plugin_loader('host_detail', $record, $extravars);
    $html .= $wspl[0];
    $js .= $wspl[1];
    $wspl = workspace_plugin_loader('location_detail', $record, $extravars);
    $html .= $wspl[0];
    $js .= $wspl[1];
    $html .= <<<EOL
        <!-- END OF FIRST COLUMN OF SMALL BOXES -->
        </td>

        <!-- START OF SECOND COLUMN OF SMALL BOXES -->
        <td valign="top" style="padding-right: 15px;">
EOL;
    $html .= <<<EOL
        <!-- END OF SECOND COLUMN OF SMALL BOXES -->
        </td>


        <!-- START OF THIRD COLUMN OF SMALL BOXES -->
        <td valign="top">
EOL;
    // START MESSAGES BOX
    // $tablename is a reference directly to the table that contains the item
    // we are displaying to the user.
    // It is possible that you can have the same ID in multiple tables, currently.
    $tablename = 'devices';
    require_once 'winc/tooltips.inc.php';
    list($lineshtml, $linesjs) = get_message_lines_html("table_id_ref = {$record['id']} AND table_name_ref LIKE '{$tablename}'");
    if ($lineshtml) {
        $html .= <<<EOL
            <!-- MESSAGES LIST -->
            <table width=100% cellspacing="0" border="0" cellpadding="0" style="margin-bottom: 8px;">
                <tr><td colspan="99" nowrap="true" style="{$style['label_box']}">
                    Messages
                </td></tr>
                <tr><td>
EOL;
        $html .= $lineshtml;
        $js .= $linesjs;
        $html .= "</td></tr></table>";
    }
    // END MESSAGES LIST
    $html .= <<<EOL
        </td>
        <!-- END OF THIRD COLUMN OF SMALL BOXES -->
    </tr></table>
    </div>
    <!-- END OF TOP SECTION -->

EOL;
    // RECORD LIST
    $tab = 'hosts';
    $submit_window = "list_{$tab}";
    $form_id = "{$submit_window}_filter_form";
    $_SESSION['ona'][$form_id]['tab'] = $tab;
    $content_id = "{$window_name}_{$submit_window}";
    $html .= <<<EOL
    <!-- INTERFACE LIST -->
    <div style="border: 1px solid {$color['border']}; margin: 10px 20px;">

        <!-- Tab & Quick Filter -->
        <table id="{$form_id}_table" cellspacing="0" border="0" cellpadding="0">
            <tr>
                <td id="{$form_id}_{$tab}_tab" class="table-tab-active">
                    Associated Hosts {$tab} <span id="{$form_id}_{$tab}_count"></span>
                </td>

                <td id="{$form_id}_quick_filter" class="padding" align="right" width="100%">
                    <form id="{$form_id}" onSubmit="return false;">
                    <input id="{$form_id}_page" name="page" value="1" type="hidden">
                    <input name="content_id" value="{$content_id}" type="hidden">
                    <input name="form_id" value="{$form_id}" type="hidden">
                    <input name="device_id" value="{$record['id']}" type="hidden">
                    <div id="{$form_id}_filter_overlay"
                         title="Filter"
                         style="position: relative;
                                display: inline;
                                color: #CACACA;
                                cursor: text;"
                         onClick="this.style.display = 'none'; el('{$form_id}_filter').focus();"
                    >Name</div>
                    <input
                        id="{$form_id}_filter"
                        name="filter"
                        class="filter"
                        type="text"
                        value=""
                        size="10"
                        maxlength="20"
                        alt="Quick Filter"
                        onFocus="el('{$form_id}_filter_overlay').style.display = 'none';"
                        onBlur="if (this.value == '') el('{$form_id}_filter_overlay').style.display = 'inline';"
                        onKeyUp="
                            if (typeof(timer) != 'undefined') clearTimeout(timer);
                            code = 'if ({$form_id}_last_search != el(\\'{$form_id}_filter\\').value) {' +
                                   '    {$form_id}_last_search = el(\\'{$form_id}_filter\\').value;' +
                                   '    document.getElementById(\\'{$form_id}_page\\').value = 1;' +
                                   '    xajax_window_submit(\\'{$submit_window}\\', xajax.getFormValues(\\'{$form_id}\\'), \\'display_list\\');' +
                                   '}';
                            timer = setTimeout(code, 700);"
                    >
                    </form>
                </td>

            </tr>
        </table>

        <div id='{$content_id}'>
            {$conf['loading_icon']}
        </div>
EOL;
    if (auth('host_add', $debug_val)) {
        $html .= <<<EOL

        <!-- ADD RECORD LINK -->
        <div class="act-box" style="padding: 2px 4px; border-top: 1px solid {$color['border']}">
            <form id="form_record_{$record['id']}"
                ><input type="hidden" name="host_id" value="{$record['id']}"
                ><input type="hidden" name="js" value="{$refresh}"
            ></form>

            <a title="Add host"
               class="act"
               onClick="xajax_window_submit('edit_host', xajax.getFormValues('form_record_{$record['id']}'), 'editor');"
            ><img src="{$images}/silk/font_add.png" border="0"></a>&nbsp;

            <a title="Add host"
               class="act"
               onClick="xajax_window_submit('edit_host', xajax.getFormValues('form_record_{$record['id']}'), 'editor');"
            >Add host</a>&nbsp;
        </div>
EOL;
    }
    $html .= "    </div>";
    $js .= <<<EOL
        /* Setup the quick filter */
        el('{$form_id}_filter_overlay').style.left = (el('{$form_id}_filter_overlay').offsetWidth + 10) + 'px';
        {$form_id}_last_search = '';

        /* Tell the browser to load/display the list */
        xajax_window_submit('{$submit_window}', xajax.getFormValues('{$form_id}'), 'display_list');
EOL;
    // Insert the new html into the window
    // Instantiate the xajaxResponse object
    $response = new xajaxResponse();
    $response->addAssign("work_space_content", "innerHTML", $html);
    if ($js) {
        $response->addScript($js);
    }
    return $response->getXML();
}
Ejemplo n.º 10
0
function ws_display_list($window_name, $form = '')
{
    global $conf, $self, $onadb;
    global $images, $color, $style;
    $html = '';
    $js = '';
    $debug_val = 3;
    // used in the auth() calls to supress logging
    // 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 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;
    //
    //       FIND RESULT SET
    //
    // Start building the "where" clause for the sql query to find the subnets to display
    $where = "";
    $and = "";
    // SERVER ID
    if ($form['server_id']) {
        $where .= $and . 'id IN (SELECT subnet_id
                                FROM   dhcp_server_subnets
                                WHERE  host_id = ' . $onadb->qstr($form['server_id']) . '
                                UNION
                                SELECT subnet_id
                                FROM dhcp_pools
                                WHERE dhcp_failover_group_id IN (SELECT id
                                                                FROM dhcp_failover_groups
                                                                WHERE primary_server_id = ' . $onadb->qstr($form['server_id']) . '
                                                                OR secondary_server_id = ' . $onadb->qstr($form['server_id']) . '))';
        $and = " AND ";
    }
    // Do the SQL Query
    $filter = '';
    if ($form['filter']) {
        // Subnet descriptions are always upper case
        $form['filter'] = strtoupper($form['filter']);
        $filter = $and . ' name LIKE ' . $onadb->qstr('%' . $form['filter'] . '%');
    }
    list($status, $rows, $results) = db_get_records($onadb, 'subnets', $where . $filter, 'ip_addr', $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);
    } else {
        if ($rows >= $conf['search_results_per_page']) {
            list($status, $rows, $records) = db_get_records($onadb, 'subnets', $where . $filter, "", 0);
        }
    }
    $count = $rows;
    //
    // *** BUILD HTML LIST ***
    //
    $html .= <<<EOL
    <!-- Subnet Results -->
    <table id="{$form['form_id']}_dhcp_server_list" class="list-box" cellspacing="0" border="0" cellpadding="0">

        <!-- Table Header -->
        <tr>
            <td class="list-header" align="center" style="{$style['borderR']};">Name</td>
            <td class="list-header" align="center" style="{$style['borderR']};">Subnet</td>
            <td class="list-header" align="center" style="{$style['borderR']};">Usage</td>
            <td class="list-header" align="center" style="{$style['borderR']};">Type</td>
            <td class="list-header" align="center">&nbsp;</td>
        </tr>
EOL;
    // Loop and display each record
    foreach ($results as $record) {
        // Get additional info about eash subnet record //
        // 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');
        list($status, $rows, $type) = ona_get_subnet_type_record(array('id' => $record['subnet_type_id']));
        $record['type'] = $type['display_name'];
        // Calculate the percentage of the subnet that's used (total size - allocated hosts - dhcp pool size)
        $usage_html = get_subnet_usage_html($record['id']);
        // Escape data for display in html
        foreach (array_keys($record) as $key) {
            $record[$key] = htmlentities($record[$key], ENT_QUOTES, $conf['php_charset']);
        }
        $primary_object_js = "xajax_window_submit('work_space', 'xajax_window_submit(\\'display_subnet\\', \\'subnet_id=>{$record['id']}\\', \\'display\\')');";
        $html .= <<<EOL
        <tr onMouseOver="this.className='row-highlight'" onMouseOut="this.className='row-normal'">

            <td class="list-row">
                <a title="View subnet. ID: {$record['id']}"
                   class="nav"
                   onClick="{$primary_object_js}"
                >{$record['name']}</a>
            </td>

            <td class="list-row" align="left">
                {$record['ip_addr']} <span title="{$record['ip_mask']}">/{$record['ip_mask_cidr']}</span>&nbsp;
            </td>

            <td class="list-row" align="center" style="vertical-align: middle;">
                {$usage_html}
            </td>

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

            <td class="list-row" align="right">
                <form id="{$form['form_id']}_list_dhcp_server_{$record['id']}"
                    ><input type="hidden" name="subnet_id" value="{$record['id']}"
                    ><input type="hidden" name="server_id" value="{$form['server_id']}"
                    ><input type="hidden" name="js" value="{$refresh}"
                ></form>

                <a title="Display subnet map"
                   class="act"
                   onClick="xajax_window_submit('work_space', 'xajax_window_submit(\\'display_block_map\\', \\'ip_block_start=>{$record['ip_addr']}\\', \\'display\\');');"
                ><img src="{$images}/silk/shape_align_left.png" border="0"></a>&nbsp;
EOL;
        if (auth('subnet_modify', $debug_val)) {
            $html .= <<<EOL

                <a title="Edit subnet"
                   class="act"
                   onClick="xajax_window_submit('edit_subnet', xajax.getFormValues('{$form['form_id']}_list_dhcp_server_{$record['id']}'), 'editor');"
                ><img src="{$images}/silk/page_edit.png" border="0"></a>&nbsp;
EOL;
        }
        // check if the subnet listed is from a failover group or an actual dhcp server subnet assignment
        list($dhcpsubnetstatus, $dhcpsubnetrows, $dhcpserver) = ona_get_dhcp_server_subnet_record(array('subnet_id' => $record['id'], 'host_id' => $form['server_id']));
        if (auth('subnet_del', $debug_val) && $dhcpsubnetrows == 1) {
            $html .= <<<EOL

                <a title="Remove subnet association with server."
                   class="act"
                   onClick="var doit=confirm('Are you sure you want to remove this subnet from this DHCP server?');
                        if (doit == true)
                            xajax_window_submit('edit_dhcp_server', xajax.getFormValues('{$form['form_id']}_list_dhcp_server_{$record['id']}'), 'delete');"
                ><img src="{$images}/silk/page_delete.png" border="0"></a>&nbsp;
EOL;
        } else {
            $html .= <<<EOL
                <span title="You must change the failover group assignment on the pool to remove this entry."><img src="{$images}/silk/comment.png" border="0"></span>&nbsp;
EOL;
        }
        $html .= <<<EOL

            </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']);
    // If there was only 1 result, and we're about to display results in the "Search Results" window, display it.
    if ($count == 1 and $form['content_id'] == 'search_results_list' and $form['filter'] == '') {
        $js .= $primary_object_js;
    }
    // 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();
}
Ejemplo n.º 11
0
function ws_save($window_name, $form = '')
{
    global $include, $conf, $self, $onadb;
    // Check permissions (there is no interface_add, it's merged with host_add)
    if (!(auth('interface_modify') and 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);
    // Instantiate the xajaxResponse object
    $response = new xajaxResponse();
    $js = '';
    // Validate input
    if ($form['set_ip'] == '') {
        $response->addScript("alert('Please complete the IP address field to continue!');");
        return $response->getXML();
    }
    // set_create_a and set_create_ptr should both be set!
    if (!$form['set_addptr']) {
        $form['set_addptr'] = 'N';
    }
    // Decide if we're editing or adding
    $module = 'interface_modify';
    // If we're adding, re-map some the array names to match what the "add" module wants
    if (!$form['interface_id']) {
        $module = 'interface_add';
        $form['ip'] = $form['set_ip'];
        unset($form['set_ip']);
        $form['mac'] = $form['set_mac'];
        unset($form['set_mac']);
        $form['name'] = $form['set_name'];
        unset($form['set_name']);
        $form['description'] = $form['set_description'];
        unset($form['set_description']);
        $form['addptr'] = $form['set_addptr'];
        unset($form['set_addptr']);
        $form['view'] = $form['set_view'];
        unset($form['set_view']);
    } else {
        $form['interface'] = $form['interface_id'];
        unset($form['interface_id']);
    }
    // Do a pre check of the ptr domain so we can prompt the user properly
    if ($module == 'interface_add') {
        $ipflip = ip_mangle($form['ip'], 'flip');
        $octets = explode(".", $ipflip);
        //GD: ipv6 IPs must be reversed in .ip6.arpa
        if (count($octets) > 4) {
            $arpa = '.ip6.arpa';
            $octcount = 31;
        } else {
            $arpa = '.in-addr.arpa';
            $octcount = 3;
        }
        list($status, $rows, $ptrdomain) = ona_find_domain($ipflip . $arpa);
        if (!$ptrdomain['id']) {
            printmsg("ERROR => You must first create at least the following DNS domain: {$octets[$octcount]}{$arpa}", 3);
            $self['error'] = "ERROR => You must first create at least the following DNS domain: {$octets[$octcount]}{$arpa}.  You could also create domains for class B or class C level reverse zones.  Click OK to open add domain dialog";
            $response->addScript("alert('{$self['error']}');xajax_window_submit('edit_domain', 'newptrdomainname=>{$octets[$octcount]}{$arpa}', 'editor');");
            return $response->getXML();
        }
    }
    // Run the module
    list($status, $output) = run_module($module, $form);
    // If the module returned an error code display a popup warning
    if ($status) {
        $js .= "alert('Save failed.\\n" . preg_replace('/[\\s\']+/', ' ', $self['error']) . "');";
    } else {
        // If the module returned an error code display a popup warning
        if ($status and $module == 'modify' and $form['set_ip']) {
            $js .= "alert('Interface update failed.\\n" . preg_replace('/[\\s\']+/', ' ', $self['error']) . "');";
        } else {
            // Update the status to tell them what they just did if they just *added* a subnet and the "keep adding" box is checked.
            // Otherwise just close the edit window.
            if ($form['keepadding'] and $module == 'interface_add') {
                $js .= "el('statusinfo_{$window_name}').innerHTML = 'Previously added: {$form['ip']}';";
            } else {
                $js .= "removeElement('{$window_name}');";
            }
            // If there is "refresh" javascript, send it to the browser to execute
            if ($form['js']) {
                $js .= $form['js'];
            }
        }
    }
    // Insert the new table into the window
    $response->addScript($js);
    return $response->getXML();
}
Ejemplo n.º 12
0
function dhcp_lease_add($options = "")
{
    // The important globals
    global $conf, $self, $mysql;
    // Version - UPDATE on every edit!
    $version = '1.00';
    printmsg("DEBUG => dhcp_lease_add({$options}) called", 3);
    // Parse incoming options string to an array
    $options = parse_options($options);
    // Return the usage summary if we need to
    if ($options['help'] or !($options['raw'] or $options['ip'] and $options['mac'])) {
        // NOTE: Help message lines should not exceed 80 characters for proper display on a console
        $self['error'] = 'ERROR => Insufficient parameters';
        return array(1, <<<EOM

dhcp_lease_add-v{$version}
Adds a dhcp lease entry into the tracking database

  Synopsis: dhcp_lease_add [KEY=VALUE] ...

  Required:
    raw=TEXT               The raw text from the DHCP log

  Notes:
    Adding a lease here does NOT effect the actual functioning
    DHCP server.  This is purely to keep track of lease information
    derived from the DHCP logfile itself.


EOM
);
    }
    $name = 'N/A';
    if ($options['raw']) {
        // break the line down into its parts
        $line = preg_split("/( on | to | via )/", $options['raw']);
        $mac = $line[2];
        $iptext = $line[1];
        $ip = ip_mangle($iptext, 'numeric');
        // if the second field has mac and a name in parens then break it out
        if (strpos($line[2], '(')) {
            list($mac, $name) = split('[()]', $line[2]);
            $name = trim($name);
        }
        // make sure the mac has been trimmed
        $mac = trim($mac);
        $text = "DHCP Lease Add: IP={$ip} IPTEXT={$line[1]} MAC={$mac} NAME={$name}\n";
        printmsg("DEBUG => {$text}", 3);
    }
    if ($options['ip'] and $options['mac']) {
        $ip = ip_mangle($options['ip'], 'numeric');
        // make sure the mac has been trimmed
        $mac = trim($options['mac']);
        if ($options['name']) {
            $name = $options['name'];
        }
        $text = "DHCP Lease Add: IP={$ip} IPTEXT={$line[1]} MAC={$mac} NAME={$name}\n";
        printmsg("DEBUG => {$text}", 3);
    }
    // Check to see if the IP is already in the database
    //    list($status, $rows, $lease) = db_get_record($mysql, "dhcp_leases", array('IP_ADDRESS' => $ip));
    //    if ($rows) {
    //        printmsg("DEBUG => updating existing record", 2);
    //        list($status, $rows)  = db_update_record($mysql, "dhcp_leases", array('IP_ADDRESS' => $ip), array('MAC' => $mac, 'HOSTNAME' => $name));
    //    } else {
    //        printmsg("DEBUG => inserting new record", 2);
    //        list($status, $rows)  = db_insert_record($mysql, "dhcp_leases", array('IP_ADDRESS' => $ip,
    //                                                                              'IP_TEXT' => $iptext,
    //                                                                              'MAC' => $mac,
    //                                                                              'HOSTNAME' => $name)
    //                                               );
    //    }
    // Return the success notice
    return array(0, $text);
}
Ejemplo n.º 13
0
function build_bind_domain($options = "")
{
    // The important globals
    global $conf, $self, $onadb;
    // Version - UPDATE on every edit!
    $version = '1.50';
    printmsg("DEBUG => build_bind_domain({$options}) called", 3);
    // Parse incoming options string to an array
    $options = parse_options($options);
    // Return the usage summary if we need to
    if ($options['help'] or !$options['domain']) {
        // NOTE: Help message lines should not exceed 80 characters for proper display on a console
        $self['error'] = 'ERROR => Insufficient parameters';
        return array(1, <<<EOF

build_bind_domain-v{$version}
Builds a zone file for a dns server from the database

  Synopsis: build_bind_domain [KEY=VALUE] ...

  Required:
    domain=DOMAIN or ID      build zone file for specified domain



EOF
);
    }
    // Get the domain information
    list($status, $rows, $domain) = ona_find_domain($options['domain']);
    printmsg("DEBUG => build_bind_domain() Domain record: {$domain['domain']}", 3);
    if (!$domain['id']) {
        printmsg("DEBUG => Unknown domain record: {$options['domain']}", 3);
        $self['error'] = "ERROR => Unknown domain record: {$options['domain']}";
        return array(2, $self['error'] . "\n");
    }
    // if for some reason the domains default_ttl is not set, use the one from the $conf['dns']['default_ttl']
    if ($domain['default_ttl'] == 0) {
        $domain['default_ttl'] = $conf['dns']['default_ttl'];
    }
    if ($domain['primary_master'] == '') {
        $domain['primary_master'] = 'localhost';
    }
    // loop through records and display them
    $q = "\n    SELECT  *\n    FROM    dns\n    WHERE   domain_id = {$domain['id']}\n    ORDER BY type";
    // exectue the query
    $rs = $onadb->Execute($q);
    if ($rs === false or !$rs->RecordCount()) {
        $self['error'] = 'ERROR => build_zone(): SQL query failed: ' . $onadb->ErrorMsg();
        printmsg($self['error'], 0);
        $exit += 1;
    }
    $rows = $rs->RecordCount();
    // check if this is a ptr domain that has delegation
    if (strpos(str_replace('in-addr.arpa', '', $domain['fqdn']), '-')) {
        $ptrdelegation = true;
    }
    // Start building the named.conf - save it in $text
    $text = "; DNS zone file for {$domain['fqdn']} built on " . date($conf['date_format']) . "\n";
    // print the opening host comment with row count
    $text .= "; TOTAL RECORDS (count={$rows})\n\n";
    // FIXME: MP do more to ensure that dots are at the end as appropriate
    $text .= "\$ORIGIN {$domain['fqdn']}.\n";
    $text .= "\$TTL {$domain['default_ttl']}\n";
    $text .= ";Serial number is current unix timestamp (seconds since UTC)\n\n";
    // NOTE: There are various ways that one could generate the serial.  The bind book suggests YYYYMMDDXX where XX is 1/100th of the day or some counter in the day.
    // I feel this is too limiting.  I prefer the Unix timestamp (seconds since UTC) method.  TinyDNS uses this method as well and it allows for much more granularity.
    // Referr to the following for some discussion on the topic: http://www.lifewithdjbdns.com/#Migration
    // NOTE: for now I am generating the serial each time the zone is built.  I'm ignoring, and may remove, the one stored in the database.
    $serial_number = time();
    // Build the SOA record
    // FIXME: MP do a bit more to ensure that dots are where they should be
    $text .= "@      IN      SOA   {$domain['primary_master']}. {$domain['admin_email']} ({$serial_number} {$domain['refresh']} {$domain['retry']} {$domain['expiry']} {$domain['minimum']})\n\n";
    // Loop through the record set
    while ($dnsrecord = $rs->FetchRow()) {
        // Dont build records that begin in the future
        if (strtotime($dnsrecord['ebegin']) > time()) {
            continue;
        }
        if (strtotime($dnsrecord['ebegin']) < 0) {
            continue;
        }
        // If there are notes, put the comment character in front of it
        if ($dnsrecord['notes']) {
            $dnsrecord['notes'] = '; ' . str_replace("\n", "; ", $dnsrecord['notes']);
        }
        // If the ttl is empty then make it truely empty
        if ($dnsrecord['ttl'] == 0) {
            $dnsrecord['ttl'] = '';
        }
        // Also, if the records ttl is the same as the domains ttl then dont display it, just to keep it "cleaner"
        if (!strcmp($dnsrecord['ttl'], $domain['default_ttl'])) {
            $dnsrecord['ttl'] = '';
        }
        // Dont print a dot unless hostname has a value
        if ($dnsrecord['name']) {
            $dnsrecord['name'] = $dnsrecord['name'] . '.';
        }
        if ($dnsrecord['type'] == 'A') {
            // Find the interface record
            list($status, $rows, $interface) = ona_get_interface_record(array('id' => $dnsrecord['interface_id']));
            if ($status or !$rows) {
                printmsg("ERROR => Unable to find interface record!", 3);
                $self['error'] = "ERROR => Unable to find interface record!";
                return array(5, $self['error'] . "\n");
            }
            $fqdn = $dnsrecord['name'] . $domain['fqdn'];
            $text .= sprintf("%-50s %-8s IN  %-8s %-30s %s\n", $fqdn . '.', $dnsrecord['ttl'], $dnsrecord['type'], $interface['ip_addr_text'], $dnsrecord['notes']);
        }
        if ($dnsrecord['type'] == 'PTR') {
            // Find the interface record
            list($status, $rows, $interface) = ona_get_interface_record(array('id' => $dnsrecord['interface_id']));
            if ($status or !$rows) {
                printmsg("ERROR => Unable to find interface record!", 3);
                $self['error'] = "ERROR => Unable to find interface record!";
                return array(5, $self['error'] . "\n");
            }
            // Get the name info that the cname points to
            list($status, $rows, $ptr) = ona_get_dns_record(array('id' => $dnsrecord['dns_id']), '');
            // If this is a delegation domain, find the subnet cidr
            if ($ptrdelegation) {
                list($status, $rows, $subnet) = ona_get_subnet_record(array('id' => $interface['subnet_id']));
                $ip_last = ip_mangle($interface['ip_addr'], 'flip');
                $ip_last_digit = substr($ip_last, 0, strpos($ip_last, '.'));
                $ip_remainder = substr($ip_last, strpos($ip_last, '.')) . '.in-addr.arpa.';
                $text .= sprintf("%-50s %-8s IN  %-8s %s.%-30s %s\n", $ip_last_digit . '-' . ip_mangle($subnet['ip_mask'], 'cidr') . $ip_remainder, $dnsrecord['ttl'], $dnsrecord['type'], $ptr['name'], $ptr['domain_fqdn'] . '.', $dnsrecord['notes']);
            } else {
                $text .= sprintf("%-50s %-8s IN  %-8s %s.%-30s %s\n", ip_mangle($interface['ip_addr'], 'flip') . '.in-addr.arpa.', $dnsrecord['ttl'], $dnsrecord['type'], $ptr['name'], $ptr['domain_fqdn'] . '.', $dnsrecord['notes']);
            }
        }
        if ($dnsrecord['type'] == 'CNAME') {
            // Find the interface record
            list($status, $rows, $interface) = ona_get_interface_record(array('id' => $dnsrecord['interface_id']));
            if ($status or !$rows) {
                printmsg("ERROR => Unable to find interface record!", 3);
                $self['error'] = "ERROR => Unable to find interface record!";
                return array(5, $self['error'] . "\n");
            }
            // Get the name info that the cname points to
            list($status, $rows, $cname) = ona_get_dns_record(array('id' => $dnsrecord['dns_id']), '');
            $fqdn = $dnsrecord['name'] . $domain['fqdn'];
            $text .= sprintf("%-50s %-8s IN  %-8s %s.%-30s %s\n", $fqdn . '.', $dnsrecord['ttl'], $dnsrecord['type'], $cname['name'], $cname['domain_fqdn'] . '.', $dnsrecord['notes']);
        }
        if ($dnsrecord['type'] == 'NS') {
            // Find the interface record
            list($status, $rows, $interface) = ona_get_interface_record(array('id' => $dnsrecord['interface_id']));
            if ($status or !$rows) {
                printmsg("ERROR => Unable to find interface record!", 3);
                $self['error'] = "ERROR => Unable to find interface record!";
                return array(5, $self['error'] . "\n");
            }
            // Get the name info that the cname points to
            list($status, $rows, $ns) = ona_get_dns_record(array('id' => $dnsrecord['dns_id']), '');
            $text .= sprintf("%-50s %-8s IN  %-8s %s.%-30s %s\n", $domain['fqdn'] . '.', $dnsrecord['ttl'], $dnsrecord['type'], $ns['name'], $ns['domain_fqdn'] . '.', $dnsrecord['notes']);
        }
        if ($dnsrecord['type'] == 'MX') {
            // Find the interface record
            list($status, $rows, $interface) = ona_get_interface_record(array('id' => $dnsrecord['interface_id']));
            if ($status or !$rows) {
                printmsg("ERROR => Unable to find interface record!", 3);
                $self['error'] = "ERROR => Unable to find interface record!";
                return array(5, $self['error'] . "\n");
            }
            // Get the name info that the cname points to
            list($status, $rows, $mx) = ona_get_dns_record(array('id' => $dnsrecord['dns_id']), '');
            if ($dnsrecord['name']) {
                $name = $dnsrecord['name'] . $domain['fqdn'];
            } else {
                $name = $domain['name'];
            }
            $text .= sprintf("%-50s %-8s IN  %s %-5s %s.%-30s %s\n", $name . '.', $dnsrecord['ttl'], $dnsrecord['type'], $dnsrecord['mx_preference'], $mx['name'], $mx['domain_fqdn'] . '.', $dnsrecord['notes']);
        }
        if ($dnsrecord['type'] == 'SRV') {
            // Find the interface record
            list($status, $rows, $interface) = ona_get_interface_record(array('id' => $dnsrecord['interface_id']));
            if ($status or !$rows) {
                printmsg("ERROR => Unable to find interface record!", 3);
                $self['error'] = "ERROR => Unable to find interface record!";
                return array(5, $self['error'] . "\n");
            }
            // Get the name info that the cname points to
            list($status, $rows, $srv) = ona_get_dns_record(array('id' => $dnsrecord['dns_id']), '');
            if ($dnsrecord['name']) {
                $name = $dnsrecord['name'] . $domain['fqdn'];
            } else {
                $name = $domain['name'];
            }
            $text .= sprintf("%-50s %-8s IN  %s %s %s %-8s %-30s %s\n", $name . '.', $dnsrecord['ttl'], $dnsrecord['type'], $dnsrecord['srv_pri'], $dnsrecord['srv_weight'], $dnsrecord['srv_port'], $srv['fqdn'] . '.', $dnsrecord['notes']);
        }
        if ($dnsrecord['type'] == 'TXT') {
            $fqdn = $dnsrecord['name'] . $domain['fqdn'];
            $text .= sprintf("%-50s %-8s IN  %-8s %-30s %s\n", $fqdn . '.', $dnsrecord['ttl'], $dnsrecord['type'], '"' . $dnsrecord['txt'] . '"', $dnsrecord['notes']);
        }
    }
    ////////////// Footer stuff //////////////////
    // MP: FIXME: For now I"m not using this.. bind errors out if the file doesnt exist.  need a deterministic way to do this.
    // Allow for a local footer include.. I expect this to rarely be used
    //    $text .= "\n; Allow for a local footer include.. I expect this to rarely be used.\n";
    //    $text .= "\$INCLUDE named-{$domain['fqdn']}-footer\n";
    // Return the zone file
    return array(0, $text);
}
Ejemplo n.º 14
0
function subnet_nextip($options = "")
{
    global $conf, $self, $onadb;
    // Version - UPDATE on every edit!
    $version = '1.00';
    printmsg('DEBUG => subnet_del(' . $options . ') called', 3);
    // Parse incoming options string to an array
    $options = parse_options($options);
    // Sanitize options[commit] (default is no)
    $options['commit'] = sanitize_YN($options['commit'], 'N');
    // Return the usage summary if we need to
    if ($options['help'] or !$options['subnet']) {
        // NOTE: Help message lines should not exceed 80 characters for proper display on a console
        $self['error'] = 'ERROR => Insufficient parameters';
        return array(1, <<<EOM

subnet_del-v{$version}
Return the next available IP address on a subnet.

  Synopsis: subnet_nextip [KEY=VALUE] ...

  Required:
    subnet=IP or ID               select subnet by search string

  Optional:
    offset=NUMBER                 Starting offset to find next available IP
    output=[dotted|numeric]       Return the number as a dotted or numeric value
                                  DEFAULT: numeric


EOM
);
    }
    // Find the subnet record we're deleting
    list($status, $rows, $subnet) = ona_find_subnet($options['subnet']);
    if ($status or !$rows) {
        $self['error'] = "ERROR => Subnet not found";
        return array(2, $self['error'] . "\n");
    }
    // Create a few variables that will be handy later
    $num_ips = 0xffffffff - $subnet['ip_mask'];
    $last_ip = $subnet['ip_addr'] + $num_ips - 1;
    // check that offset is a number
    if (isset($options['offset']) and !is_numeric($options['offset'])) {
        $self['error'] = "ERROR => Offset must be a numeric number";
        return array(3, $self['error'] . "\n");
    } else {
        $offsetmsg = " beyond offset {$options['offset']}";
    }
    // make sure the offset does not extend beyond the specified subnet
    if ($options['offset'] >= $num_ips - 1) {
        $self['error'] = "ERROR => Offset extends beyond specified subnet boundary";
        return array(4, $self['error'] . "\n");
    }
    if (!isset($options['output'])) {
        $options['output'] = '1';
    } else {
        if ($options['output'] != 'dotted' && $options['output'] != 'numeric') {
            $self['error'] = "ERROR => Output option must be 'dotted' or 'numeric'";
            return array(5, $self['error'] . "\n");
        }
    }
    // Find the first number based on our subnet and offset
    $ip = $subnet['ip_addr'] + $options['offset'];
    // Make sure we skip past the subnet IP to the first usable IP
    if ($ip == $subnet['ip_addr']) {
        $ip++;
    }
    // Start looping through our IP addresses until we find an available one
    while ($ip <= $last_ip) {
        // Find out if the ip is used in an interface
        list($status, $rows, $interfaces) = db_get_records($onadb, 'interfaces', array('ip_addr' => $ip));
        // If we find a free address.. check that it is not in a DHCP pool
        if (!$rows) {
            list($status, $rows, $pool) = db_get_record($onadb, 'dhcp_pools', "{$ip} >= ip_addr_start AND {$ip} <= ip_addr_end");
            if ($rows) {
                $ip = $pool['ip_addr_end'];
            } else {
                break;
            }
        }
        $ip++;
        // increment by one and check again
    }
    // If we checked all the IPs, make sure we are not on the broadcast IP of the subnet
    if ($ip == $last_ip + 1) {
        $self['error'] = "ERROR => No available IP addresses found on subnet{$offsetmsg}";
        return array(5, $self['error'] . "\n");
    }
    // return the IP
    return array(0, ip_mangle($ip, $options['output']) . "\n");
}
Ejemplo n.º 15
0
function rpt_output_text($form)
{
    global $onadb, $style, $images;
    // Provide a usage message here
    $usagemsg = <<<EOL
Report: nmap_scan
  Processes the XML output of an nmap scan and compares it to data in the database.

  Required:
    subnet=ID|IP|STRING   Subnet ID, IP, or name of existing subnet with a scan
      OR
    file=PATH             Local XML file will be sent to server for processing
      OR
    all                   Process ALL XML files on the server
      OR
    update_response       Update the last response field for all UP IPs to time in scan

  Output Formats:
    html
    text
    csv

NOTE: When running update_response, any entry that was updated will have a ~ indication
      at the beginning of the line.
      DNS names with a * preceeding them indicate there are more than one name available
      for this entry and it could have a more common name associated with it.

EOL;
    // Provide a usage message
    if ($form['rpt_usage']) {
        return array(0, $usagemsg);
    }
    if (!$form['totalhosts'] and !$form['all']) {
        return array(1, "\nERROR => No hosts found, check that the XML file is not empty, or that your subnet exists in the database.\n{$usagemsg}");
    }
    if (!$form['all']) {
        $text .= "NMAP scan of {$form['totalhosts']} hosts done on {$form['runtime']}. {$form['scansource']}\n\n";
    } else {
        $text .= "Displaying records for ALL nmap scans in the system.  It also only shows issues, not entries that are OK.\n\n";
    }
    //$text .= sprintf("%-50s %-8s %-8s\n",'NMAP SCAN','DATABASE','Actions');
    if ($form['csv_output']) {
        $text .= sprintf("%s,%s,%s,%s,%s,%s,%s,%s\n", 'STAT', 'NET IP', 'NET NAME', 'NET MAC', 'DB IP', 'DB NAME', 'DB MAC', 'ACTION');
    } else {
        $text .= sprintf("%-6s %-15s %-25s %-12s %-15s %-25s %-12s %s\n", 'STAT', 'NET IP', 'NET NAME', 'NET MAC', 'DB IP', 'DB NAME', 'DB MAC', 'ACTION');
    }
    // netip    netname     netmac      dbip    dbname  dbmac
    $poolhostcount = 0;
    // find out the broadcast IP for this subnet
    // TODO: fix this for ipv6 stuff!
    $num_hosts = 0xffffffff - ip_mangle($form['netcidr'], 'numeric');
    $broadcastip = ip_mangle(ip_mangle($form['netip'], 'numeric') + $num_hosts, 'dotted');
    foreach ((array) $form['ip'] as $record) {
        // scans with only one row in them may show up wrong, skip them
        if (!$record['netstatus'] and !$record['netip']) {
            continue;
        }
        $action = '';
        $upresp = ' ';
        // Check devices that are down
        if ($record['netstatus'] == "down") {
            // Skip over hosts that are not in network or database
            if ($record['dbip'] == "NOT FOUND") {
                continue;
            }
            // If it is only in the database then they should validate the ip or remove from database
            if ($record['netip'] == $record['dbip'] or $record['netdnsname'] != $record['dbdnsname']) {
                $action = "Ping to verify then delete as desired";
            }
        }
        // check devices that are up
        if ($record['netstatus'] == "up") {
            // If this is the subnet address or broadcast then skip it.  Sometimes nmap shows them as up
            if ($record['netip'] == $form['netip']) {
                continue;
            }
            if ($record['netip'] == $broadcastip) {
                continue;
            }
            // update the database last response field.
            if ($form['update_response'] and $record['dbip'] != "NOT FOUND") {
                //if (isset($options['dcm_output'])) { $text .=  "dcm.pl -r interface_modify interface={$record['ip']} set_last_response='{$runtime}'\n"; }
                list($updatestatus, $output) = run_module('interface_modify', array('interface' => $record['dbip'], 'set_last_response' => $form['runtime']));
                if ($updatestatus) {
                    $self['error'] = "ERROR => Failed to update response time for '{$record['dbip']}': " . $output;
                    printmsg($self['error'], 1);
                }
                $upresp = '~';
            }
            // Break out the host and domain parts of the name if we can
            if ($record['netdnsname']) {
                list($status, $rows, $domain) = ona_find_domain($record['netdnsname'], 0);
                // Now find what the host part of $search is
                $hostname = str_replace(".{$domain['fqdn']}", '', $record['netdnsname']);
            }
            // If we dont find it in the database
            if ($record['dbip'] == "NOT FOUND") {
                $action = "Add as host or Add as interface, check proper pool range";
            }
            // If it is in the database and network
            if ($record['netip'] == $record['dbip']) {
                $action = 'OK';
                // But if the names are not the same then action is partial
                if ($record['netdnsname'] != $record['dbdnsname']) {
                    $action = 'Update DNS';
                }
                if (strstr($record['dbdnsname'], '(')) {
                    $action = 'Update DNS PTR';
                }
            }
            // if the database name is empty, then provide a generic "name"
            if (!$record['dbdnsname'] and $record['dbip'] != 'NOT FOUND' and $record['netdnsname']) {
                $record['dbdnsname'] = 'NONE SET';
            }
            // if the names are different, offer an edit button for the DB
            if ($record['netdnsname'] and strtolower($record['netdnsname']) != $record['dbdnsname']) {
                // not a lot of testing here to make sure it will find the right name.
                list($status, $rows, $rptdnsrecord) = ona_find_dns_record($record['dbdnsname']);
            }
            // If the device is in a dhcp pool range, then count it and identify it.
            if ($record['inpool'] == 1) {
                $poolhostcount++;
                $record['dbip'] = 'DHCP Pooled';
                $action = 'DHCP Pooled device';
            }
        }
        // If we have more than 2 dns records, display info about them
        if ($record['dbdnsrows'] > 2) {
            $record['dbdnsname'] = '*' . $record['dbdnsname'];
        }
        /*
        TODO:
        * more testing of mac address stuff
        * display info about last response time.. add option to update last response form file.. flag if db has newer times than the scan
        */
        if ($form['csv_output']) {
            $txt = sprintf("%s,%s,%s,%s,%s,%s,%s,\"%s\"\n", $upresp . $record['netstatus'], $record['netip'], $record['netdnsname'], $record['netmacaddr'], $record['dbip'], $record['dbdnsname'] . ' ' . $record['dbdnsptrname'], $record['dbmacaddr'], $action);
        } else {
            $txt = sprintf("%-6s %-15s %-25s %-12s %-15s %-25s %-12s %s\n", $upresp . $record['netstatus'], $record['netip'], $record['netdnsname'], $record['netmacaddr'], $record['dbip'], $record['dbdnsname'] . ' ' . $record['dbdnsptrname'], $record['dbmacaddr'], $action);
        }
        // if we are in all mode, print only errors.. otherwise, print it all
        if ($form['all'] and $action == 'OK') {
            $txt = '';
        }
        // add the new line to the html output variable
        $text .= $txt;
    }
    if (!$form['all']) {
        $hostpoolinfo = "Hosts in DHCP pool range: {$poolhostcount}\n";
    }
    $text .= "\n{$hostpoolinfo}END OF REPORT";
    return array(0, $text);
}
Ejemplo n.º 16
0
function ws_display($window_name, $form = '')
{
    global $conf, $self, $onadb, $base;
    global $images, $color, $style;
    $html = '';
    $js = '';
    $debug_val = 3;
    // used in the auth() calls to supress logging
    // If the user supplied an array in a string, build the array and store it in $form
    $form = parse_options_string($form);
    // Load the host record
    if ($form['host_id']) {
        list($status, $rows, $record) = ona_get_host_record(array('id' => $form['host_id']));
    } else {
        if ($form['host']) {
            list($status, $rows, $record) = ona_find_host($form['host']);
        }
    }
    if ($status or !$rows) {
        array_pop($_SESSION['ona']['work_space']['history']);
        $html .= "<br><center><font color=\"red\"><b>Host doesn't exist!</b></font></center>";
        $response = new xajaxResponse();
        $response->addAssign("work_space_content", "innerHTML", $html);
        return $response->getXML();
    }
    // Update History Title (and tell the browser to re-draw the history div)
    $history = array_pop($_SESSION['ona']['work_space']['history']);
    $js .= "xajax_window_submit('work_space', ' ', 'rewrite_history');";
    if ($history['title'] == $window_name) {
        $history['title'] = $record['name'];
        array_push($_SESSION['ona']['work_space']['history'], $history);
    }
    // Create some javascript to refresh the current page
    $refresh = htmlentities(str_replace(array("'", '"'), array("\\'", '\\"'), $history['url']), ENT_QUOTES, $conf['php_charset']);
    $refresh = "xajax_window_submit('work_space', '{$refresh}');";
    // FIXME: umm.. put this somewhere else
    if (!$record['name']) {
        $record['name'] = "NONE SET";
    }
    // Interface (and find out how many there are)
    list($status, $interfaces, $interface) = ona_get_interface_record(array('host_id' => $record['id']), '');
    $record['ip_address'] = ip_mangle($interface['ip_addr'], 'dotted');
    $interface_style = '';
    if ($interfaces > 1) {
        $interface_style = 'font-weight: bold;';
    }
    // Subnet description
    list($status, $rows, $subnet) = ona_get_subnet_record(array('id' => $interface['subnet_id']));
    $record['subnet'] = $subnet['name'];
    $record['subnet_id'] = $subnet['id'];
    $record['ip_subnet_mask'] = ip_mangle($subnet['ip_mask'], 'dotted');
    $record['ip_subnet_mask_cidr'] = ip_mangle($subnet['ip_mask'], 'cidr');
    // Device Description
    list($status, $rows, $device) = ona_get_device_record(array('id' => $record['device_id']));
    $record['device_type_id'] = $device['device_type_id'];
    list($status, $rows, $device_type) = ona_get_device_type_record(array('id' => $device['device_type_id']));
    list($status, $rows, $role) = ona_get_role_record(array('id' => $device_type['role_id']));
    list($status, $rows, $model) = ona_get_model_record(array('id' => $device_type['model_id']));
    list($status, $rows, $manufacturer) = ona_get_manufacturer_record(array('id' => $model['manufacturer_id']));
    $record['devicefull'] = "{$manufacturer['name']}, {$model['name']} ({$role['name']})";
    $record['device'] = str_replace('Unknown', '?', $record['devicefull']);
    $record['location_id'] = $device['location_id'];
    // Device serial number and/or asset tag
    $record['serial_number'] = $device['serial_number'];
    $record['asset_tag'] = $device['asset_tag'];
    // Get location_number from the location_id
    list($status, $rows, $location) = ona_get_location_record(array('id' => $record['location_id']));
    // extra stuff to pass to ws_plugins
    $extravars['refresh'] = $refresh;
    $extravars['window_name'] = $window_name;
    // Escape data for display in html
    foreach (array_keys($record) as $key) {
        $record[$key] = htmlentities($record[$key], ENT_QUOTES, $conf['php_charset']);
    }
    // Create a div for workspace plugins to live
    $html .= "<div id='wsplugins' style='margin: 10px;'>";
    // Start displaying all the ws plugins
    $wspl = workspace_plugin_loader('host_detail', $record, $extravars);
    $html .= $wspl[0];
    $js .= $wspl[1];
    $wsmenu[] = $wspl[2];
    $wspl = workspace_plugin_loader('host_services', $record);
    $html .= $wspl[0];
    $js .= $wspl[1];
    $wsmenu[] = $wspl[2];
    $wspl = workspace_plugin_loader('custom_attributes', $record, $extravars);
    $html .= $wspl[0];
    $js .= $wspl[1];
    $wsmenu[] = $wspl[2];
    $wspl = workspace_plugin_loader('dhcp_entries', $record, $extravars);
    $html .= $wspl[0];
    $js .= $wspl[1];
    $wsmenu[] = $wspl[2];
    $wspl = workspace_plugin_loader('config_archives', $record);
    $html .= $wspl[0];
    $js .= $wspl[1];
    $wsmenu[] = $wspl[2];
    // Display the host_action workspace_plugin
    $wspl = workspace_plugin_loader('host_actions', $record);
    $html .= $wspl[0];
    $js .= $wspl[1];
    $wsmenu[] = $wspl[2];
    // Display messages
    $wspl = workspace_plugin_loader('messages', $record, $extravars);
    $html .= $wspl[0];
    $js .= $wspl[1];
    $wsmenu[] = $wspl[2];
    $wspl = workspace_plugin_loader('reports', $record, $extravars);
    $html .= $wspl[0];
    $js .= $wspl[1];
    $wsmenu[] = $wspl[2];
    // Get all the plugin based worspace items
    $wspl_list = plugin_list('wspl_item');
    // Load all the dynamic plugins
    foreach ($wspl_list as $p) {
        $wspl = workspace_plugin_loader($p['path'], $record, $extravars);
        $html .= $wspl[0];
        $js .= $wspl[1];
        $wsmenu[] = $wspl[2];
    }
    // Gather our menuitems and build the HTML
    $wsmenuhtml = build_workspace_menu($wsmenu);
    $html .= <<<EOL

    </div>
    <br style="clear:both;">

    <form id="form_host_{$record['id']}"
        ><input type="hidden" name="host_id" value="{$record['id']}"
        ><input type="hidden" name="js" value="{$refresh}"
    ></form>

    <div id='wsmenu' style='display:none;'>{$wsmenuhtml}</div>

EOL;
    // RECORD LIST
    $tab = 'records';
    $submit_window = "list_{$tab}";
    $form_id = "{$submit_window}_filter_form";
    $_SESSION['ona'][$form_id]['tab'] = $tab;
    $content_id = "{$window_name}_{$submit_window}";
    $html .= <<<EOL
    <!-- INTERFACE LIST -->
    <div style="border: 1px solid {$color['border']}; margin: 10px 20px;">

        <!-- Tab & Quick Filter -->
        <table id="{$form_id}_table" cellspacing="0" border="0" cellpadding="0">
            <tr>
                <td id="{$form_id}_{$tab}_tab" class="table-tab-active">
                    Associated DNS {$tab} <span id="{$form_id}_{$tab}_count"></span>
                </td>

                <td id="{$form_id}_quick_filter" class="padding" align="right" width="100%">
                    <form id="{$form_id}" onSubmit="return false;">
                    <input id="{$form_id}_page" name="page" value="1" type="hidden">
                    <input name="content_id" value="{$content_id}" type="hidden">
                    <input name="form_id" value="{$form_id}" type="hidden">
                    <input name="host_id" value="{$record['id']}" type="hidden">
                    <div id="{$form_id}_filter_overlay"
                         title="Filter"
                         style="position: relative;
                                display: inline;
                                color: #CACACA;
                                cursor: text;"
                         onClick="this.style.display = 'none'; el('{$form_id}_filter').focus();"
                    >Name</div>
                    <input
                        id="{$form_id}_filter"
                        name="filter"
                        class="filter"
                        type="text"
                        value=""
                        size="10"
                        maxlength="20"
                        alt="Quick Filter"
                        onFocus="el('{$form_id}_filter_overlay').style.display = 'none';"
                        onBlur="if (this.value == '') el('{$form_id}_filter_overlay').style.display = 'inline';"
                        onKeyUp="
                            if (typeof(timer) != 'undefined') clearTimeout(timer);
                            code = 'if ({$form_id}_last_search != el(\\'{$form_id}_filter\\').value) {' +
                                   '    {$form_id}_last_search = el(\\'{$form_id}_filter\\').value;' +
                                   '    document.getElementById(\\'{$form_id}_page\\').value = 1;' +
                                   '    xajax_window_submit(\\'{$submit_window}\\', xajax.getFormValues(\\'{$form_id}\\'), \\'display_list\\');' +
                                   '}';
                            timer = setTimeout(code, 700);"
                    >
                    </form>
                </td>

            </tr>
        </table>

        <div id='{$content_id}'>
            {$conf['loading_icon']}
        </div>
EOL;
    if (auth('host_add', $debug_val)) {
        $html .= <<<EOL

        <!-- ADD RECORD LINK -->
        <div class="act-box" style="padding: 2px 4px; border-top: 1px solid {$color['border']}">
            <form id="form_record_{$record['id']}"
                ><input type="hidden" name="host_id" value="{$record['id']}"
                ><input type="hidden" name="js" value="{$refresh}"
            ></form>

            <a title="Add DNS record"
               class="act"
               onClick="xajax_window_submit('edit_record', xajax.getFormValues('form_record_{$record['id']}'), 'editor');"
            ><img src="{$images}/silk/font_add.png" border="0"></a>&nbsp;

            <a title="Add DNS record"
               class="act"
               onClick="xajax_window_submit('edit_record', xajax.getFormValues('form_record_{$record['id']}'), 'editor');"
            >Add DNS record</a>&nbsp;
        </div>
EOL;
    }
    $html .= "    </div>";
    $js .= <<<EOL
        /* Setup the quick filter */
        el('{$form_id}_filter_overlay').style.left = (el('{$form_id}_filter_overlay').offsetWidth + 10) + 'px';
        {$form_id}_last_search = '';

        /* Tell the browser to load/display the list */
        xajax_window_submit('{$submit_window}', xajax.getFormValues('{$form_id}'), 'display_list');
EOL;
    // INTERFACE LIST
    $tab = 'interfaces';
    $submit_window = "list_{$tab}";
    $form_id = "{$submit_window}_filter_form";
    $_SESSION['ona'][$form_id]['tab'] = $tab;
    $content_id = "{$window_name}_{$submit_window}";
    $html .= <<<EOL
    <!-- INTERFACE LIST -->
    <div style="border: 1px solid {$color['border']}; margin: 10px 20px;">

        <!-- Tab & Quick Filter -->
        <table id="{$form_id}_table" cellspacing="0" border="0" cellpadding="0">
            <tr>
                <td id="{$form_id}_{$tab}_tab" class="table-tab-active">
                    Associated {$tab} <span id="{$form_id}_{$tab}_count"></span>
                </td>

                <td id="{$form_id}_quick_filter" class="padding" align="right" width="100%">
                    <form id="{$form_id}" onSubmit="return false;">
                    <input id="{$form_id}_page" name="page" value="1" type="hidden">
                    <input name="content_id" value="{$content_id}" type="hidden">
                    <input name="form_id" value="{$form_id}" type="hidden">
                    <input name="host_id" value="{$record['id']}" type="hidden">
                    <div id="{$form_id}_filter_overlay"
                         title="Filter"
                         style="position: relative;
                                display: inline;
                                color: #CACACA;
                                cursor: text;"
                         onClick="this.style.display = 'none'; el('{$form_id}_filter').focus();"
                    >Full IP</div>
                    <input
                        id="{$form_id}_filter"
                        name="filter"
                        class="filter"
                        type="text"
                        value=""
                        size="10"
                        maxlength="20"
                        alt="Quick Filter"
                        onFocus="el('{$form_id}_filter_overlay').style.display = 'none';"
                        onBlur="if (this.value == '') el('{$form_id}_filter_overlay').style.display = 'inline';"
                        onKeyUp="
                            if (typeof(timer) != 'undefined') clearTimeout(timer);
                            code = 'if ({$form_id}_last_search != el(\\'{$form_id}_filter\\').value) {' +
                                   '    {$form_id}_last_search = el(\\'{$form_id}_filter\\').value;' +
                                   '    document.getElementById(\\'{$form_id}_page\\').value = 1;' +
                                   '    xajax_window_submit(\\'{$submit_window}\\', xajax.getFormValues(\\'{$form_id}\\'), \\'display_list\\');' +
                                   '}';
                            timer = setTimeout(code, 700);"
                    >
                    </form>
                </td>

            </tr>
        </table>

        <div id='{$content_id}'>
            {$conf['loading_icon']}
        </div>
EOL;
    if (auth('host_add', $debug_val)) {
        $html .= <<<EOL

        <!-- ADD INTERFACE LINK -->
        <div class="act-box" style="padding: 2px 4px; border-top: 1px solid {$color['border']}">
            <form id="form_interface_{$record['id']}"
                ><input type="hidden" name="host_id" value="{$record['id']}"
                ><input type="hidden" name="js" value="{$refresh}"
            ></form>

            <a title="Add interface"
               class="act"
               onClick="xajax_window_submit('edit_interface', xajax.getFormValues('form_interface_{$record['id']}'), 'editor');"
            ><img src="{$images}/silk/page_add.png" border="0"></a>&nbsp;

            <a title="Add interface"
               class="act"
               onClick="xajax_window_submit('edit_interface', xajax.getFormValues('form_interface_{$record['id']}'), 'editor');"
            >Add interface</a>&nbsp;
        </div>
EOL;
    }
    $html .= "    </div>";
    $js .= <<<EOL
        /* Setup the quick filter */
        el('{$form_id}_filter_overlay').style.left = (el('{$form_id}_filter_overlay').offsetWidth + 10) + 'px';
        {$form_id}_last_search = '';



        /* Tell the browser to load/display the list */
        xajax_window_submit('{$submit_window}', xajax.getFormValues('{$form_id}'), 'display_list');
EOL;
    // Insert the new html into the window
    // Instantiate the xajaxResponse object
    $response = new xajaxResponse();
    $response->addAssign("work_space_content", "innerHTML", $html);
    if ($js) {
        $response->addScript($js);
    }
    return $response->getXML();
}
Ejemplo n.º 17
0
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 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 blocks to display
    $where = "";
    $and = "";
    // DISPLAY ALL BLOCKS
    if ($form['all_flag']) {
        $where .= $and . "id > 0";
        $and = " AND ";
    }
    // BLOCK ID
    if ($form['id']) {
        $where .= $and . "id = " . $onadb->qstr($form['id']);
        $and = " AND ";
    }
    // BLOCK , assume a block descripton
    if ($form['blockname']) {
        $where .= $and . "name LIKE " . $onadb->qstr('%' . strtoupper($form['blockname']) . '%');
        $and = " AND ";
    }
    // display a nice message when we dont find all the records
    if ($where == '' and $form['content_id'] == 'search_results_list') {
        $js .= "el('search_results_msg').innerHTML = 'Unable to find blocks matching your query, showing all records';";
    }
    // Wild card .. if $while is still empty, add a 'ID > 0' to it so you see everything.
    if ($where == '') {
        $where = 'id > 0';
    }
    // Do the SQL Query
    $filter = '';
    if ($form['filter']) {
        $filter = ' AND name LIKE ' . $onadb->qstr('%' . $form['filter'] . '%');
    }
    list($status, $rows, $results) = db_get_records($onadb, 'blocks', $where . $filter, "ip_addr_start ASC", $conf['search_results_per_page'], $offset);
    // If we got less than search_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);
    } else {
        if ($rows >= $conf['search_results_per_page']) {
            list($status, $rows, $records) = db_get_records($onadb, 'blocks', $where . $filter, "", 0);
        }
    }
    $count = $rows;
    $html .= <<<EOL
        <!-- Block List -->
        <table id="{$form['form_id']}_block_list" class="list-box" cellspacing="0" border="0" cellpadding="0">

            <!-- Table Header -->
            <tr>
                <td class="list-header" align="center" style="{$style['borderR']};">Block Name</td>
                <td class="list-header" align="center" style="{$style['borderR']};">Starting IP</td>
                <td class="list-header" align="center" style="{$style['borderR']};">Ending IP</td>
                <td class="list-header" align="center">&nbsp;</td>
            </tr>
EOL;
    // Loop and display each record
    foreach ($results as $record) {
        // Grab some info from the associated block record
        list($status, $rows, $block) = ona_get_block_record(array('id' => $record['id']));
        $num_hosts = 0xffffffff - $block['ip_addr_end'];
        $block['ip_block_end'] = $block['ip_addr'] + $num_hosts;
        $record['name'] = $block['name'];
        // Convert IP and Netmask to a presentable format
        $record['ip_addr_start'] = ip_mangle($record['ip_addr_start'], 'dotted');
        $record['ip_addr_end'] = ip_mangle($block['ip_addr_end'], 'dotted');
        // Escape data for display in html
        foreach (array_keys($record) as $key) {
            $record[$key] = htmlentities($record[$key], ENT_QUOTES, $conf['php_charset']);
        }
        $primary_object_js = "xajax_window_submit('work_space', 'xajax_window_submit(\\'display_block\\', \\'block_id=>{$record['id']}\\', \\'display\\')');";
        $html .= <<<EOL
            <tr onMouseOver="this.className='row-highlight'" onMouseOut="this.className='row-normal'">

                <td class="list-row" align="left">
                    <a title="View block. ID: {$record['id']}"
                       class="nav"
                       onClick="{$primary_object_js}"
                    >{$record['name']}</a>
                </td>

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

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

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

                    <a title="Edit block. ID: {$record['id']}"
                       class="act"
                       onClick="xajax_window_submit('edit_block', xajax.getFormValues('{$form['form_id']}_list_block_{$record['id']}'), 'editor');"
                    ><img src="{$images}/silk/brick_edit.png" border="0"></a>&nbsp;
EOL;
        }
        $html .= <<<EOL
                    <a title="Display subnet map"
                       class="act"
                       onClick="xajax_window_submit('work_space', 'xajax_window_submit(\\'display_block_map\\', \\'ip_block_start=>{$record['ip_addr_start']},ip_block_end=>{$record['ip_addr_end']},id=>{$record['id']}\\', \\'display\\');');"
                    ><img src="{$images}/silk/shape_align_left.png" border="0"></a>&nbsp;
EOL;
        if (auth('advanced')) {
            $html .= <<<EOL

                    <a title="Delete block"
                       class="act"
                       onClick="var doit=confirm('Are you sure you want to delete this block?');
                                if (doit == true)
                                    xajax_window_submit('edit_block', xajax.getFormValues('{$form['form_id']}_list_block_{$record['id']}'), 'delete');"
                    ><img src="{$images}/silk/delete.png" border="0"></a>
EOL;
        }
        $html .= <<<EOL
                    &nbsp;
                </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']);
    // If there was only 1 result, and we're about to display results in the "Search Results" window, display it.
    if ($count == 1 and $form['content_id'] == 'search_results_list' and $form['filter'] == '') {
        $js .= $primary_object_js;
    }
    // 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();
}
Ejemplo n.º 18
0
function host_del($options = "")
{
    global $conf, $self, $onadb;
    printmsg("DEBUG => host_del({$options}) called", 3);
    // Version - UPDATE on every edit!
    $version = '1.19';
    // Parse incoming options string to an array
    $options = parse_options($options);
    // Sanitize options[commit] (default is no)
    $options['commit'] = sanitize_YN($options['commit'], 'N');
    // Return the usage summary if we need to
    if ($options['help'] or !$options['host']) {
        // NOTE: Help message lines should not exceed 80 characters for proper display on a console
        $self['error'] = 'ERROR => Insufficient parameters';
        return array(1, <<<EOM

host_del-v{$version}
Deletes a host, and all related records from the database

  Synopsis: host_del [KEY=VALUE] ...

  Required:
    host=NAME[.DOMAIN] or ID      Hostname or ID of the host to delete

  Optional:
    commit=[yes|no]               Commit db transaction (no)

  Notes:
    * A host won't be deleted if it has config text records
    * A host won't be deleted if it's configured as a dns or dhcp server


EOM
);
    }
    // Find the host (and domain) record from $options['host']
    list($status, $rows, $host) = ona_find_host($options['host']);
    printmsg("DEBUG => host_del() Host: {$host['fqdn']} ({$host['id']})", 3);
    if (!$host['id']) {
        printmsg("DEBUG => Unknown host: {$host['fqdn']}", 3);
        $self['error'] = "ERROR => Unknown host: {$host['fqdn']}";
        return array(2, $self['error'] . "\n");
    }
    // Check permissions
    if (!auth('host_del') or !authlvl($host['LVL'])) {
        $self['error'] = "Permission denied!";
        printmsg($self['error'], 0);
        return array(10, $self['error'] . "\n");
    }
    // If "commit" is yes, delete the host
    if ($options['commit'] == 'Y') {
        $text = "";
        $add_to_error = "";
        $add_to_status = 0;
        // SUMMARY:
        //   Don't allow a delete if it is performing server duties
        //   Don't allow a delete if config text entries exist
        //   Delete Interfaces
        //   Delete interface cluster entries
        //   Delete dns records
        //   Delete custom attributes
        //   Delete DHCP entries
        //   Delete device record if it is the last host associated with it.
        //
        // IDEA: If it's the last host in a domain (maybe do the same for or a networks & vlans in the interface delete)
        //       It could just print a notice or something.
        // Check that it is the host is not performing server duties
        // FIXME: MP mostly fixed..needs testing
        $serverrow = 0;
        // check ALL the places server_id is used and remove the entry from server_b if it is not used
        list($status, $rows, $srecord) = db_get_record($onadb, 'dhcp_server_subnets', array('host_id' => $host['id']));
        if ($rows) {
            $serverrow++;
        }
        list($status, $rows, $srecord) = db_get_record($onadb, 'dhcp_failover_groups', array('primary_server_id' => $host['id']));
        if ($rows) {
            $serverrow++;
        }
        list($status, $rows, $srecord) = db_get_record($onadb, 'dhcp_failover_groups', array('secondary_server_id' => $host['id']));
        if ($rows) {
            $serverrow++;
        }
        if ($serverrow > 0) {
            printmsg("DEBUG => Host ({$host['fqdn']}) cannot be deleted, it is performing duties as a DHCP server!", 3);
            $self['error'] = "ERROR => Host ({$host['fqdn']}) cannot be deleted, it is performing duties as a DHCP server!";
            return array(5, $self['error'] . "\n");
        }
        // Check if host is a dns server
        $serverrow = 0;
        list($status, $rows, $srecord) = db_get_record($onadb, 'dns_server_domains', array('host_id' => $host['id']));
        if ($rows) {
            $serverrow++;
        }
        if ($serverrow > 0) {
            printmsg("DEBUG => Host ({$host['fqdn']}) cannot be deleted, it is performing duties as a DNS server!", 3);
            $self['error'] = "ERROR => Host ({$host['fqdn']}) cannot be deleted, it is performing duties as a DNS server!";
            return array(5, $self['error'] . "\n");
        }
        // Display an error if it has any entries in configurations
        list($status, $rows, $server) = db_get_record($onadb, 'configurations', array('host_id' => $host['id']));
        if ($rows) {
            printmsg("DEBUG => Host ({$host['fqdn']}) cannot be deleted, it has config archives!", 3);
            $self['error'] = "ERROR => Host ({$host['fqdn']}) cannot be deleted, it has config archives!";
            return array(5, $self['error'] . "\n");
        }
        // Delete interface(s)
        // get list for logging
        $clustcount = 0;
        $dnscount = 0;
        list($status, $rows, $interfaces) = db_get_records($onadb, 'interfaces', array('host_id' => $host['id']));
        // Cant delete if one of the interfaces is primary for a cluster
        foreach ($interfaces as $int) {
            list($status, $rows, $records) = db_get_records($onadb, 'interface_clusters', array('interface_id' => $int['id']));
            $clustcount = $clustcount + $rows;
        }
        if ($clustcount) {
            $self['error'] = "ERROR => host_del() An interface on this host is primary for some interface shares, delete the share or move the interface first.";
            printmsg($self['error'], 0);
            return array(5, $self['error'] . "\n");
        }
        // do the interface_cluster delete.  This just removes this host from the cluster, not the whole cluster itself
        // It will error out as well if this interface is the primary in the cluster
        list($status, $rows) = db_delete_records($onadb, 'interface_clusters', array('host_id' => $host['id']));
        if ($status) {
            $self['error'] = "ERROR => host_del() interface_cluster delete SQL Query failed: {$self['error']}";
            printmsg($self['error'], 0);
            return array(5, $self['error'] . "\n");
        }
        // log deletions
        printmsg("INFO => {$rows} Shared interface(s) DELETED from {$host['fqdn']}", 0);
        $add_to_error .= "INFO => {$rows} Shared interface(s) DELETED from {$host['fqdn']}\n";
        // Delete each DNS record associated with this hosts interfaces.
        //         foreach ($interfaces as $int) {
        //             // Loop through each dns record associated with this interface.
        //             list($status, $rows, $records) = db_get_records($onadb, 'dns', array('interface_id' => $int['id']));
        //             if ($rows) {
        //                 foreach($records as $record) {
        //                     // Run the module
        //                     list($status, $output) = run_module('dns_record_del', array('name' => $record['id'], 'type' => $record['type'], 'commit' => 'Y', 'delete_by_module' => 'Y'));
        //                     $add_to_error .= $output;
        //                     $add_to_status = $add_to_status + $status;
        //                 }
        //             }
        //         }
        // Delete messages
        // get list for logging
        list($status, $rows, $records) = db_get_records($onadb, 'messages', array('table_name_ref' => 'hosts', 'table_id_ref' => $host['id']));
        // do the delete
        list($status, $rows) = db_delete_records($onadb, 'messages', array('table_name_ref' => 'hosts', 'table_id_ref' => $host['id']));
        if ($status) {
            $self['error'] = "ERROR => host_del() message delete SQL Query failed: {$self['error']}";
            printmsg($self['error'], 0);
            return array(5, $self['error'] . "\n");
        }
        // log deletions
        printmsg("INFO => {$rows} Message(s) DELETED from {$host['fqdn']}", 0);
        $add_to_error .= "INFO => {$rows} Message(s) DELETED from {$host['fqdn']}\n";
        // Delete the interfaces.. this should delete dns names and other things associated with interfaces..
        foreach ($interfaces as $record) {
            // Run the module
            list($status, $output) = run_module('interface_del', array('interface' => $record['id'], 'commit' => 'on', 'delete_by_module' => 'Y'));
            $add_to_error .= $output;
            $add_to_status = $add_to_status + $status;
        }
        // Delete device record
        // Count how many hosts use this same device
        list($status, $rows, $records) = db_get_records($onadb, 'hosts', array('device_id' => $host['device_id']));
        // if device count is just 1 do the delete
        if ($rows == 1) {
            list($status, $rows) = db_delete_records($onadb, 'devices', array('id' => $host['device_id']));
            if ($status) {
                $self['error'] = "ERROR => host_del() device delete SQL Query failed: {$self['error']}";
                printmsg($self['error'], 0);
                return array(5, $add_to_error . $self['error'] . "\n");
            }
            // log deletions
            printmsg("INFO => Device record DELETED: [{$record['id']}] no remaining hosts using this device", 0);
        } else {
            printmsg("INFO => Device record NOT DELETED: [{$record['id']}] there are other hosts using this device.", 1);
        }
        // Delete tag entries
        list($status, $rows, $records) = db_get_records($onadb, 'tags', array('type' => 'host', 'reference' => $host['id']));
        $log = array();
        $i = 0;
        foreach ($records as $record) {
            $log[$i] = "INFO => Tag DELETED: {$record['name']} from {$host['fqdn']}";
            $i++;
        }
        //do the delete
        list($status, $rows) = db_delete_records($onadb, 'tags', array('type' => 'host', 'reference' => $host['id']));
        if ($status) {
            $self['error'] = "ERROR => host_del() Tag delete SQL Query failed: {$self['error']}";
            printmsg($self['error'], 0);
            return array(5, $add_to_error . $self['error'] . "\n");
        }
        //log deletions
        foreach ($log as $log_msg) {
            printmsg($log_msg, 0);
            $add_to_error .= $log_msg . "\n";
        }
        // Delete custom attribute entries
        // get list for logging
        list($status, $rows, $records) = db_get_records($onadb, 'custom_attributes', array('table_name_ref' => 'hosts', 'table_id_ref' => $host['id']));
        $log = array();
        $i = 0;
        foreach ($records as $record) {
            list($status, $rows, $ca) = ona_get_custom_attribute_record(array('id' => $record['id']));
            $log[$i] = "INFO => Custom Attribute DELETED: {$ca['name']} ({$ca['value']}) from {$host['fqdn']}";
            $i++;
        }
        //do the delete
        list($status, $rows) = db_delete_records($onadb, 'custom_attributes', array('table_name_ref' => 'hosts', 'table_id_ref' => $host['id']));
        if ($status) {
            $self['error'] = "ERROR => host_del() Custom attribute delete SQL Query failed: {$self['error']}";
            printmsg($self['error'], 0);
            return array(5, $add_to_error . $self['error'] . "\n");
        }
        //log deletions
        foreach ($log as $log_msg) {
            printmsg($log_msg, 0);
            $add_to_error .= $log_msg . "\n";
        }
        // Delete DHCP options
        // get list for logging
        list($status, $rows, $records) = db_get_records($onadb, 'dhcp_option_entries', array('host_id' => $host['id']));
        $log = array();
        $i = 0;
        foreach ($records as $record) {
            list($status, $rows, $dhcp) = ona_get_dhcp_option_entry_record(array('id' => $record['id']));
            $log[$i] = "INFO => DHCP entry DELETED: {$dhcp['display_name']}={$dhcp['value']} from {$host['fqdn']}";
            $i++;
        }
        // do the delete
        list($status, $rows) = db_delete_records($onadb, 'dhcp_option_entries', array('host_id' => $host['id']));
        if ($status) {
            $self['error'] = "ERROR => host_del() DHCP option entry delete SQL Query failed: {$self['error']}";
            printmsg($self['error'], 0);
            return array(5, $add_to_error . $self['error'] . "\n");
        }
        // log deletions
        foreach ($log as $log_msg) {
            printmsg($log_msg, 0);
            $add_to_error .= $log_msg . "\n";
        }
        // Delete the host
        list($status, $rows) = db_delete_records($onadb, 'hosts', array('id' => $host['id']));
        if ($status) {
            $self['error'] = "ERROR => host_del() host delete SQL Query failed: {$self['error']}";
            printmsg($self['error'], 0);
            return array(5, $add_to_error . $self['error'] . "\n");
        }
        // Return the success notice
        if ($add_to_status == 0) {
            $self['error'] = "INFO => Host DELETED: {$host['fqdn']}";
        }
        printmsg($self['error'], 0);
        return array($add_to_status, $add_to_error . $self['error'] . "\n");
    }
    //
    // We are just displaying records that would have been deleted
    //
    // SUMMARY:
    //   Display a warning if it is a server
    //   Display a warning if it has config text entries
    //   Display Interfaces
    //   Display dns records
    //   Display custom attributes
    //   Display DHCP entries
    // Otherwise just display the host record for the host we would have deleted
    $text = "Record(s) NOT DELETED (see \"commit\" option)\n" . "Displaying record(s) that would have been deleted:\n";
    // Display a warning if host is performing server duties
    list($status, $rows, $srecord) = db_get_record($onadb, 'dhcp_server_subnets', array('host_id' => $host['id']));
    if ($rows) {
        $text .= "\nWARNING!  This host is a DHCP server for {$rows} subnet(s)\n";
    }
    list($status, $rows, $srecord) = db_get_record($onadb, 'dns_server_domains', array('host_id' => $host['id']));
    if ($rows) {
        $text .= "\nWARNING!  This host is a DNS server for one or more domains!\n";
    }
    list($status, $rows, $srecord) = db_get_record($onadb, 'dhcp_failover_groups', array('primary_server_id' => $host['id']));
    if ($rows) {
        $text .= "\nWARNING!  This host is a server that is primary in a DHCP failover group\n";
    }
    list($status, $rows, $srecord) = db_get_record($onadb, 'dhcp_failover_groups', array('secondary_server_id' => $host['id']));
    if ($rows) {
        $text .= "\nWARNING!  This host is a server that is secondary in a DHCP failover group\n";
    }
    // Display a warning if it has any configurations
    list($status, $rows, $server) = db_get_record($onadb, 'configurations', array('host_id' => $host['id']));
    if ($rows) {
        $text .= "\nWARNING!  Host can not be deleted, it has config archives!\n";
    }
    if ($rows) {
        $text .= "\nWARNING!  Host will NOT be deleted, due to previous warnings!\n";
    }
    // Display the Host's complete record
    list($status, $tmp) = host_display("host={$host['id']}&verbose=N");
    $text .= "\n" . $tmp;
    // Display count of messages
    list($status, $rows, $records) = db_get_records($onadb, 'messages', array('table_name_ref' => 'hosts', 'table_id_ref' => $host['id']));
    if ($rows) {
        $text .= "\nASSOCIATED MESSAGE RECORDS ({$rows}):\n";
    }
    // Display associated interface(s)
    list($status, $int_rows, $interfaces) = db_get_records($onadb, 'interfaces', array('host_id' => $host['id']));
    // show the dns records associated
    foreach ($interfaces as $record) {
        list($status, $rows, $dnsrec) = db_get_records($onadb, 'dns', array('interface_id' => $record['id']));
        if ($rows) {
            $text .= "\nASSOCIATED DNS RECORDS ({$rows}) ON INTERFACE (" . ip_mangle($record['ip_addr'], 'dotted') . "):\n";
            foreach ($dnsrec as $rec) {
                // show AAAA or A type as needed
                if ($record['ip_addr'] > 4294967295 and $rec['type'] == 'A') {
                    $rec['type'] = 'AAAA';
                }
                $text .= "  TYPE: [ID:{$rec['id']}] {$rec['type']}, {$rec['name']} -> " . ip_mangle($record['ip_addr'], 'dotted') . "\n";
            }
        }
    }
    if ($int_rows) {
        $text .= "\nASSOCIATED INTERFACE RECORDS ({$int_rows}):\n";
    }
    foreach ($interfaces as $record) {
        $text .= "  [ID:{$record['id']}] " . ip_mangle($record['ip_addr'], 'dotted') . "\n";
    }
    // Display associated interface_clusters(s)
    list($status, $clust_rows, $interfaceclusters) = db_get_records($onadb, 'interface_clusters', array('host_id' => $host['id']));
    if ($clust_rows) {
        $text .= "\nASSOCIATED SHARED INTERFACE RECORDS ({$clust_rows}):\n";
    }
    foreach ($interfaceclusters as $record) {
        list($status, $rows, $int) = ona_get_interface_record(array('id' => $record['interface_id']));
        $text .= "  [ID:{$int['id']}] {$int['ip_addr_text']}\n";
    }
    // Display associated tags
    list($status, $rows, $records) = db_get_records($onadb, 'tags', array('type' => 'host', 'reference' => $host['id']));
    if ($rows) {
        $text .= "\nASSOCIATED TAG RECORDS ({$rows}):\n";
    }
    foreach ($records as $record) {
        $text .= "  {$record['name']}\n";
    }
    // Display associated custom attributes
    list($status, $rows, $records) = db_get_records($onadb, 'custom_attributes', array('table_name_ref' => 'hosts', 'table_id_ref' => $host['id']));
    if ($rows) {
        $text .= "\nASSOCIATED CUSTOM ATTRIBUTE RECORDS ({$rows}):\n";
    }
    foreach ($records as $record) {
        list($status, $rows, $ca) = ona_get_custom_attribute_record(array('id' => $record['id']));
        $text .= "  {$ca['name']} => {$ca['value']}\n";
    }
    // Display associated DHCP entries
    list($status, $rows, $records) = db_get_records($onadb, 'dhcp_option_entries', array('host_id' => $host['id']));
    if ($rows) {
        $text .= "\nASSOCIATED DHCP OPTION RECORDS ({$rows}):\n";
    }
    foreach ($records as $record) {
        list($status, $rows, $dhcp) = ona_get_dhcp_option_entry_record(array('id' => $record['id']));
        $text .= "  {$dhcp['display_name']} => {$dhcp['value']}\n";
    }
    return array(7, $text);
}
Ejemplo n.º 19
0
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, transform it into an array
    $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 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'];
    }
    printmsg("DEBUG => Displaying records list page: {$page}", 1);
    // 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;
    //
    // *** ADVANCED RECORD SEARCH ***
    //       FIND RESULT SET
    //
    // Start building the "where" clause for the sql query to find the records to display
    $where = "";
    $and = "";
    $orderby = "";
    // enable or disable wildcards
    $wildcard = '%';
    if ($form['nowildcard']) {
        $wildcard = '';
    }
    // RECORD ID
    if ($form['record_id']) {
        $where .= $and . "id = " . $onadb->qstr($form['record_id']);
        $and = " AND ";
    }
    // DNS VIEW ID
    if ($form['dns_view']) {
        if (is_string($form['dns_view'])) {
            list($status, $rows, $dnsview) = ona_get_dns_view_record(array('name' => $form['dns_view']));
        }
        if (is_numeric($form['dns_view'])) {
            list($status, $rows, $dnsview) = ona_get_dns_view_record(array('id' => $form['dns_view']));
        }
        $where .= $and . "dns_view_id = " . $onadb->qstr($dnsview['id']);
        $and = " AND ";
    }
    // INTERFACE ID
    if ($form['interface_id']) {
        $where .= $and . "interface_id = " . $onadb->qstr($form['interface_id']);
        $and = " AND ";
    }
    // DNS RECORD note
    if ($form['notes']) {
        $where .= $and . "notes LIKE " . $onadb->qstr($wildcard . $form['notes'] . $wildcard);
        $and = " AND ";
    }
    // DNS RECORD TYPE
    if ($form['dnstype']) {
        $where .= $and . "type = " . $onadb->qstr($form['dnstype']);
        $and = " AND ";
    }
    // HOSTNAME
    if ($form['hostname']) {
        $where .= $and . "id IN (SELECT id " . "  FROM dns " . "  WHERE name LIKE " . $onadb->qstr($wildcard . $form['hostname'] . $wildcard) . " )";
        $and = " AND ";
    }
    // DOMAIN
    if ($form['domain']) {
        // FIXME: MP test if this clause works correctly?  Not sure that anything even uses this?
        list($status, $rows, $tmpdomain) = ona_find_domain($form['domain']);
        $where .= $and . "domain_id = " . $onadb->qstr($tmpdomain['id']);
        $orderby .= "name, domain_id";
        $and = " AND ";
    }
    // DOMAIN ID
    if ($form['domain_id']) {
        //$where .= $and . "primary_dns_id IN ( SELECT id " .
        //                                    "  FROM dns " .
        //                                    "  WHERE domain_id = " . $onadb->qstr($form['domain_id']) . " )  ";
        $where .= $and . "domain_id = " . $onadb->qstr($form['domain_id']);
        $orderby .= "name, domain_id";
        $and = " AND ";
    }
    // IP ADDRESS
    $ip = $ip_end = '';
    if ($form['ip']) {
        // Build $ip and $ip_end from $form['ip'] and $form['ip_thru']
        $ip = ip_complete($form['ip'], '0');
        if ($form['ip_thru']) {
            $ip_end = ip_complete($form['ip_thru'], '255');
        } else {
            $ip_end = ip_complete($form['ip'], '255');
        }
        // Find out if $ip and $ip_end are valid
        $ip = ip_mangle($ip, 'numeric');
        $ip_end = ip_mangle($ip_end, 'numeric');
        if ($ip != -1 and $ip_end != -1) {
            // We do a sub-select to find interface id's between the specified ranges
            $where .= $and . "interface_id IN ( SELECT id " . "        FROM interfaces " . "        WHERE ip_addr >= " . $onadb->qstr($ip) . " AND ip_addr <= " . $onadb->qstr($ip_end) . " )";
            $and = " AND ";
        }
    }
    // display a nice message when we dont find all the records
    if ($where == '' and $form['content_id'] == 'search_results_list') {
        $js .= "el('search_results_msg').innerHTML = 'Unable to find DNS records matching your query, showing all records';";
    }
    // Wild card .. if $while is still empty, add a 'ID > 0' to it so you see everything.
    if ($where == '') {
        $where = 'id > 0';
    }
    // If we dont have DNS views turned on, limit data to just the default view.
    // Even if there is data associated with other views, ignore it
    if (!$conf['dns_views']) {
        $where .= ' AND dns_view_id = 0';
    }
    // Do the SQL Query
    $filter = '';
    if ($form['filter']) {
        // Host names should always be lower case
        $form['filter'] = strtolower($form['filter']);
        $filter = ' AND name LIKE ' . $onadb->qstr('%' . $form['filter'] . '%');
    }
    // If we get a specific host to look for we must do the following
    // 1. get (A) records that match any interface_id associated with the host
    // 2. get CNAMES that point to dns records that are using an interface_id associated with the host
    if ($form['host_id']) {
        // If we dont have DNS views turned on, limit data to just the default view.
        // Even if there is data associated with other views, ignore it
        // MP: something strange with this, it should only limit to default view.. sometimes it does not???
        if (!$conf['dns_views']) {
            $hwhere .= 'dns_view_id = 0 AND ';
        }
        // Get the host record so we know what the primary interface is
        list($status, $rows, $host) = ona_get_host_record(array('id' => $form['host_id']), '');
        list($status, $rows, $results) = db_get_records($onadb, 'dns', $hwhere . 'interface_id in (select id from interfaces where host_id = ' . $onadb->qstr($form['host_id']) . ') OR interface_id in (select interface_id from interface_clusters where host_id = ' . $onadb->qstr($form['host_id']) . ')', "type", $conf['search_results_per_page'], $offset);
        // If we got less than search_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);
        } else {
            if ($rows >= $conf['search_results_per_page']) {
                list($status, $rows, $records) = db_get_records($onadb, 'dns', $hwhere . 'interface_id in (select id from interfaces where host_id = ' . $onadb->qstr($form['host_id']) . ') OR interface_id in (select interface_id from interface_clusters where host_id = ' . $onadb->qstr($form['host_id']) . ')' . $filter, "", 0);
            }
        }
    } else {
        list($status, $rows, $results) = db_get_records($onadb, 'dns', $where . $filter, $orderby, $conf['search_results_per_page'], $offset);
        // If we got less than search_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);
        } else {
            if ($rows >= $conf['search_results_per_page']) {
                list($status, $rows, $records) = db_get_records($onadb, 'dns', $where . $filter, "", 0);
            }
        }
    }
    $count = $rows;
    //
    // *** BUILD HTML LIST ***
    //
    $html .= <<<EOL
        <!-- dns record Results -->
        <table id="{$form['form_id']}_dns_record_list" class="list-box" cellspacing="0" border="0" cellpadding="0">

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

                <td colspan="2" class="list-header" align="center" style="{$style['borderR']};">Name</td>
                <td class="list-header" align="center" style="{$style['borderR']};">Time to Live</td>
                <td class="list-header" align="center" style="{$style['borderR']};">Type</td>
                <td class="list-header" align="center" style="{$style['borderR']};">Data</td>
                <td class="list-header" align="center" style="{$style['borderR']};">Effective</td>
EOL;
    if ($conf['dns_views']) {
        $html .= "<td class=\"list-header\" align=\"center\" style=\"{$style['borderR']};\">DNS View</td>";
    }
    $html .= <<<EOL
                <td class="list-header" align="center" style="{$style['borderR']};">Notes</td>
                <td class="list-header" align="center">&nbsp;</td>
            </tr>
EOL;
    // Loop and display each record
    //  $last_record = array('name' => $results[0]['name'], 'domain_id' => $results[0]['domain_id']);
    //  $last_record_count = 0;
    for ($i = 1; $i <= count($results); $i++) {
        $record = $results[$i];
        // Get additional info about each host record
        $record = $results[$i - 1];
        // if the interface is the primary_dns_id for the host then mark it
        $primary_record = '&nbsp;';
        if ($host['primary_dns_id'] == $record['id']) {
            $primary_record = '<img title="Primary DNS record" src="' . $images . '/silk/font_go.png" border="0">';
        }
        // Check for interface records (and find out how many there are)
        list($status, $interfaces, $interface) = ona_get_interface_record(array('id' => $record['interface_id']), '');
        if ($interfaces) {
            // Get the host record so we know what the primary interface is
            //list($status, $rows, $inthost) = ona_get_host_record(array('id' => $interface['host_id']), '');
            // Make the type correct based on the IP passed in
            if (strlen($interface['ip_addr']) > 11 and $record['type'] == 'A') {
                $record['type'] = 'AAAA';
            }
            $record['ip_addr'] = ip_mangle($interface['ip_addr'], 'dotted');
            // Subnet description
            list($status, $rows, $subnet) = ona_get_subnet_record(array('id' => $interface['subnet_id']));
            $record['subnet'] = $subnet['name'];
            $record['ip_mask'] = ip_mangle($subnet['ip_mask'], 'dotted');
            $record['ip_mask_cidr'] = ip_mangle($subnet['ip_mask'], 'cidr');
            // Create string to be embedded in HTML for display
            $data = <<<EOL
                        {$record['ip_addr']}&nbsp;

EOL;
        } else {
            // Get other DNS records which name this record as parent
            list($status, $rows, $dns_other) = ona_get_host_record(array('id' => $record['dns_id']));
            // Create string to be embedded in HTML for display
            if ($rows) {
                $data = <<<EOL
                <a title="View host. ID: {$dns_other['id']}"
                    class="nav"
                    onClick="xajax_window_submit('work_space', 'xajax_window_submit(\\'display_host\\', \\'host_id=>{$dns_other['id']}\\', \\'display\\')');"
                >{$dns_other['name']}</a
                >.<a title="View domain. ID: {$dns_other['domain_id']}"
                        class="domain"
                        onClick="xajax_window_submit('work_space', 'xajax_window_submit(\\'display_domain\\', \\'domain_id=>{$dns_other['domain_id']}\\', \\'display\\')');"
                >{$dns_other['domain_fqdn']}</a>&nbsp;
EOL;
            }
        }
        $record['notes_short'] = truncate($record['notes'], 30);
        // Add a dot to the end of record name for display purposes
        $record['name'] = $record['name'] . '.';
        // Process PTR record
        if ($record['type'] == 'PTR') {
            list($status, $rows, $pointsto) = ona_get_dns_record(array('id' => $record['dns_id']), '');
            list($status, $rows, $pdomain) = ona_get_domain_record(array('id' => $record['domain_id']), '');
            // Flip the IP address
            $record['name'] = ip_mangle($record['ip_addr'], 'flip');
            $record['domain'] = $pdomain['name'];
            if ($pdomain['parent_id']) {
                list($status, $rows, $parent) = ona_get_domain_record(array('id' => $pdomain['parent_id']));
                $parent['name'] = ona_build_domain_name($parent['id']);
                $record['domain'] = $pdomain['name'] . '.' . $parent['name'];
                unset($parent['name']);
            }
            // strip down the IP to just the "host" part as it relates to the domain its in
            if (strstr($record['domain'], 'in-addr.arpa')) {
                $domain_part = preg_replace("/.in-addr.arpa\$/", '', $record['domain']);
            } else {
                $domain_part = preg_replace("/.ip6.arpa\$/", '', $record['domain']);
            }
            $record['name'] = preg_replace("/{$domain_part}\$/", '', $record['name']);
            $data = <<<EOL
                    <a title="Edit DNS A record"
                       class="act"
                       onClick="xajax_window_submit('edit_record', 'dns_record_id=>{$record['dns_id']}', 'editor');"
                    >{$pointsto['name']}</a>.<a title="View domain. ID: {$pointsto['domain_id']}"
                         class="domain"
                         onClick="xajax_window_submit('work_space', 'xajax_window_submit(\\'display_domain\\', \\'domain_id=>{$pointsto['domain_id']}\\', \\'display\\')');"
                    >{$pointsto['domain_fqdn']}</a>.&nbsp;
EOL;
        }
        // Process CNAME record
        if ($record['type'] == 'CNAME') {
            list($status, $rows, $cname) = ona_get_dns_record(array('id' => $record['dns_id']), '');
            $data = <<<EOL
                    <a title="Edit DNS A record"
                       class="act"
                       onClick="xajax_window_submit('edit_record', 'dns_record_id=>{$record['dns_id']}', 'editor');"
                    >{$cname['name']}</a>.<a title="View domain. ID: {$cname['domain_id']}"
                         class="domain"
                         onClick="xajax_window_submit('work_space', 'xajax_window_submit(\\'display_domain\\', \\'domain_id=>{$cname['domain_id']}\\', \\'display\\')');"
                    >{$cname['domain_fqdn']}</a>.&nbsp;
EOL;
        }
        // Process NS record
        if ($record['type'] == 'NS') {
            // clear out the $record['domain'] value so it shows properly in the list
            $record['name'] = '';
            list($status, $rows, $ns) = ona_get_dns_record(array('id' => $record['dns_id']), '');
            $data = <<<EOL
                    <a title="Edit DNS A record"
                       class="act"
                       onClick="xajax_window_submit('edit_record', 'dns_record_id=>{$record['dns_id']}', 'editor');"
                    >{$ns['name']}</a>.<a title="View domain. ID: {$ns['domain_id']}"
                         class="domain"
                         onClick="xajax_window_submit('work_space', 'xajax_window_submit(\\'display_domain\\', \\'domain_id=>{$ns['domain_id']}\\', \\'display\\')');"
                    >{$ns['domain_fqdn']}</a>.&nbsp;
EOL;
        }
        // Process MX record
        if ($record['type'] == 'MX') {
            // show the preference value next to the type
            $record['type'] = "{$record['type']} ({$record['mx_preference']})";
            list($status, $rows, $mx) = ona_get_dns_record(array('id' => $record['dns_id']), '');
            $data = <<<EOL
                    <a title="Edit DNS A record"
                       class="act"
                       onClick="xajax_window_submit('edit_record', 'dns_record_id=>{$record['dns_id']}', 'editor');"
                    >{$mx['name']}</a>.<a title="View domain. ID: {$mx['domain_id']}"
                         class="domain"
                         onClick="xajax_window_submit('work_space', 'xajax_window_submit(\\'display_domain\\', \\'domain_id=>{$mx['domain_id']}\\', \\'display\\')');"
                    >{$mx['domain_fqdn']}</a>.&nbsp;
EOL;
        }
        // Process SRV record
        if ($record['type'] == 'SRV') {
            // show the preference value next to the type
            $record['type'] = "{$record['type']} ({$record['srv_port']})";
            list($status, $rows, $srv) = ona_get_dns_record(array('id' => $record['dns_id']), '');
            $data = <<<EOL
                    <a title="Edit DNS A record"
                       class="act"
                       onClick="xajax_window_submit('edit_record', 'dns_record_id=>{$record['dns_id']}', 'editor');"
                    >{$srv['name']}</a>.<a title="View domain. ID: {$srv['domain_id']}"
                         class="domain"
                         onClick="xajax_window_submit('work_space', 'xajax_window_submit(\\'display_domain\\', \\'domain_id=>{$srv['domain_id']}\\', \\'display\\')');"
                    >{$srv['domain_fqdn']}</a>.&nbsp;
EOL;
        }
        // Process TXT record
        if ($record['type'] == 'TXT') {
            // some records will have an interfaceid and dnsid when associated to another dns name
            // some will just be un associated txt records or domain only records.  Determine that here and
            // display appropriately.  This is to ensure associated DNS records match up if the name changes
            if ($record['interface_id'] and $record['dns_id']) {
                list($status, $rows, $txtmain) = ona_get_dns_record(array('id' => $record['dns_id']), '');
                $record['name'] = $txtmain['name'] . '.';
            }
            $data = truncate($record['txt'], 70);
        }
        // Get the domain name and domain ttl
        $ttl_style = 'title="Time-to-Live"';
        list($status, $rows, $domain) = ona_get_domain_record(array('id' => $record['domain_id']));
        // Make record['domain'] have the right name in it
        if ($record['type'] != 'PTR') {
            $record['domain'] = $domain['fqdn'];
        }
        // clear out the $record['domain'] value so it shows properly in the list for NS records
        if ($record['type'] == 'NS') {
            $record['domain'] = $domain['fqdn'];
        }
        // if the ttl is blank, use the one in the domain (minimum)
        if ($record['ttl'] == 0) {
            $record['ttl'] = $domain['default_ttl'];
            $ttl_style = 'style="font-style: italic;" title="Using TTL from domain"';
        }
        // format the ebegin using the configured date format
        $ebegin = '';
        // If it is in the future, print the time
        if (strtotime($record['ebegin']) > time()) {
            $ebegin = '<span title="Active in DNS on: ' . $record['ebegin'] . '">' . date($conf['date_format'], strtotime($record['ebegin'])) . '</span>';
        }
        // If it is 0 then show as disabled
        if (strtotime($record['ebegin']) < 0) {
            $ebegin = <<<EOL
                <span
                    style="background-color:#FFFF99;"
                    title="Disabled: Won't build in DNS"
                    onClick="var doit=confirm('Are you sure you want to enable this DNS record?');
                                if (doit == true)
                                    xajax_window_submit('edit_record', xajax.getFormValues('{$form['form_id']}_list_record_{$record['id']}'), 'enablerecord');"
                >Disabled</span>
EOL;
        }
        // If we get this far and the name we have built has a leading . in it then remove the dot.
        $record['name'] = preg_replace("/^\\./", '', $record['name']);
        // Get the name of the view and the description
        if ($conf['dns_views']) {
            list($status, $rows, $dnsview) = ona_get_dns_view_record(array('id' => $record['dns_view_id']));
            $record['view_name'] = $dnsview['name'];
            $record['view_desc'] = $dnsview['description'];
        }
        // Escape data for display in html
        foreach (array_keys($record) as $key) {
            $record[$key] = htmlentities($record[$key], ENT_QUOTES, $conf['php_charset']);
        }
        //$primary_object_js = "xajax_window_submit('work_space', 'xajax_window_submit(\'display_host\', \'host_id=>{$record['id']}\', \'display\')');";
        $html .= <<<EOL
            <tr onMouseOver="this.className='row-highlight';" onMouseOut="this.className='row-normal';">
                <td class="list-row" style="padding-right: 2px; padding-left: 4px;" width="16px">
                {$primary_record}
                </td>

                <td class="list-row">
                    <span title="Record. ID: {$record['id']}"
                       onClick=""
                    >{$record['name']}</span
                    ><a title="View domain. ID: {$domain['id']}"
                         class="domain"
                         onClick="xajax_window_submit('work_space', 'xajax_window_submit(\\'display_domain\\', \\'domain_id=>{$domain['id']}\\', \\'display\\')');"
                    >{$record['domain']}.</a>
                </td>

                <td class="list-row">
                    <span
                       onClick=""
                       {$ttl_style}
                    >{$record['ttl']} seconds</span>&nbsp;
                </td>

                <td class="list-row">
                    <span title="Record Type"
                       onClick=""
                    >{$record['type']}</span>&nbsp;
                </td>

                <td class="list-row" align="left">
EOL;
        // Put the data in!
        $html .= $data;
        $html .= <<<EOL
                </td>

                <td class="list-row" align="center">
                    {$ebegin}&nbsp;
                </td>
EOL;
        // Display the view we are part of
        if ($conf['dns_views']) {
            $html .= <<<EOL
                <td class="list-row" align="center" title="{$record['view_desc']}">
                    {$record['view_name']}&nbsp;
                </td>
EOL;
        }
        $html .= <<<EOL
                <td class="list-row">
                    <span title="{$record['notes']}">{$record['notes_short']}</span>&nbsp;
                </td>

                <!-- ACTION ICONS -->
                <td class="list-row" align="right">
                    <form id="{$form['form_id']}_list_record_{$record['id']}"
                        ><input type="hidden" name="dns_record_id" value="{$record['id']}"
                        ><input type="hidden" name="host_id" value="{$host['id']}"
                        ><input type="hidden" name="js" value="{$refresh}"
                    ></form>&nbsp;
EOL;
        if (auth('dns_record_modify')) {
            // If it is an A record but not the primary, display an option to make it primary. and only if we are dealing with a specific host
            if (($record['type'] == 'A' or $record['type'] == 'AAAA') and $host['primary_dns_id'] != $record['id'] and $form['host_id']) {
                $html .= <<<EOL

                    <a title="Make this the primary DNS record"
                       class="act"
                       onClick="var doit=confirm('Are you sure you want to make this the primary DNS record for this host?');
                                if (doit == true)
                                    xajax_window_submit('edit_record', xajax.getFormValues('{$form['form_id']}_list_record_{$record['id']}'), 'makeprimary');"
                    ><img src="{$images}/silk/font_go.png" border="0"></a>
EOL;
            }
        }
        // display a view host button on the dns record search form list
        if ($form['search_form_id'] == 'dns_record_search_form') {
            $html .= <<<EOL

                    <a title="View associated host record: {$interface['host_id']}"
                       class="act"
                       onClick="xajax_window_submit('display_host', 'host_id=>{$interface['host_id']}', 'display');"
                    ><img src="{$images}/silk/computer_go.png" border="0"></a>&nbsp;
EOL;
        }
        if (auth('dns_record_modify')) {
            $html .= <<<EOL

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

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

            </tr>
EOL;
        // reset the record counter before we go back for the next iteration
        $last_record = array('name' => $record['name'], 'domain_id' => $record['domain_id']);
        $last_record_count = 1;
    }
    $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();
}
Ejemplo n.º 20
0
        <table width=100% cellspacing="0" border="0" cellpadding="0" style="margin-bottom: 8px;">
EOL;
    $haspool = 1;
    // Gather info about this subnet and if it is assigned to any dhcp servers.
    list($status, $srows, $dhcp_servers) = db_get_records($onadb, 'dhcp_server_subnets', array('subnet_id' => $record['id']));
    // find out if this subnet has any other pools that are part of failover groups
    list($status, $fgrows, $dhcp_fg_servers) = db_get_records($onadb, 'dhcp_pools', "subnet_id = '{$record['id']}' and dhcp_failover_group_id > 0");
    foreach ($dhcp_pool as $pool) {
        // Test for a dhcp server subnet entry for the pool or that it is part of a failover group
        $hasserver = $rowstyle = '';
        if (!$fgrows and !$srows and $pool['dhcp_failover_group_id'] == 0) {
            $hasserver = "<img src='{$images}/silk/error.png' border='0'>";
            $rowstyle = 'style="background-color: #FFDDDD;" title="There is no DHCP server defined for this pool!"';
        }
        $pool['ip_addr_start'] = ip_mangle($pool['ip_addr_start'], 'dotted');
        $pool['ip_addr_end'] = ip_mangle($pool['ip_addr_end'], 'dotted');
        $modbodyhtml .= <<<EOL
            <tr {$rowstyle}>
                <td align="left" nowrap="true">
                    {$hasserver} {$pool['ip_addr_start']}&nbsp;Thru&nbsp;{$pool['ip_addr_end']}&nbsp;
EOL;
        // Display information about what pool group this pool is assigned to
        // TODO: make this more efficient.  seems like there would be a better way to do this
        if ($pool['dhcp_failover_group_id']) {
            list($status, $rows, $failover_group) = ona_get_dhcp_failover_group_record(array('id' => $pool['dhcp_failover_group_id']));
            list($status, $rows, $server_host1) = ona_get_host_record(array('id' => $failover_group['primary_server_id']));
            list($status, $rows, $server_host2) = ona_get_host_record(array('id' => $failover_group['secondary_server_id']));
            $modbodyhtml .= <<<EOL
                <a title="View DHCP server (Primary failover) - {$server_host1['fqdn']}"
                    class="nav"
                    onClick="xajax_window_submit('work_space', 'xajax_window_submit(\\'display_dhcp_server\\', \\'host_id=>{$server_host1['id']}\\', \\'display\\')');"
Ejemplo n.º 21
0
function ws_display($window_name, $form = '')
{
    global $conf, $self, $ona;
    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);
    // Build $ip from $form['ip_block_start']
    $form['ip_block_start'] = ip_complete($form['ip_block_start'], '0');
    // Since we currently only display /24 (C) class networks, the
    //GD Need to call ip_mangle() so we can use is_ipv4()
    // last quad needs to be a .0.
    $ip = ip_mangle($form['ip_block_start'], 'numeric');
    if (is_ipv4($ip)) {
        $end = '\\.\\d+$';
        $replace_end_by = '.0';
        $version = 4;
    } else {
        $end = ':[0-9A-F]{0,4}$';
        // $replace_end_by = ':0000';
        $replace_end_by = ':';
        $version = 6;
    }
    $ip = $form['ip_block_start'] = preg_replace("/{$end}/", $replace_end_by, $form['ip_block_start']);
    // Find out if $ip is valid
    $ip = ip_mangle($ip, 'numeric');
    if ($ip == -1) {
        $js .= "alert('The IP address specified is invalid!');";
    }
    // Update History Title
    $history = array_pop($_SESSION['ona']['work_space']['history']);
    $js .= "xajax_window_submit('work_space', ' ', 'rewrite_history');";
    if ($history['title'] == $window_name) {
        $history['title'] = 'Map: ' . ip_mangle($ip, 'dotted');
        array_push($_SESSION['ona']['work_space']['history'], $history);
    }
    // Create some javascript to refresh the current page
    $refresh = htmlentities(str_replace(array("'", '"'), array("\\'", '\\"'), $history['url']), ENT_QUOTES, $conf['php_charset']);
    $refresh = "xajax_window_submit('work_space', '{$refresh}');";
    // Define the window's inner html
    $html .= <<<EOL
    <div id="{$window_name}_content" style="padding: 2px 4px;">
        <form id="block_search_form" onsubmit="el('zoom_block_button').onclick(); return false;">
        <div id="{$window_name}_tools">
            <b>IP Address</b>
            <input type="hidden" id="{$window_name}_zoom" name="zoom" value="8">
            <input id="{$window_name}_ip_block_start" name="{$window_name}_ip_block_start" value="{$form['ip_block_start']}" class="edit" type="text" size="15" />
            <a id="zoom_block_button" title="Zoom block"
                       class="act"
                       onClick="xajax_window_submit('work_space', 'xajax_window_submit(\\'{$window_name}\\', \\'ip_block_start=>' + el('{$window_name}_ip_block_start').value + ',zoom=>' + el('{$window_name}_zoom').value + '\\', \\'display\\');');"
            ><img src="{$images}/silk/bullet_go.png" border="0"></a>&nbsp;
        <br><br>
        </div>
        </form>

        <div id="{$window_name}_portal">
            <span id="{$window_name}_substrate"></span>
        </div>

    </div>
EOL;
    // Position/size the portal ourselves
    $js .= <<<EOL
        var _el = el('{$window_name}_portal');

        /* Now calculate where we will sit */
        var my_height = el('work_space_content').offsetHeight - el('{$window_name}_tools').offsetHeight - 40;
        var my_width  = el('{$window_name}_tools').offsetWidth - 10;

        /* Finally reposition/resize the window */
        _el.style.position = 'relative';
        _el.style.height   = my_height + 'px';

EOL;
    // Get javascript to setup the map portal
    $js .= get_portal_js($window_name, $ip, $version);
    //*** Send a fake mouseup event to draw the initial map view ***
    $js .= "el('{$window_name}_portal').myonmouseup('fake event');";
    // Insert the new html into the window
    // Instantiate the xajaxResponse object
    $response = new xajaxResponse();
    // GDO need to use Big Int JS
    $response->addIncludeScript('include/js/bignumber.js');
    $response->addAssign("work_space_content", "innerHTML", $html);
    if ($js) {
        $response->addScript($js);
    }
    return $response->getXML();
}
Ejemplo n.º 22
0
function ws_free_ip($window_name, $form = '')
{
    global $conf, $self, $onadb;
    global $color, $style, $images;
    $html = $js = '';
    // If the user supplied an array in a string, build the array and store it in $form
    $form = parse_options_string($form);
    // Set max_results and max_usage_bars if we need to
    if (!is_numeric($form['max_results'])) {
        $form['max_results'] = 512;
    }
    //
    // *** QF AVAILBLE IP ADDRESS SEARCH ***
    //
    // Get the specified subnet record by id
    list($status, $rows, $subnet) = ona_get_subnet_record(array('id' => $form['subnet_id']));
    if ($status or !$rows) {
        // Send a javascript popup error
        $response = new xajaxResponse();
        $response->addScript("alert('ERROR => Invalid subnet selected!');");
        return $response->getXML();
    }
    // Get a list of interfaces on the selected subnet
    list($status, $rows, $interfaces) = db_get_records($onadb, 'interfaces', array('subnet_id' => $subnet['id']));
    // Transform that list into a simple array of ip addresses
    // NOTE: you must use a string as the used_ips array element as integers will get too large
    $used_ips = array();
    foreach ($interfaces as $interface) {
        $used_ips["{$interface['ip_addr']}"] = $interface['host_id'];
    }
    unset($interfaces, $interface);
    // Get a list of dhcp pools on the selected subnet
    list($status, $rows, $pools) = db_get_records($onadb, 'dhcp_pools', array('subnet_id' => $subnet['id']));
    // Add DHCP pool addresses into the list of used ips
    foreach ($pools as $pool) {
        for ($ip = $pool['ip_addr_start']; $ip <= $pool['ip_addr_end']; $ip++) {
            $used_ips["{$ip}"] = $pool['id'];
        }
    }
    // Create a few variables that will be handy later
    if (strlen($subnet['ip_addr']) < 11) {
        // echo "ipv4";
        $num_ips = 0xffffffff - $subnet['ip_mask'];
        if ($subnet['ip_mask'] < 4294967294) {
            $last_ip = $subnet['ip_addr'] + $num_ips - 1;
        } else {
            $last_ip = $subnet['ip_addr'] + $num_ips;
        }
    } else {
        // echo "ipv6";
        $sub = gmp_sub("340282366920938463463374607431768211455", $subnet['ip_mask']);
        $num_ips = gmp_strval($sub);
        $last_ip = $subnet['ip_addr'] + $num_ips - 1;
    }
    // Search results go in here
    $results = array();
    $allused = count($used_ips);
    $count = gmp_strval(gmp_sub($num_ips, $allused));
    // Create a list of available IP's
    if ($subnet['ip_mask'] = 4294967296) {
        $ip = $subnet['ip_addr'];
    } else {
        $ip = gmp_strval(gmp_add($subnet['ip_addr'], '1'));
    }
    while ($ip <= $last_ip and count($results) <= $form['max_results']) {
        if (!array_key_exists("{$ip}", $used_ips)) {
            $results[] = $ip;
        }
        $plusone = gmp_add("1", $ip);
        $ip = gmp_strval($plusone);
    }
    //
    // *** BUTILD RESULTS HTML ***
    //
    $html .= <<<EOL
<table style="cursor: pointer;" width="100%" cellspacing="0" border="0" cellpadding="0">
EOL;
    if ($count > $form['max_results']) {
        $html .= <<<EOL
<tr><td style="cursor: default; font-size: 12px; background-color: #FFCCCC; color: 000;" colspan="5" align="center">Displaying {$form['max_results']} of {$count} results</td></tr>
EOL;
    }
    if ($count > $form['max_usage_bars']) {
        $too_many_bars_message = <<<EOL
<tr><td style="cursor: default; font-size: 12px; background-color: #FFCCCC; color: 000;" colspan="5" align="center">Usage graph only displayed for the first {$form['max_usage_bars']} subnets</td></tr>
EOL;
    }
    $subnet['name'] = htmlentities($subnet['name'], ENT_QUOTES, $conf['php_charset']);
    foreach ($results as $ip) {
        if (strlen($ip) > 11) {
            $ip = ip_mangle($ip, 'ipv6gz');
        } else {
            $ip = ip_mangle($ip, 'dotted');
        }
        $html .= <<<EOL
<tr onMouseOver="this.className='row-highlight';"
    onMouseOut="this.className='row-normal';"
    onClick="el('{$form['input_id']}').value = '{$ip}'; el('{$form['text_id']}').innerHTML = '{$subnet['name']}'; removeElement('{$form['id']}');">
    <td style="font-size: 10px; padding: 0px 2px;">{$ip}</td>
</tr>
EOL;
    }
    $html .= <<<EOL
</table>
EOL;
    $js .= <<<EOL
        el('{$form['content_id']}').style.display = 'block';
        /* Reposition the popup if the new content is displayed off the screen */
        wwTT_position('{$form['id']}');
EOL;
    // Insert the new html into the window
    // Instantiate the xajaxResponse object
    $response = new xajaxResponse();
    $response->addAssign($form['content_id'], "innerHTML", $html);
    if ($js) {
        $response->addScript($js);
    }
    return $response->getXML();
}
Ejemplo n.º 23
0
function subnet_conf($subnet = array(), $indent = 0)
{
    printmsg("DEBUG => subnet_conf(\$subnet, {$indent}) called", 5);
    // global $dhcp_entry_options;
    global $self;
    $exit = 0;
    // Validate input
    if (!(is_array($subnet) and count($subnet) > 0)) {
        return array(1, "");
    }
    // set the indent info if required
    $dent = '';
    if ($indent != 0) {
        $dent = '    ';
    }
    $text = "\n{$dent}# {$subnet['name']}\n";
    // Determine if this is a IPv6 address
    if ($subnet['ip_addr'] > '4294967295') {
        $text .= "{$dent}subnet6 " . ip_mangle($subnet['ip_addr'], 'ipv6') . "/" . ip_mangle($subnet['ip_mask'], 'cidr') . " {\n";
        // v6 does not allow a gateway defined, it uses the RA to do it.
        $hasgatewayoption = 1;
        $v6option = 'dhcp6.';
    } else {
        $text .= "{$dent}subnet " . long2ip($subnet['ip_addr']) . " netmask " . long2ip($subnet['ip_mask']) . " {\n";
        $hasgatewayoption = 0;
        $v6option = '';
    }
    // Loop through all of the dhcp entries and print them
    $i = 0;
    do {
        list($status, $rows, $dhcp_entry) = ona_get_dhcp_option_entry_record(array('subnet_id' => $subnet['id']));
        printmsg("DEBUG => subnet_conf(): Processing option {$dhcp_entry['display_name']}", 3);
        if (!$rows) {
            break;
        }
        if ($status) {
            $exit++;
            break;
        }
        // if the current dhcp entry is the "Default Gateway" option then set hasgatewayoption to 1
        if (strpos($dhcp_entry['name'], 'router') !== false) {
            printmsg("DEBUG => subnet_conf(\$subnet, {$indent}): --------.", 5);
            $hasgatewayoption = 1;
        }
        $i++;
        // format the tag appropriatly
        list($status, $formatted_entry) = format_tag($dhcp_entry);
        if ($formatted_entry) {
            $text .= "{$dent}    option {$v6option}{$dhcp_entry['name']} {$formatted_entry};\n";
        } else {
            $exit++;
            break;
        }
    } while ($i < $rows);
    // Loop through all of the dhcp pools and print them
    $i = 0;
    do {
        list($status, $poolrows, $pool) = ona_get_dhcp_pool_record(array('subnet_id' => $subnet['id']));
        if (!$rows) {
            break;
        }
        if ($status) {
            $exit++;
            break;
        }
        $i++;
        list($status, $srows, $server_subnet) = ona_get_dhcp_server_subnet_record(array('subnet_id' => $pool['subnet_id']));
        // if there is no failover group assignment and this pool is related to your server, print it
        if ($server_subnet['host_id'] == $self['serverid'] && $pool['dhcp_failover_group_id'] == 0) {
            printmsg("DEBUG => subnet_conf(\$subnet, {$indent}): Found pool with no failovergroup.", 5);
            list($status, $pool_entry) = process_dhcp_pool($pool, $indent);
            $text .= $pool_entry;
        }
        // if there is a failover group assignment, print the pool
        if ($pool['dhcp_failover_group_id'] != 0) {
            printmsg("DEBUG => subnet_conf(\$subnet, {$indent}): Found pool with a failovergroup", 5);
            list($status, $pool_entry) = process_dhcp_pool($pool, $indent);
            $text .= $pool_entry;
        }
    } while ($i < $poolrows);
    // Close the subnet block
    $text .= "{$dent}}\n";
    // Return the subnet block if there is a gateway option defined.
    if ($hasgatewayoption == 1) {
        return array($exit, $text);
    } else {
        printmsg("ERROR => subnet_conf({$subnet['name']}): Not enabling subnet, no gateway option defined. ", 0);
        $text = "\n{$dent}# WARNING => Subnet {$subnet['name']} has no default gateway opiton defined, skipping...\n";
        return array($exit, $text);
    }
}
Ejemplo n.º 24
0
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 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'];
    }
    printmsg("DEBUG => Displaying subnets list page: {$page}", 1);
    // 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;
    //
    // *** ADVANCED SUBNET SEARCH ***
    //       FIND RESULT SET
    //
    // Start building the "where" clause for the sql query to find the subnets to display
    $where = "";
    $and = "";
    // enable or disable wildcards
    $wildcard = '%';
    if ($form['nowildcard']) {
        $wildcard = '';
    }
    // DISPLAY ALL
    if ($form['all_flag']) {
        $where .= $and . "id > 0";
        $and = " AND ";
    }
    // SUBNET ID
    if ($form['subnet_id']) {
        $where .= $and . "id = " . $form['subnet_id'];
        $and = " AND ";
    }
    // VLAN ID
    if ($form['vlan_id']) {
        $where .= $and . "vlan_id = " . $onadb->qstr($form['vlan_id']);
        $and = " AND ";
    }
    // SUBNET TYPE
    if ($form['nettype']) {
        $where .= $and . "subnet_type_id = " . $onadb->qstr($form['nettype']);
        $and = " AND ";
    }
    // find subnets that are associated with dhcp server
    if ($form['server_id']) {
        $where .= $and . "id IN (SELECT subnet_id FROM dhcp_server_subnets WHERE host_id = " . $onadb->qstr($form['server_id']) . ')';
        $and = " AND ";
    }
    // SUBNET NAME
    if ($form['subnetname']) {
        // This field is always upper case
        $form['subnetname'] = strtoupper($form['subnetname']);
        $where .= $and . "name LIKE " . $onadb->qstr($wildcard . $form['subnetname'] . $wildcard);
        $and = " AND ";
    }
    // IP ADDRESS
    if ($form['ip_subnet']) {
        // Build $ip and $ip_end from $form['ip_subnet'] and $form['ip_subnet_thru']
        $ip = ip_complete($form['ip_subnet'], '0');
        if ($form['ip_subnet_thru']) {
            $ip = ip_complete($form['ip_subnet'], '0');
            $ip_end = ip_complete($form['ip_subnet_thru'], '255');
            // Find out if $ip and $ip_end are valid
            $ip = ip_mangle($ip, 'numeric');
            $ip_end = ip_mangle($ip_end, 'numeric');
            if ($ip != -1 and $ip_end != -1) {
                // Find subnets between the specified ranges
                $where .= $and . " ip_addr >= " . $ip . " AND ip_addr <= " . $ip_end;
                $and = " AND ";
            }
        } else {
            list($status, $rows, $record) = ona_find_subnet($ip);
            if ($rows) {
                $where .= $and . " id = " . $record['id'];
                $and = " AND ";
            }
        }
    }
    // tag
    if ($form['tag_net']) {
        $where .= $and . "id in (select reference from tags where type like 'subnet' and name like " . $onadb->qstr($form['tag_net']) . ")";
        $and = " AND ";
    }
    // custom attribute type
    if ($form['custom_attribute_type_net']) {
        $where .= $and . "id in (select table_id_ref from custom_attributes where table_name_ref like 'subnets' and custom_attribute_type_id = (SELECT id FROM custom_attribute_types WHERE name = " . $onadb->qstr($form['custom_attribute_type_net']) . "))";
        $and = " AND ";
        $cavaluetype = "and custom_attribute_type_id = (SELECT id FROM custom_attribute_types WHERE name = " . $onadb->qstr($form['custom_attribute_type_net']) . ")";
    }
    // custom attribute value
    if ($form['ca_value_net']) {
        $where .= $and . "id in (select table_id_ref from custom_attributes where table_name_ref like 'subnets' {$cavaluetype} and value like " . $onadb->qstr($wildcard . $form['ca_value_net'] . $wildcard) . ")";
        $and = " AND ";
    }
    // display a nice message when we dont find all the records
    if ($where == '' and $form['content_id'] == 'search_results_list') {
        $js .= "el('search_results_msg').innerHTML = 'Unable to find subnets matching your query, showing all records';";
    }
    // Wild card .. if $where is still empty, add a 'ID > 0' to it so you see everything.
    if ($where == '') {
        $where = 'id > 0';
    }
    // Do the SQL Query
    $filter = '';
    if ($form['filter']) {
        // Subnet namess are always upper case
        $form['filter'] = strtoupper($form['filter']);
        $filter = ' AND name LIKE ' . $onadb->qstr('%' . $form['filter'] . '%');
    }
    list($status, $rows, $results) = db_get_records($onadb, 'subnets', $where . $filter, "ip_addr", $conf['search_results_per_page'], $offset);
    // If we got less than search_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);
    } else {
        if ($rows >= $conf['search_results_per_page']) {
            list($status, $rows, $records) = db_get_records($onadb, 'subnets', $where . $filter, "", 0);
        }
    }
    $count = $rows;
    //
    // *** BUILD HTML LIST ***
    //
    $html .= <<<EOL
    <!-- Subnet Results -->
    <table id="{$form['form_id']}_subnet_list" class="list-box" cellspacing="0" border="0" cellpadding="0">

        <!-- Table Header -->
        <tr>
            <td class="list-header" align="center" style="{$style['borderR']};">Name</td>
            <td class="list-header" align="center" style="{$style['borderR']};">Subnet</td>
            <td class="list-header" align="center" style="{$style['borderR']};">Usage</td>
            <td class="list-header" align="center" style="{$style['borderR']};">Type</td>
            <td class="list-header" align="center">&nbsp;</td>
        </tr>
EOL;
    // Loop and display each record
    foreach ($results as $record) {
        // Get additional info about eash subnet record //
        // 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_SUBNET_MASK_CIDR'] = ip_mangle($record['ip_mask'], 'cidr');
        list($status, $rows, $type) = ona_get_subnet_type_record(array('id' => $record['subnet_type_id']));
        $record['type'] = $type['display_name'];
        // Calculate the percentage of the subnet that's used (total size - allocated hosts - dhcp pool size)
        $usage_html = get_subnet_usage_html($record['id']);
        // Escape data for display in html
        foreach (array_keys($record) as $key) {
            $record[$key] = htmlentities($record[$key], ENT_QUOTES, $conf['php_charset']);
        }
        $primary_object_js = "xajax_window_submit('work_space', 'xajax_window_submit(\\'display_subnet\\', \\'subnet_id=>{$record['id']}\\', \\'display\\')');";
        $html .= <<<EOL
        <tr onMouseOver="this.className='row-highlight'" onMouseOut="this.className='row-normal'">

            <td class="list-row">
                <a title="View subnet. ID: {$record['id']}"
                   class="nav"
                   onClick="{$primary_object_js}"
                >{$record['name']}</a>
            </td>

            <td class="list-row" align="left">
                {$record['ip_addr']} <span title="{$record['ip_mask']}">/{$record['IP_SUBNET_MASK_CIDR']}</span>&nbsp;
            </td>

            <td class="list-row" align="center" style="vertical-align: middle;">
                {$usage_html}
            </td>

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

            <td class="list-row" align="right">
                <form id="{$form['form_id']}_list_subnet_{$record['id']}"
                    ><input type="hidden" name="subnet_id" value="{$record['id']}"
                    ><input type="hidden" name="js" value="{$refresh}"
                ></form>

                <a title="Display subnet map"
                   class="act"
                   onClick="xajax_window_submit('work_space', 'xajax_window_submit(\\'display_block_map\\', \\'ip_block_start=>{$record['ip_addr']}\\', \\'display\\');');"
                ><img src="{$images}/silk/shape_align_left.png" border="0"></a>&nbsp;
EOL;
        if (auth('subnet_modify')) {
            $html .= <<<EOL

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

                <a title="Delete subnet"
                   class="act"
                   onClick="var doit=confirm('Are you sure you want to delete this subnet?');
                            if (doit == true)
                                xajax_window_submit('edit_subnet', xajax.getFormValues('{$form['form_id']}_list_subnet_{$record['id']}'), 'delete');"
                ><img src="{$images}/silk/delete.png" border="0"></a>&nbsp;
EOL;
        }
        $html .= <<<EOL
            </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']);
    // If there was only 1 result, and we're about to display results in the "Search Results" window, display it.
    if ($count == 1 and $form['content_id'] == 'search_results_list' and $form['filter'] == '') {
        $js .= $primary_object_js;
    }
    // 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();
}
Ejemplo n.º 25
0
function get_ip_suggestions($q, $max_results = 10)
{
    global $onadb;
    $formatted = $results = array();
    // Complete the (potentially incomplete) ip address
    $ip = ip_complete($q, '0');
    $ip_end = ip_complete($q, '255');
    // Find out if $ip and $ip_end are valid
    $ip = ip_mangle($ip, 'numeric');
    $ip_end = ip_mangle($ip_end, 'numeric');
    if ($ip == -1 or $ip_end == -1) {
        return array();
    }
    // It's not valid ip addresses
    // Now use SQL to look for subnet ip records that match
    $table = 'subnets';
    $field = 'ip_addr';
    $where = "{$field} >= " . $onadb->qstr($ip) . " AND {$field} <= " . $onadb->qstr($ip_end);
    $order = "{$field} ASC";
    // Search the db for results and put results into $results
    list($status, $rows, $records) = db_get_records($onadb, $table, $where, $order, $max_results);
    foreach ($records as $record) {
        $results[] = $record[$field];
    }
    // If we need more suggestions, look in the host_subnets table
    $max_results -= count($results);
    if ($max_results) {
        $table = 'interfaces';
        list($status, $rows, $records) = db_get_records($onadb, $table, $where, $order, $max_results);
        foreach ($records as $record) {
            $results[] = $record[$field];
        }
    }
    // Format the ip's in dotted format
    sort($results);
    foreach ($results as $result) {
        // format ipv6 or regular
        $format = is_ipv4($result) ? 'dotted' : 'ipv6';
        $formatted[] = ip_mangle($result, $format);
    }
    unset($results, $result, $records, $record);
    return $formatted;
}
Ejemplo n.º 26
0
function ws_save($window_name, $form = '')
{
    global $include, $conf, $self, $onadb;
    // Check permissions
    if (!(auth('subnet_modify') and auth('subnet_add'))) {
        $response = new xajaxResponse();
        $response->addScript("alert('Permission denied!');");
        return $response->getXML();
    }
    // Instantiate the xajaxResponse object
    $response = new xajaxResponse();
    $js = '';
    // Validate input
    if ($form['set_name'] == '' or $form['set_type'] == '' or $form['set_ip'] == '' or $form['set_netmask'] == '') {
        $response->addScript("alert('Please complete all fields to continue!');");
        return $response->getXML();
    }
    // Make sure the IP address specified is valid
    $form['set_ip'] = ip_mangle($form['set_ip'], 'dotted');
    if ($form['set_ip'] == -1) {
        $response->addScript("alert('{$self['error']}');");
        return $response->getXML();
    }
    // Make sure the netmask specified is valid
    $form['set_netmask'] = ip_mangle($form['set_netmask'], 'cidr');
    if ($form['set_netmask'] == -1) {
        $self['error'] = preg_replace('/IP address/i', 'netmask', $self['error']);
        $response->addScript("alert('{$self['error']}');");
        return $response->getXML();
    }
    // Before we go on, we must alert the user if this new subnet would require a new PTR zone.
    //     $ipflip = ip_mangle($form['set_ip'],'flip');
    //     $octets = explode(".",$ipflip);
    //     // Find a pointer zone for this ip to associate with.
    //     list($status, $rows, $ptrdomain) = ona_find_domain($ipflip.".in-addr.arpa");
    //     if (!$ptrdomain['id']) {
    //         $self['error'] = "ERROR => This subnet is the first in the {$octets[3]}.0.0.0 class A range.  You must first create at least the following DNS domain: {$octets[3]}.in-addr.arpa\\n\\nSelect OK to create new DNS domain now.";
    //         $response->addScript("var doit=confirm('{$self['error']}');if (doit == true) {xajax_window_submit('edit_domain', 'newptrdomainname=>{$octets[3]}.in-addr.arpa', 'editor');} else {removeElement('{$window_name}');}");
    //         return($response->getXML());
    //     }
    // Decide if we're editing or adding
    $module = 'modify';
    // If we're adding, re-map some the array names to match what the "add" module wants
    if (!$form['subnet']) {
        $module = 'add';
        // If there's no "refresh" javascript, add a command to view the new subnet
        if (!preg_match('/\\w/', $form['js'])) {
            $form['js'] = "xajax_window_submit('work_space', 'xajax_window_submit(\\'display_subnet\\', \\'ip=>{$form['set_ip']}\\', \\'display\\')');";
        }
        // Remap some of the option names for the subnet_add() module
        $form['name'] = $form['set_name'];
        unset($form['set_name']);
        $form['type'] = $form['set_type'];
        unset($form['set_type']);
        $form['ip'] = $form['set_ip'];
        unset($form['set_ip']);
        $form['netmask'] = $form['set_netmask'];
        unset($form['set_netmask']);
        $form['vlan'] = $form['set_vlan'];
        unset($form['set_vlan']);
    }
    // Run the module to ADD or MODIFY the SUBNET.
    list($status, $output) = run_module('subnet_' . $module, $form);
    // If the module returned an error code display a popup warning
    if ($status) {
        $js .= "alert('Save failed.\\n" . preg_replace('/[\\s\']+/', ' ', $self['error']) . "');";
    } else {
        // Update the status to tell them what they just did if they just *added* a subnet and the "keep adding" box is checked.
        // Otherwise just close the edit window.
        if ($form['keepadding'] and $module == 'add') {
            $js .= "el('statusinfo_{$window_name}').innerHTML = 'Previously added: {$form['name']}';";
        } else {
            $js .= "removeElement('{$window_name}');";
        }
        // If there is "refresh" javascript, send it to the browser to execute
        // MP: FIXME.. there is an issue that if you add a new subnet, then imidiately modify its IP the JS refresh uses the old ip and fails.  find out why
        if ($form['js']) {
            $js .= $form['js'];
        }
    }
    // Insert the new table into the window
    $response->addScript($js);
    return $response->getXML();
}
Ejemplo n.º 27
0
function ona_find_subnet($search = "")
{
    global $self;
    // Validate input
    if ($search == "") {
        return array(1, 0, array());
    }
    // If it's numeric
    if (preg_match('/^\\d+$/', $search)) {
        // It's a number - do several sql queries and see if we can get a unique match
        foreach (array('id', 'ip_addr') as $field) {
            // list($status, $rows, $record) = ona_get_subnet_record(array($field => $search));
            // GDO: don't use array() here, because it breaks ipv6 subnets
            list($status, $rows, $record) = ona_get_subnet_record("{$field} = {$search}");
            // If we got it, return it
            if ($status == 0 and $rows == 1) {
                printmsg("DEBUG => ona_find_subnet() found subnet record by {$field} {$search}", 2);
                return array(0, $rows, $record);
            }
        }
    }
    // If it's an IP address
    $ip = ip_mangle($search, 1);
    if ($ip != -1) {
        // Do a cool SQL query to find the subnet that the given IP address is on
        // Basically we tell the database we want to find an IP address >= than the base
        // of the subnet, and less than the end of the subnet.
        // Description:
        //   (2^32 - 1) == 4294967295 == a 32bit integer with all 1's.
        //   4294967295 - subnet_mask results in the number of hosts on that subnet.
        //   + the base ip_addr results in the top of the subnet.
        if (strlen($ip) > 11) {
            // IPv6.. had to check that it was above ipv4 space
            $where = "{$ip} between ip_addr AND ((340282366920938463463374607431768211455 - ip_mask) + ip_addr) and ip_addr > 4294967295";
        } else {
            $where = "{$ip} >= ip_addr AND {$ip} <= ((4294967295 - ip_mask) + ip_addr)";
        }
        list($status, $rows, $record) = ona_get_subnet_record($where);
        // If we got it, return it
        if ($status == 0 and $rows == 1) {
            printmsg("DEBUG => ona_find_subnet() found record by IP address", 2);
            return array(0, $rows, $record);
        }
        // Otherwise return an error
        if ($rows == 0) {
            $ip = ip_mangle($ip, 2);
            $self['error'] = "NOTICE => IP supplied, {$ip}, does not belong to any existing subnet!";
            printmsg($self['error'], 2);
            return array(3, $rows, array());
        }
        $self['error'] = "NOTICE => IP supplied, {$ip}, belongs to more than one subnet! Data corruption?";
        printmsg($self['error'], 2);
        return array(4, $rows, array());
    }
    // Try the name field
    // We use all upper-case subnet names
    list($status, $rows, $record) = ona_get_subnet_record(array('name' => strtoupper($search)));
    // If we got it, return it
    if ($status == 0 and $rows == 1) {
        printmsg("DEBUG => ona_find_subnet() found subnet record by its name", 2);
        return array(0, $rows, $record);
    }
    // We didn't find it - return and error code, 0 matches, and an empty record.
    $self['error'] = "NOTICE => couldn't find a unique subnet record with specified search criteria";
    printmsg($self['error'], 2);
    return array(2, 0, array());
}
Ejemplo n.º 28
0
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;
}
Ejemplo n.º 29
0
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();
}
Ejemplo n.º 30
0
Archivo: 2-to-3.php Proyecto: edt82/ona
// Uncomment the following to get a ton o' debug
//$conf['debug'] = 6;
// Get the PTR records that dont have a domain_id
list($status, $rows, $ptrs) = db_get_records($onadb, 'dns', "domain_id = 0 and type like 'PTR'", '');
echo "Found {$rows} PTR records with no domain.\n";
if (!$rows) {
    echo "  Everything looks OK!\n";
}
foreach ($ptrs as $ptr) {
    list($status, $rows, $interface) = ona_get_interface_record(array('id' => $ptr['interface_id']));
    // Print an error if it doesnt find an IP
    if (!$interface['ip_addr']) {
        echo "Possible orphan PTR record in dns table at ID: {$ptr['id']}.  You should delete this record manually.\n";
        continue;
    }
    $ipflip = ip_mangle($interface['ip_addr'], 'flip');
    $octets = explode(".", $ipflip);
    // Find a pointer domain for this record to associate with.
    list($status, $rows, $ptrdomain) = ona_find_domain($ipflip . ".in-addr.arpa", 0);
    // CRAPPY security cludge
    $_SESSION['ona']['auth']['user']['username'] = '******';
    $_SESSION['ona']['auth']['perms']['advanced'] = 'Y';
    $_SESSION['ona']['auth']['perms']['host_modify'] = 'Y';
    if (!$ptrdomain['id']) {
        echo "  {$interface['ip_addr_text']}: Unable to find a pointer domain for this IP! Creating the following DNS domain: {$octets[3]}.in-addr.arpa\n";
        list($status, $output) = run_module('domain_add', array('name' => $octets[3] . '.in-addr.arpa'));
        if ($status) {
            echo "ERROR => {$output}\n";
            exit($status);
        }
        list($status, $rows, $ptrdomain) = ona_find_domain($ipflip . ".in-addr.arpa", 0);