Example #1
0
function ws_menu($window_name, $form = '')
{
    global $conf, $images;
    $html = $js = '';
    // If an array in a string was provided, build the array and store it in $form
    $form = parse_options_string($form);
    printmsg("DEBUG => Displaying tooltip: {$form['tooltip']}", 4);
    $menuname = 'get_html_' . $form['menu_name'];
    list($html, $js) = $menuname($form);
    // Okay here's what we do:
    //   1. Hide the tool-tip
    //   2. Update it's content
    //   3. Reposition it
    //   4. Unhide it
    $response = new xajaxResponse();
    if ($html) {
        $response->addScript("el('{$form['id']}').style.visibility = 'hidden';");
        $response->addAssign($form['id'], "innerHTML", $html);
        $response->addScript("wwTT_position('{$form['id']}'); el('{$form['id']}').style.visibility = 'visible';");
    }
    if ($js) {
        $response->addScript($js);
    }
    return $response->getXML();
}
function checkmessage($msg)
{
    if (isset($msg) && !empty($msg)) {
        $type = substr($msg, 0, 1);
        $msg = substr($msg, 1);
        printmsg($msg, $type);
    }
}
Example #3
0
function add_permission($options = "")
{
    global $conf, $self, $onadb;
    printmsg('DEBUG => add_permission(' . $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['name']) {
        $self['error'] = 'ERROR => Insufficient parameters';
        // NOTE: Help message lines should not exceed 80 characters for proper display on a console
        return array(1, <<<EOM

add_permission-v{$version}
Registers a new permission, this should be used by install scripts that are
creating new functionality that requires a registered permission.

  Synopsis: add_permission(OPTIONS)

  Options:
    name=STRING         Name of permission
    desc=STRING         Quoted string to describe this permission


EOM
);
    }
    // Get a list of the valid "permissions" and their descriptions.
    list($status, $rows, $permissions) = db_get_record($onadb, 'permissions', array('name' => $options['name']), '');
    if ($rows) {
        $self['error'] = "ERROR => add_permission() Permission already exists: {$options['name']}";
        printmsg($self['error'], 0);
        return array(1, $self['error'] . "\n");
    }
    // Get the next ID for the new host record
    $id = ona_get_next_id('permissions');
    if (!$id) {
        $self['error'] = "ERROR => The ona_get_next_id('permissions') call failed!";
        printmsg($self['error'], 0);
        return array(7, $self['error'] . "\n");
    }
    printmsg("DEBUG => ID for new permission record: {$id}", 3);
    // Add the record
    list($status, $rows) = db_insert_record($onadb, 'permissions', array('id' => $id, 'name' => $options['name'], 'description' => $options['desc']));
    if ($status or !$rows) {
        $self['error'] = "ERROR => add_permission() SQL Query failed: " . $self['error'];
        printmsg($self['error'], 0);
        return array(2, $self['error'] . "\n");
    }
    // Return the success notice
    $self['error'] = "INFO => Permission ADDED: {$options['name']} [{$options['desc']}]";
    printmsg($self['error'], 0);
    return array(0, $self['error'] . "\n");
}
Example #4
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);
    }
}
Example #5
0
function sess_read($key)
{
    global $SESS_DBH, $SESS_LIFE;
    printmsg("sess_read({$key}) called", 6);
    list($status, $rows, $record) = db_get_record($SESS_DBH, 'sessions', "`sesskey` = '{$key}' AND `expiry` > " . time());
    if ($status or $rows == 0) {
        return false;
    }
    if (array_key_exists('sessvalue', $record)) {
        // Update the expiry time (i.e. keep sessions alive even if nothing in the session has changed)
        $expiry = time() + $SESS_LIFE;
        list($status, $rows) = db_update_record($SESS_DBH, 'sessions', "`sesskey` = '{$key}' AND `expiry` > " . time(), array('expiry' => $expiry));
        if ($status) {
            return false;
        }
        // Return the value
        return $record['sessvalue'];
    }
    return false;
}
Example #6
0
function ws_process_alerts_submit($window_name, $form = '')
{
    global $conf, $self, $onadb, $tip_style;
    global $font_family, $color, $style, $images;
    $html = $js = '';
    // If an array in a string was provided, build the array and store it in $form
    $form = parse_options_string($form);
    printmsg("DEBUG => Processing Alerts:", 5);
    // FIXME: this code is called from html_desktop.inc.php.. however it is failing to process for some reason
    // The intent of this code is to be called to display a "message waiting" type icon in the top menu bar.
    // Check for messages that begin with SYS_ in the table_name_ref column
    list($status, $rows, $msg) = db_get_record($onadb, 'messages', "table_name_ref LIKE 'SYS_%'");
    if ($rows) {
        $js .= "if (el('sys_alert')) {el('sys_alert').style.visibility = 'visible';}";
    } else {
        $js .= "if (el('sys_alert')) {el('sys_alert').style.visibility = 'hidden';}";
    }
    $response = new xajaxResponse();
    if ($js) {
        $response->addScript($js);
    }
    return $response->getXML();
}
Example #7
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();
}
Example #8
0
function ona_sql($options = "")
{
    // The important globals
    global $conf, $onadb, $base;
    // Version - UPDATE on every edit!
    $version = '1.05';
    // TODO: Maybe make this into a sys_config option
    $srvdir = dirname($base) . "/sql";
    printmsg('DEBUG => ona_sql(' . $options . ') called', 3);
    // Parse incoming options string to an array
    $options = parse_options($options);
    // Sanitize delimeter
    if (!$options['delimiter']) {
        $options['delimiter'] = ':';
    }
    // fix up the escaped ' marks.  may need the = and & stuff too????
    $options['sql'] = str_replace('\\\'', '\'', $options['sql']);
    $options['sql'] = str_replace('\\=', '=', $options['sql']);
    // Set "options[commit] to no if it's not set
    if (!array_key_exists('commit', $options)) {
        $options['commit'] = 'N';
    } else {
        $options['commit'] = sanitize_YN($options['commit'], 'N');
    }
    // Set "options[commit] to no if it's not set
    if (!array_key_exists('dataarray', $options)) {
        $options['dataarray'] = 'N';
    } else {
        $options['dataarray'] = sanitize_YN($options['dataarray'], 'N');
    }
    // Set "options[header] to yes if it's not set
    if (!array_key_exists('header', $options)) {
        $options['header'] = 'Y';
    } else {
        $options['header'] = sanitize_YN($options['header'], 'Y');
    }
    // Check permissions
    if (!auth('ona_sql')) {
        $self['error'] = "Permission denied!";
        printmsg($self['error'], 0);
        return array(10, $self['error'] . "\n");
    }
    // Return the usage summary if we need to
    if ($options['help'] or !($options['list'] and !$options['sql'] or !$options['list'] and $options['sql'])) {
        // NOTE: Help message lines should not exceed 80 characters for proper display on a console
        return array(1, <<<EOM

ona_sql-v{$version}
Runs the specified SQL query on the database and prints the result

  Synopsis: ona_sql [KEY=VALUE] ...

  Required:
    sql=STATEMENT|FILENAME   quoted SQL statement to execute
    OR
    list                     lists the SQL files available on the server side

  Optional:
    show                     displays contents of SQL, gives usage etc
    commit=yes|no            commit the transaction (no)
    header=yes|no            display record header (yes)
    delimiter=DELIMITER      record delimiter for output (:)
    (1,2,..)=VALUE           bind variables, replaces ? in query sequentially.
                             the first ? found is replaced by 1=value, and so on

  Notes:
    * Query is sent to the configured OpenNetAdmin database server.
    * The use of bind variables requires your options to match positionally.
    * The SQL option will be tried first as a local file, then as a server
      file, then as a raw text SQL query.  Filenames are case sensitive.
    * Server based SQL files are located in {$srvdir}
    * Some plugins may provide their own SQL dir inside the plugin directory
    * Use the show option to display contents of SQL files, this should contain
      a long description and any usage information that is needed.


EOM
);
    }
    // TODO: check that the user has admin privs? or at least a ona_sql priv
    // Get a list of the files
    $plugins = plugin_list();
    $files = array();
    $srvdirs = array();
    array_push($srvdirs, $srvdir);
    // add a local sql dir as well so they don't get overrriden by installs
    array_push($srvdirs, dirname($base) . '/www/local/sql');
    // loop through the plugins and find files inside of their sql directories.
    foreach ($plugins as $plug) {
        array_push($srvdirs, $plug['path'] . '/sql');
    }
    // Loop through each of our plugin directories and the default directory to find .sql files
    foreach ($srvdirs as $srvdir) {
        if ($handle = @opendir($srvdir)) {
            while (false !== ($file = readdir($handle))) {
                if ($file != "." && $file != ".." && substr($file, -4) == '.sql') {
                    // Build an array of filenames
                    array_push($files, $srvdir . '/' . $file);
                }
            }
            closedir($handle);
        }
    }
    // sort the file names
    asort($files);
    // List the sql files on the server side
    if ($options['list'] == 'Y') {
        $text .= sprintf("\n%-25s%s\n", 'FILE', 'DESCRIPTION');
        $text .= sprintf("%'-80s\n", '');
        // Loop through and display info about the files
        foreach ($files as $file) {
            // Open the file and get the first line, this is the short description
            $fh = fopen($file, 'r');
            $desc = rtrim(fgets($fh));
            fclose($fh);
            // Print the info
            $text .= sprintf("%-25s%s\n", basename($file), $desc);
        }
        $text .= "\n";
        return array(0, $text);
    }
    // Check that the sql variable passsed matches a file name locally, if it does, open it and replace $options['sql'] with it
    // Loop through files array till we find the right file
    $foundfile = false;
    foreach ($files as $file) {
        if (strstr($file, $options['sql'])) {
            $options['sql'] = trim(file_get_contents($file));
            $foundfile = true;
        }
    }
    // if we have not found a file on the server and the sql option does end in .sql then print a message that we coulnt find a file
    // otherwise assume it is a sql statement being passed at the cli
    if ($foundfile == false and substr($options['sql'], -4) == '.sql') {
        $self['error'] = "ERROR => Unable to find specified SQL stored on server: {$options['sql']}";
        printmsg($self['error'], 2);
        return array(10, $self['error'] . "\n");
    }
    // Show the contents of the sql query for usage info etc.
    if ($options['show'] == 'Y') {
        $text .= $options['sql'] . "\n\n";
        return array(0, $text);
    }
    // Count how many ?s there are in the sql query. that must match how many sqlopts are passed
    // if this is an oracle database you could change the ? to a :.. more work on this however needs to be done
    $qvars = substr_count($options['sql'], '?');
    // loop through the options based on how many qvars are in the sql statement. print an error if we didnt
    // get a variable to use in the sql statement
    for ($i = 1; $i <= $qvars; $i++) {
        if (!array_key_exists($i, $options)) {
            $self['error'] = "ERROR => You did not supply a value for bind variable {$i}!";
            printmsg($self['error'], 2);
            return array(10, $self['error'] . "\n");
        }
        // assign the variables to sqlopts
        $sqlopts[$i] = $options[$i];
    }
    // One last check to be sure
    // Count how many times ? is in the sql statement.  there should be that many elements in sqlopts
    if (count($sqlopts) != $qvars) {
        $self['error'] = "ERROR => SQL query and bind variable count did not match.";
        printmsg($self['error'], 2);
        return array(1, $self['error'] . "\n");
    }
    printmsg("DEBUG => [ona_sql] Running SQL query: {$options['sql']}", 5);
    // Run the query
    $rs = $onadb->Execute($options['sql'], $sqlopts);
    if ($rs === false) {
        $self['error'] = "ERROR => SQL query failed: " . $onadb->ErrorMsg() . "\n";
        return array(2, $self['error']);
    }
    $text = "";
    $dataarr = array();
    // If we got a record, that means they did a select .. display it
    if ($rs->RecordCount()) {
        $build_header = 1;
        $i = 0;
        // Loop through each record returned by the sql query
        while (!$rs->EOF) {
            $i++;
            $record = $rs->FetchRow();
            $dataarr[$i] = $record;
            // Build the header if we need to
            if ($build_header == 1 and $options['header'] == 'Y') {
                $build_header = 0;
                foreach (array_keys($record) as $key) {
                    $text .= $key . $options['delimiter'];
                }
                $text = preg_replace("/{$options['delimiter']}\$/", "", $text);
                $text .= "\n";
            }
            // Display the row
            foreach (array_keys($record) as $key) {
                $text .= $record[$key] . $options['delimiter'];
            }
            $text = preg_replace("/{$options['delimiter']}\$/", "", $text);
            $text .= "\n";
        }
    } else {
        $text .= "NOTICE => SQL executed successfully - no records returned\n";
    }
    // If we want the recordset returned instead of the text
    if ($options['dataarray'] == 'Y') {
        return array(0, $dataarr);
    }
    // Unless the user said YES to commit, return a non-zero
    // exit status so that module_run.php doesn't commit the DB transaction.
    $return = 1;
    if ($options['commit'] == 'Y') {
        $return = 0;
    }
    return array($return, $text);
}
Example #9
0
function dns_record_display($options = "")
{
    global $conf, $self, $onadb;
    // Version - UPDATE on every edit!
    $version = '1.00';
    printmsg("DEBUG => dns_record_display({$options}) called", 3);
    // Parse incoming options string to an array
    $options = parse_options($options);
    // Sanitize options[verbose] (default is yes)
    $options['verbose'] = sanitize_YN($options['verbose'], 'Y');
    // 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_display-v{$version}
Displays a DNS record from the database

  Synopsis: dns_record_display [KEY=VALUE] ...

  Required:
    name=NAME[.DOMAIN] or ID      hostname or ID of the dns record to display

  Optional:
    verbose=[yes|no]              display additional info (yes)



EOM
);
    }
    // If the name we were passed has a leading . in it then remove the dot.
    $options['name'] = preg_replace("/^\\./", '', $options['name']);
    // Find the DNS record from $options['name']
    list($status, $rows, $record) = ona_find_dns_record($options['name']);
    printmsg("DEBUG => dns_record_del() DNS record: {$record['name']}", 3);
    if (!$record['id']) {
        printmsg("DEBUG => Unknown DNS record: {$options['name']}", 3);
        $self['error'] = "ERROR => Unknown DNS record: {$options['name']}";
        return array(2, $self['error'] . "\n");
    }
    // Build text to return
    $text = "DNS {$record['type']} RECORD ({$record['fqdn']})\n";
    $text .= format_array($record);
    // If 'verbose' is enabled, grab some additional info to display
    if ($options['verbose'] == 'Y') {
        // PTR record(s)
        $i = 0;
        do {
            list($status, $rows, $ptr) = ona_get_dns_record(array('dns_id' => $record['id'], 'type' => 'PTR'));
            if ($rows == 0) {
                break;
            }
            $i++;
            $text .= "\nASSOCIATED PTR RECORD ({$i} of {$rows})\n";
            $text .= format_array($ptr);
        } while ($i < $rows);
        // CNAME record(s)
        $i = 0;
        do {
            list($status, $rows, $cname) = ona_get_dns_record(array('dns_id' => $record['id'], 'type' => 'CNAME'));
            if ($rows == 0) {
                break;
            }
            $i++;
            $text .= "\nASSOCIATED CNAME RECORD ({$i} of {$rows})\n";
            $text .= format_array($cname);
        } while ($i < $rows);
        // FIXME: MP display other types of records like NS,MX,SRV etc etc, also support dns views better
    }
    // Return the success notice
    return array(0, $text);
}
function build_dhcpd_conf($options = "")
{
    global $self;
    global $conf;
    global $onadb;
    // Version - UPDATE on every edit!
    $version = '1.10';
    // Exit status of the function
    $exit = 0;
    printmsg('DEBUG => build_dhcpd_conf(' . $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['server']) {
        // NOTE: Help message lines should not exceed 80 characters for proper display on a console
        return array(1, <<<EOM

build_dhcpd_conf-v{$version}
Builds configuration for dhcpcd from the database

  Synopsis: build_dhcpd_conf [KEY=VALUE] ...

  Required:
    server=NAME[.DOMAIN] or ID    Build conf by hostname or HOST_ID

  Optional:
    header_path=PATH              Path to the server local header to include

  Notes:
    * Specified host must be a valid DHCP server
    * header_path is a file on the DHCP server.  It will be defined at
      the very top of your configuration using the DHCP "include" directive.


EOM
);
    }
    // TODO: ipv6 need to pass in if we want v4 or v6.. default to v4 for now.
    //       looks like you cant have a mixed config
    // Debugging
    printmsg("DEBUG => Building DHCP config for: {$options['server']}", 3);
    // Validate that there is already a host named $options['server'].
    list($status, $rows, $host) = ona_find_host($options['server']);
    if (!$host['id']) {
        return array(2, "ERROR => No such host: {$options['server']}\n");
    }
    // Now determine if that host is a valid server
    list($status, $dhcp_rows, $dhcp_server) = db_get_records($onadb, 'dhcp_server_subnets', array('host_id' => $host['id']), '');
    list($status, $dhcpf_rows, $dhcpf_server) = db_get_records($onadb, 'dhcp_failover_groups', "primary_server_id = {$host['id']} or secondary_server_id = {$host['id']}", '');
    if ($dhcp_rows == 0 and $dhcpf_rows == 0) {
        return array(3, "ERROR => Specified host is not a DHCP server: {$options['server']}\n");
    }
    // Throw the host id into a self variable for later use
    $self['serverid'] = $host['id'];
    // Start an output variable with build timestamp
    $text .= "###### DO NOT EDIT THIS FILE ###### \n";
    $text .= "# dhcpd.conf file for {$host['fqdn']} built on " . date($conf['date_format']) . "\n#\n";
    $text .= "# This file is built by an automated script.  Any change to this \n";
    $text .= "# file will be lost at the next build.\n\n";
    // setup standard include path
    // TODO: MP possibly put this into a configuration option like header so the user can easily change where this is.
    if (isset($options['header_path'])) {
        $text .= "include \"{$options['header_path']}\";\n";
    }
    /////////////////////////////// Build global options //////////////////////////////////////////
    list($status, $globals) = build_global($host['id']);
    $text .= $globals;
    /////////////////////////////// Failover groups //////////////////////////////////////////
    // build list of failover group statements for provided server
    list($status, $failovergroup) = ona_dhcp_build_failover_group($host['id']);
    $text .= $failovergroup;
    /////////////////////////////// shared subnets //////////////////////////////////////////
    // setup a variable to keep track of which vlan we are on
    $vlananchor = '';
    // Loop through all of the vlan subnets and print them
    printmsg("DEBUG => Processing all Shared (VLAN) Subnets", 1);
    $i = 0;
    do {
        list($status, $rows, $vlan_subnet) = ona_get_record('vlan_id != 0 AND
                                                              id IN (SELECT subnet_id
                                                                     FROM   dhcp_server_subnets
                                                                     WHERE  host_id = ' . $host['id'] . '
                                                                     UNION
                                                                     SELECT subnet_id
                                                                     FROM dhcp_pools
                                                                     WHERE dhcp_failover_group_id IN (SELECT id
                                                                                                      FROM dhcp_failover_groups
                                                                                                      WHERE primary_server_id = ' . $host['id'] . '
                                                                                                      OR secondary_server_id = ' . $host['id'] . '))', 'subnets', 'vlan_id ASC');
        if ($status) {
            printmsg($self['error'], 0);
            $exit += $status;
        }
        if ($rows == 0) {
            printmsg("DEBUG => build_dhcpd_conf(): Found no shared subnets.", 3);
            break;
        } else {
            if ($i == 0) {
                $text .= "# --------SHARED SUBNETS (count={$rows})--------\n\n";
            }
        }
        printmsg("DEBUG => Processing vlan subnet " . ($i + 1) . " of {$rows}", 3);
        // pull info about the vlan itself
        list($status, $vlanrows, $vlan) = ona_get_vlan_record(array('id' => $vlan_subnet['vlan_id']));
        if ($status) {
            printmsg($self['error'], 0);
            $exit += $status;
        }
        // check to see if we have switched to a new vlan
        if ($vlananchor != $vlan_subnet['vlan_id']) {
            // if this is NOT the first loop through, close the previous shared network block
            if ($i >= 1) {
                $text .= "}\n\n";
            }
            // print the opening statement for the shared network block and strip characters that may cause errors
            $text .= "shared-network " . preg_replace('/[^A-Za-z0-9_-]/', '', "{$vlan['vlan_campus_name']}-{$vlan['number']}-{$vlan['name']}") . " {\n";
        }
        // print the subnet block for the current subnet in the loop
        list($status, $subnetblock) = subnet_conf($vlan_subnet, 1);
        if ($status) {
            printmsg("ERROR => subnet_conf() returned an error: vlan subnet: {$vlan_subnet['name']}", 0);
            $exit += $status;
        } else {
            $text .= $subnetblock;
        }
        $i++;
        // If the loop is at the end,and this isnt the first time we've come through the loop, print a close statement
        // if ($i == $rows && $vlananchor != '') {$text .= "}\n\n";}
        if ($i == $rows) {
            $text .= "}\n\n";
        }
        // continue to update the vlan anchor
        $vlananchor = $vlan_subnet['vlan_id'];
    } while ($i < $rows);
    /////////////////////////////// standard subnets //////////////////////////////////////////
    // Loop through all of the NON vlan subnets and print them
    printmsg("DEBUG => Processing all Non-Shared (Standard) Subnets", 1);
    // We do our own sql query here because it makes more sense than calling ona_get_record() a zillion times ;)
    $q = "SELECT *\n          FROM subnets\n          WHERE vlan_id = 0 AND\n                id IN (SELECT subnet_id\n                       FROM dhcp_server_subnets\n                       WHERE host_id = {$host['id']}\n                       UNION\n                       SELECT subnet_id\n                       FROM dhcp_pools\n                       WHERE dhcp_failover_group_id IN (SELECT id\n                                                        FROM dhcp_failover_groups\n                                                        WHERE primary_server_id = {$host['id']}\n                                                        OR secondary_server_id = {$host['id']}))\n\n          ORDER BY name ASC";
    $rs = $onadb->Execute($q);
    if ($rs === false) {
        $self['error'] = 'ERROR => build_dhcpd_conf(): standard_subnets: SQL query failed: ' . $onadb->ErrorMsg();
        printmsg($self['error'], 0);
        $exit += 1;
    }
    $rows = $rs->RecordCount();
    if ($rows > 0) {
        $text .= "# --------STANDARD SUBNETS (count={$rows})--------\n";
    }
    $i = 0;
    // Loop through the record set
    while ($std_subnet = $rs->FetchRow()) {
        printmsg("DEBUG => build_dhcpd_conf() Processing standard subnet " . ($i + 1) . " of {$rows}", 3);
        // print the subnet info for the current subnet in the loop
        list($status, $subnetblock) = subnet_conf($std_subnet, 0);
        if ($status) {
            printmsg("ERROR => subnet_conf() returned an error: non-vlan subnet: {$std_subnet['description']}", 0);
            $exit += $status;
        } else {
            $text .= $subnetblock;
        }
        $i++;
    }
    $rs->Close();
    /////////////////////////////// build static hosts //////////////////////////////////////////
    list($status, $hostconf) = build_hosts($host['id']);
    $text .= $hostconf;
    /////////////////////////////// Yer done, go home //////////////////////////////////////////
    // Return the config file
    return array($exit, $text);
}
Example #11
0
        $CurrPag = 0;
    }
    if ($CurrPag < 0) {
        $CurrPag = 0;
    }
    $postlink = $CurrPag * $PostXPage + 1;
    $db->query("replace temp(chiave,valore,TTL) values ('" . $_REQUEST['THR_ID'] . "',{$Num3d}," . (time() + 2592000) . ");");
    $db->query("update {$SNAME}_msghe set read_num=read_num+1 WHERE HASH='" . mysql_escape_string($MSGID) . "';");
    // *** convertire searcher.pm prima di attivare questa funzione ***
    //echo "<a href=\"searcher.pm?MODO=2&amp;REP_OF=".urlencode($MSGID)."\">";
    //echo $lang['shmsg_findnewmsg']."</a><br />";
    PageSelect(1);
    if ($CurrPag < 1) {
        printmsg($riga, $postlink - 1);
    }
    $query = "SELECT edit.TITLE AS title, edit.BODY AS body, membri.AUTORE as autore, " . " (origi.DATE+" . GMT_TIME . ") as 'date', (membri.DATE+" . GMT_TIME . ") AS regdate, membri.avatar AS avatar, membri.firma AS firma," . " membri.is_auth AS 'is_auth', membri.msg_num AS 'msg_num'," . " membri.title as 'gruppo', membri.HASH AS 'memhash',origi.HASH AS 'hash', edit.REP_OF AS 'repof'," . " edit.EDIT_OF AS 'edit_of', edit.HASH AS 'real_hash', edit.AUTORE AS 'real_autore', (edit.DATE+" . GMT_TIME . ") AS 'real_date'" . " FROM `{$SNAME}_reply` AS origi, `{$SNAME}_reply` AS edit, `{$SNAME}_membri` AS membri\r\n\t   WHERE edit.EDIT_OF=origi.HASH" . " AND membri.HASH=origi.AUTORE" . " AND edit.REP_OF='" . mysql_escape_string($MSGID) . "'" . " AND edit.visibile='1'" . " ORDER BY origi.DATE" . " LIMIT " . $CurrPag * $PostXPage . ",{$PostXPage};";
    $risultato = $db->get_results($query);
    if ($risultato) {
        foreach ($risultato as $riga) {
            printmsg($riga, $postlink);
            $postlink++;
        }
    }
    PageSelect(2);
    FastReply();
}
?>
</td>
</tr>
<?php 
include "end.php";
Example #12
0
function run_module($module = '', $options = '', $transaction = 1)
{
    global $conf, $self, $onadb;
    // Build the options array string from $options_string if we need to
    // This is only used for logging!  If $options_string is an array it
    // is passed untouched to the module.
    $options_string = $options;
    if (is_array($options)) {
        $options_string = '';
        $and = '';
        foreach (array_keys($options) as $key) {
            // Quote any "special" characters in the value.
            // Specifically the '=' and '&' characters need to be escaped.
            $options[$key] = str_replace(array('=', '&'), array('\\=', '\\&'), $options[$key]);
            // If the key has no value or it is the javascript key, dont print it.
            if ($options[$key] != "" and $key != 'js') {
                $options_string .= "{$and}{$key}={$options[$key]}";
                $and = '&';
            }
        }
    }
    // get the options as an array so we can look for logging info
    $local_options = parse_options($options);
    // If the user passes in an option called 'module_loglevel' then use it as the run module output level
    // otherwise default it to 1 so it will print out as normal.
    $log_level = 1;
    if ($local_options['module_loglevel']) {
        $log_level = $local_options['module_loglevel'];
    }
    // Remove config info as it can be huge and could have sensitive info in it.
    // This could cause issues since I"m doing & as an anchor at the end.  see how it goes.
    // The module that is called could also display this information depending on debug level
    $options_string = preg_replace("/config=.*&/", '', $options_string);
    printmsg("INFO => Running module: {$module} options: {$options_string}", $log_level);
    // Load the module
    if (load_module($module)) {
        return array(1, $self['error'] . "\n");
    }
    // Start an DB transaction (If the database supports it)
    if ($transaction) {
        $has_trans = $onadb->BeginTrans();
    }
    if (!$has_trans) {
        printmsg("WARNING => Transactions support not available on this database, this can cause problems!", 1);
    }
    // If begintrans worked and we support transactions, do the smarter "starttrans" function
    if ($has_trans) {
        printmsg("DEBUG => Commiting transaction", 2);
        $onadb->StartTrans();
    }
    // Start a timer so we can display moudle run time if debugging is enabled
    $start_time = microtime_float();
    // Run the function
    list($status, $output) = $module($options);
    // Stop the timer, and display how long it took
    $stop_time = microtime_float();
    printmsg("DEBUG => [Module_runtime] " . round($stop_time - $start_time, 2) . " seconds -- [Total_SQL_Queries] " . $self['db_get_record_count'] . " --  [Module_exit_code] {$status}", 1);
    // Either commit, or roll back the transaction
    if ($transaction and $has_trans) {
        if ($status != 0) {
            printmsg("INFO => There was a module error, marking transaction for a Rollback!", 1);
            //$onadb->RollbackTrans();
            $onadb->FailTrans();
        }
    }
    if ($has_trans) {
        // If there was any sort of failure, make sure the status has incremented, this catches sub module output errors;
        if ($onadb->HasFailedTrans()) {
            $status = $status + 1;
        }
        // If the user passed the rollback flag then dont commit the transaction
        // FIXME: not complete or tested.. it would be nice to have an ability for the user to pass
        //        a rollback flag to force the transaction to rollback.. good for testing adds/modify.
        //        The problem is sub modules will fire and then the whole thing stops so you wont see/test the full operation.
        //         if ($local_options['rollback']) {
        //             printmsg("INFO => The user requested to mark the transaction for a rollback, no changes made.", 0);
        //             $output .= "INFO => The user requested to mark the transaction for a rollback, no changes made.\n";
        //             $status = $status + 1;
        //         }
        printmsg("DEBUG => Commiting transaction", 2);
        $onadb->CompleteTrans();
    }
    // Return the module's output
    return array($status, $output);
}
Example #13
0
             fwrite($fh, "<?php\n\n\$ona_contexts=" . var_export($ona_contexts, TRUE) . ";\n\n?>");
             fclose($fh);
             $text .= "<img src=\"{$images}/silk/accept.png\" border=\"0\" /> Created database connection config file.<br>";
         }
         // Update the version element in the sys_config table
         if (@$db->Execute("UPDATE sys_config SET value='{$new_ver}' WHERE name like 'version'")) {
             // $text .= "<img src=\"{$images}/silk/accept.png\" border=\"0\" /> Updated local version info.<br>";
         } else {
             $status++;
             $text .= "<img src=\"{$images}/silk/exclamation.png\" border=\"0\" /> Failed to update version info in table 'sys_config'.<br><span style='font-size: xx-small;'>" . $db->ErrorMsg() . "</span><br>";
         }
     }
 } else {
     $status++;
     $text .= "<img src=\"{$images}/silk/exclamation.png\" border=\"0\" /> Failed to select DB '{$database_name}'.<br><span style='font-size: xx-small;'>" . $db->ErrorMsg() . "</span><br>";
     printmsg("ERROR => Failed to select DB: {$database_name}.  " . $db->ErrorMsg(), 0);
 }
 if ($status > 0) {
     $text .= "<img src=\"{$images}/silk/exclamation.png\" border=\"0\" /> There was a fatal error. Install may be incomplete. Fix the issue and <a href=\"{$baseURL}\">try again</a>.<br>";
 } else {
     // remove the run_install file in the install dir
     if (@file_exists($runinstall)) {
         if (!@unlink($runinstall)) {
             $text .= "<img src=\"{$images}/silk/exclamation.png\" border=\"0\" /> Failed to delete the file '{$runinstall}'.<br>";
             $text .= "<img src=\"{$images}/silk/exclamation.png\" border=\"0\" /> Please remove '{$runinstall}' manually.<br>";
         }
     }
     $text .= "You can now <a href='" . parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH) . "'>CLICK HERE TO START</a> using OpenNetAdmin!<br>You can log in as 'admin' with a password of 'admin'<br>Enjoy!";
 }
 // Close the database connection
 @$db->Close();
Example #14
0
function config_diff($options = "")
{
    // The important globals
    global $conf;
    global $self;
    global $onadb;
    // Version - UPDATE on every edit!
    $version = '1.03';
    printmsg('DEBUG => config_diff(' . $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['host'] or !$options['type']) and (!$options['ida'] or !$options['idb'])) {
        // NOTE: Help message lines should not exceed 80 characters for proper display on a console
        return array(1, <<<EOM

config_diff-v{$version}
Displays the difference between selected archive entries
  
  Synopsis: config_diff [KEY=VALUE] ...
  
  Required:
    host=ID or NAME[.DOMAIN]    display most recent config for specified host
    type=TYPE                   type of config to display -
                                  usually "IOS_VERSION" or "IOS_CONFIG"
     OR
    ida=ID                      First config ID to compare against idb
    idb=ID                      Second config ID to compare against ida

  Note:
    If you don't pass any IDs you will get the two most recent configs
    related to the host/type you provide.

EOM
);
    }
    $text = "";
    // Compare arbitrary configs based on config IDs
    // If we have ids, lets use those instead
    if ($options['ida'] and $options['idb']) {
        // get the two configs from the db
        list($status, $rows, $configs) = db_get_records($onadb, 'configurations', "id in ({$options['ida']},{$options['idb']})", 'ctime DESC', '2', '');
    } else {
        // Get a config record if there is one
        $self['error'] = "";
        list($status, $rows, $config) = ona_find_config($options);
        list($status, $rows, $configs) = db_get_records($onadb, 'configurations', array('host_id' => $config['host_id'], 'configuration_type_id' => $config['configuration_type_id']), 'ctime DESC', '2', '');
    }
    // Error if an error was returned
    if ($status or $rows != 2) {
        if ($self['error']) {
            $text = $self['error'] . "\n";
        }
        $text .= "ERROR => One or more config text entries not found!\n";
        return array(2, $text);
    }
    // Get a unified text diff output
    $text .= text_diff($configs[1]['config_body'], $configs[0]['config_body']);
    // Return the success notice
    return array(0, $text);
}
Example #15
0
function block_display($options = "")
{
    global $conf, $self, $onadb;
    // Version - UPDATE on every edit!
    $version = '1.00';
    printmsg("DEBUG => block_display({$options}) called", 3);
    // Parse incoming options string to an array
    $options = parse_options($options);
    // Sanitize options[verbose] (default is yes)
    $options['verbose'] = sanitize_YN($options['verbose'], 'Y');
    // Return the usage summary if we need to
    if ($options['help'] or !$options['block']) {
        // 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_display-v{$version}
Displays a block record from the database

  Synopsis: block_display [KEY=VALUE] ...

  Required:
    block=NAME or ID      Block name or ID of the block display

  Optional:
    verbose=[yes|no]      Display additional info (DEFAULT: yes)


EOM
);
    }
    // The formatting rule on block names is all upper and trim it
    $options['block'] = trim($options['block']);
    $options['block'] = preg_replace('/\\s+/', '-', $options['block']);
    $options['block'] = strtoupper($options['block']);
    // 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);
    // Build text to return
    $text = "BLOCK RECORD\n";
    $text .= format_array($block);
    // If 'verbose' is enabled, grab some additional info to display
    if ($options['verbose'] == 'Y') {
        $where .= " ip_addr >= " . $block['ip_addr_start'] . " AND ip_addr <= " . $block['ip_addr_end'];
        list($status, $netrows, $nets) = db_get_records($onadb, 'subnets', $where, "ip_addr");
        // subnet record(s)
        $i = 0;
        foreach ($nets as $record) {
            list($status, $rows, $subnet) = ona_get_subnet_record(array('id' => $record['id']));
            if ($rows == 0) {
                break;
            }
            $i++;
            $text .= "\nASSOCIATED SUBNET RECORD ({$i} of {$netrows})\n";
            $text .= format_array($subnet);
        }
    }
    // Return the success notice
    return array(0, $text);
}
Example #16
0
function message_add($options = "")
{
    // The important globals
    global $conf, $self, $onadb;
    // Version - UPDATE on every edit!
    $version = '1.00';
    // Default expiration
    $exp_default = "+6 week";
    $pri_default = 3;
    // Priority is one of the following:
    // 0 = Informational
    // 1 = red or high
    // 2 = yellow or medium
    // 3 = green or low
    printmsg("DEBUG => message_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['subnet'] and !$options['host'] or !$options['message'] and (!$options['expiration'] and !$options['priority'])) {
        // NOTE: Help message lines should not exceed 80 characters for proper display on a console
        $self['error'] = 'ERROR => Insufficient parameters';
        return array(1, <<<EOM

message_add-v{$version}
Adds the provided message to the host or subnet specified

  Synopsis: message_add

  Required:
    host=NAME[.DOMAIN]|IP     hostname or IP of the host
    OR
    subnet=NAME|IP            name or IP of the subnet

    message="STRING"          the content of the message

  Optional:
    priority=NUMBER           device/model type or ID (default: {$pri_default})
    expiration=DATE           date to expire message (default: NOW {$exp_default}s)

  Notes:
    Priority is one of the following:
    0 = blue or Informational
    1 = red or high
    2 = yellow or medium
    3 = green or low



EOM
);
    }
    // If they provided a hostname / ID let's look it up
    if ($options['host']) {
        list($status, $rows, $host) = ona_find_host($options['host']);
        $table_name_ref = 'hosts';
        $table_id_ref = $host['id'];
        $desc = $host['fqdn'];
    } else {
        if ($options['subnet']) {
            list($status, $rows, $subnet) = ona_find_subnet($options['subnet']);
            $table_name_ref = 'subnets';
            $table_id_ref = $subnet['id'];
            $desc = $subnet['name'];
        }
    }
    // If we didn't get a record then exit
    if (!$host['id'] and !$subnet['id']) {
        printmsg("DEBUG => No host or subnet found!", 3);
        $self['error'] = "ERROR => No host or subnet found!";
        return array(4, $self['error'] . "\n");
    }
    // Set the priority
    $priority = array_key_exists('priority', $options) ? $options['priority'] : $pri_default;
    if ($priority > 3 or $priority < 0 or !is_numeric($priority)) {
        $self['error'] = "ERROR => Priority must be a number between 0 and 3!";
        return array(4, $self['error'] . "\n");
    }
    // Get a username or "anonymous"
    $username = isset($_SESSION['username']) ? $_SESSION['username'] : "******";
    // Expiration date format
    if ($options['expiration']) {
        $expiration = date("Y-m-d G:i:s", strtotime($options['expiration']));
    } else {
        $expiration = date("Y-m-d G:i:s", strtotime($exp_default));
    }
    //  TODO: there should probably be some sort of security checks on the message that is passed in.
    //  I suspect this could be a security issue.  SQL injection etc.
    list($status, $rows) = db_insert_record($onadb, 'messages', array('table_name_ref' => $table_name_ref, 'table_id_ref' => $table_id_ref, 'priority' => $priority, 'username' => $username, 'expiration' => $expiration, 'message_text' => $options['message']));
    if ($status or !$rows) {
        $self['error'] = "ERROR => message_add() SQL Query failed: " . $self['error'];
        printmsg($self['error'], 0);
        return array(6, $self['error'] . "\n");
    }
    $text = "INFO => Message ADDED to: {$desc}\n";
    // Return the message file
    return array(0, $text);
}
Example #17
0
function ws_save($window_name, $form = '')
{
    global $conf, $self, $onadb;
    // Check permissions
    if (!auth('advanced')) {
        $response = new xajaxResponse();
        $response->addScript("alert('Permission denied!');");
        return $response->getXML();
    }
    // Instantiate the xajaxResponse object
    $response = new xajaxResponse();
    $js = '';
    // Strip whitespace
    // FIXME: (PK) What about SQL injection attacks?  This is a user-entered string...
    // Sanitize "name" option
    // We require view names to be in upper case and spaces are converted to -'s.
    $form['dns_view_name'] = strtoupper(trim($form['dns_view_name']));
    $form['dns_view_name'] = preg_replace('/\\s+/', '-', $form['dns_view_name']);
    $form['dns_view_description'] = trim($form['dns_view_description']);
    // Don't insert a string of all white space!
    if (trim($form['dns_view_name']) == "") {
        $self['error'] = "ERROR => Blank names not allowed.";
        printmsg($self['error'], 1);
        $response->addScript("alert('{$self['error']}');");
        return $response->getXML();
    }
    // If you get a numeric in $form, update the record
    if (is_numeric($form['id'])) {
        // Get the record before updating (logging)
        list($status, $rows, $original_type) = ona_get_record(array('id' => $form['id']), 'dns_views');
        $SET = array();
        if (strtoupper($form['dns_view_name']) != $original_type['name']) {
            // check for an existing entry like this
            list($status, $rows, $test) = ona_get_record(array('name' => $form['dns_view_name']), 'dns_views');
            if ($rows) {
                $self['error'] = "ERROR => The name you are trying to use already exists.";
                printmsg($self['error'], 1);
                $response->addScript("alert('{$self['error']}');");
                return $response->getXML();
            }
            $SET['name'] = strtoupper($form['dns_view_name']);
        }
        if ($form['dns_view_description'] != $original_type['description']) {
            $SET['description'] = $form['dns_view_description'];
        }
        list($status, $rows) = db_update_record($onadb, 'dns_views', array('id' => $form['id']), $SET);
        if ($status or !$rows) {
            $self['error'] = "ERROR => dns_view_edit update ws_save() failed: " . $self['error'];
            printmsg($self['error'], 1);
            $response->addScript("alert('{$self['error']}');");
        } else {
            // Get the record after updating (logging)
            list($status, $rows, $new_type) = ona_get_record(array('id' => $form['id']), 'dns_views');
            // Return the success notice
            $self['error'] = "INFO => DNS view UPDATED:{$new_type['id']}: {$new_type['name']}";
            printmsg($self['error'], 0);
            $log_msg = "INFO => DNS view UPDATED:{$new_type['id']}: name[{$original_type['name']}=>{$new_type['name']}]";
            printmsg($log_msg, 0);
        }
    } else {
        // check for an existing entry like this
        list($status, $rows, $test) = ona_get_record(array('name' => $form['dns_view_name']), 'dns_views');
        if ($rows) {
            $self['error'] = "ERROR => The name you are trying to use already exists.";
            printmsg($self['error'], 1);
            $response->addScript("alert('{$self['error']}');");
            return $response->getXML();
        }
        $id = ona_get_next_id('dns_views');
        if (!$id) {
            $self['error'] = "ERROR => The ona_get_next_id() call failed!";
            printmsg($self['error'], 1);
        } else {
            printmsg("DEBUG => id for new dns view record: {$id}", 3);
            list($status, $rows) = db_insert_record($onadb, "dns_views", array('id' => $id, 'name' => strtoupper(trim($form['dns_view_name'])), 'description' => $form['dns_view_description']));
            if ($status or !$rows) {
                $self['error'] = "ERROR => dns_view_edit add ws_save() failed: " . $self['error'];
                printmsg($self['error'], 1);
            } else {
                $self['error'] = "INFO => DNS view ADDED: {$form['dns_view_name']} ";
                printmsg($self['error'], 0);
            }
        }
    }
    // If the module returned an error code display a popup warning
    if ($status or !$rows) {
        $js .= "alert(\"Save failed. " . trim($self['error']) . " (Hint: Does the name you're trying to insert already exist?)\");";
    } else {
        $js .= "removeElement('{$window_name}');";
        $js .= "xajax_window_submit('app_dns_view_list', xajax.getFormValues('app_dns_view_list_filter_form'), 'display_list');";
    }
    // Return some javascript to the browser
    $response->addScript($js);
    return $response->getXML();
}
Example #18
0
function domain_server_del($options = "")
{
    // The important globals
    global $conf, $self, $onadb;
    // Version - UPDATE on every edit!
    $version = '1.02';
    printmsg("DEBUG => domain_server_del({$options}) called", 3);
    // Parse incoming options string to an array
    $options = parse_options($options);
    // Sanitize options[commit] (default is yes)
    $options['commit'] = sanitize_YN($options['commit'], 'N');
    // Return the usage summary if we need to
    if ($options['help'] or !($options['domain'] and $options['server'])) {
        // NOTE: Help message lines should not exceed 80 characters for proper display on a console
        $self['error'] = 'ERROR => Insufficient parameters';
        return array(1, <<<EOM

domain_server_del-v{$version}
Removes a domain record from a DNS server

  Synopsis: domain_server_del [KEY=VALUE] ...

  Required:
    domain=NAME or ID               domain name or ID
    server=NAME[.DOMAIN] or ID      server name or ID

  Optional:
    commit=[Y|N]                    commit db transaction (no)

EOM
);
    }
    if (is_numeric($options['domain'])) {
        $domainsearch['id'] = $options['domain'];
    } else {
        $domainsearch['name'] = strtoupper($options['domain']);
    }
    // Determine the entry itself exists
    list($status, $rows, $domain) = ona_get_domain_record($domainsearch);
    // Test to see that we were able to find the specified record
    if (!$domain['id']) {
        printmsg("DEBUG => Unable to find the domain record using {$options['domain']}!", 3);
        $self['error'] = "ERROR => Unable to find the domain record using {$options['domain']}!";
        return array(4, $self['error'] . "\n");
    }
    printmsg("DEBUG => domain_server_del(): Found domain, {$domain['name']}", 3);
    if ($options['server']) {
        // Determine the server is valid
        list($status, $rows, $host) = ona_find_host($options['server']);
        if (!$host['id']) {
            printmsg("DEBUG => The server ({$options['server']}) does not exist!", 3);
            $self['error'] = "ERROR => The server specified, {$options['server']}, does not exist!";
            return array(2, $self['error'] . "\n");
        }
    }
    // Test that this domain is even assigned to the server
    list($status, $rows, $domainserver) = ona_get_dns_server_domain_record(array('host_id' => $host['id'], 'domain_id' => $domain['id']));
    if (!$rows) {
        printmsg("DEBUG => Unable to find {$domain['name']} on server {$host['fqdn']}", 3);
        $self['error'] = "ERROR => Unable to find {$domain['name']} on server {$host['fqdn']}";
        return array(11, $self['error'] . "\n");
    }
    // Test that there are no NS records for this pair
    // ASSUMPTION: MP this will always be just one record??
    // depending on how the user has their NS records set up, we may not find anything.
    list($status, $dnsrows, $dnsrec) = db_get_record($onadb, 'dns', "domain_id = {$domain['id']} AND type = 'NS' AND interface_id in (select id from interfaces where host_id = {$host['id']})");
    // If "commit" is yes, delete the record
    if ($options['commit'] == 'Y') {
        // Check permissions
        if (!auth('advanced') or !authlvl($host['LVL']) or !authlvl($domain['LVL'])) {
            $self['error'] = "Permission denied!";
            printmsg($self['error'], 0);
            return array(10, $self['error'] . "\n");
        }
        // delete record from domain_server_domains
        list($status, $rows) = db_delete_records($onadb, 'dns_server_domains', array('id' => $domainserver['id']));
        if ($status) {
            $self['error'] = "ERROR => domain_server_del() SQL Query failed:" . $self['error'];
            printmsg($self['error'], 0);
            return array(9, $self['error'] . "\n");
        }
        // Run the module to delete the associated NS record.. Only if we found a dns record for NS
        if ($dnsrec['id']) {
            list($status, $output) = run_module('dns_record_del', array('name' => $dnsrec['id'], 'type' => 'NS', 'commit' => 'Y'));
            if ($status) {
                $self['error'] = "ERROR => domain_server_del() NS record delete failed:" . $output;
                printmsg($self['error'], 0);
                return array(9, $self['error'] . "\n");
            } else {
                // add the output to self error for display
                $add_to_error = $output;
            }
        }
        // Return the success notice
        $self['error'] = "INFO => DNS Domain/Server Pair DELETED: {$domain['name']}/{$host['fqdn']} ";
        printmsg($self['error'], 0);
        return array(0, $add_to_error . $self['error'] . "\n");
    }
    // Otherwise display the record that would have been deleted
    $text = <<<EOL
    Record(s) NOT DELETED (see "commit" option)
    Displaying record(s) that would have been removed:

    {$domain['name']} from: {$host['fqdn']}


EOL;
    if ($dnsrows) {
        $text .= "    Removing related NS record, if any. Please double check your NS records for this domain.\n";
    }
    return array(6, $text);
}
Example #19
0
function ws_delete($window_name, $form = '')
{
    global $conf, $self, $onadb;
    // Check permissions
    if (!auth('advanced')) {
        $response = new xajaxResponse();
        $response->addScript("alert('Permission denied!');");
        return $response->getXML();
    }
    // Instantiate the xajaxResponse object
    $response = new xajaxResponse();
    $js = '';
    // Load the record to make sure it exists
    list($status, $rows, $role) = db_get_record($onadb, 'roles', array('id' => $form));
    if ($status or !$rows) {
        $response->addScript("alert('Delete failed: Role id {$form} does not exist');");
        return $response->getXML();
    }
    // Get a list of device models that use this role
    list($status, $rows, $devicemodels) = db_get_records($onadb, 'models', array('role_id' => $form), '', 0);
    // Check that there are no parent records using this type
    if ($rows > 0) {
        $js .= "alert('Delete failed: There are {$rows} device models using this role.');";
    } else {
        // Delete the record
        list($status, $rows) = db_delete_records($onadb, 'roles', array('id' => $role['id']));
        if ($status or !$rows) {
            // If the module returned an error code display a popup warning
            $js .= "alert('Delete failed: " . trim($self['error']) . "');";
            $self['error'] = "ERROR => role_list ws_delete() SQL Query failed: " . $self['error'];
            printmsg($self['error'], 0);
        } else {
            $self['error'] = "INFO => Role DELETED: {$role['name']} ";
            printmsg($self['error'], 0);
        }
    }
    // Refresh the current list.. it's changed!
    $js .= "xajax_window_submit('{$window_name}', xajax.getFormValues('{$window_name}_filter_form'), 'display_list');";
    // Send an XML response
    $response->addScript($js);
    return $response->getXML();
}
Example #20
0
<?php

// Do some HTML headers before printing anything
header("Cache-control: private");
$year = date('Y');
// If there is a message of the day file, display it.
$motdfile = $base . '/local/config/motd.txt';
if (file_exists($motdfile)) {
    printmsg("INFO => Displaying MOTD: {$motdfile}", 1);
    $MOTD = file_get_contents($motdfile);
}
// Build a select option list for the context names
foreach (array_keys($ona_contexts) as $entry) {
    $selected = "";
    // If this entry matches the record you are editing, set it to selected
    if ($entry == $self['context_name']) {
        $selected = "SELECTED=\"yes\"";
    }
    if ($entry) {
        $context_list .= "<option {$selected} value=\"{$entry}\">{$entry}</option>\n";
    }
}
// Lets start building the page!
print <<<EOL
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN">
<!-- This web site is copyrighted (c) {$year} -->
<html>
<head>
    <title>{$conf['title']}</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <link rel="stylesheet" type="text/css" href="{$baseURL}/include/html_style_sheet.inc.php">
Example #21
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);
}
Example #22
0
function dhcp_server_del($options = "")
{
    // The important globals
    global $conf, $self, $onadb;
    // Version - UPDATE on every edit!
    $version = '1.03';
    printmsg("DEBUG => dhcp_server_del({$options}) called", 3);
    // Parse incoming options string to an array
    $options = parse_options($options);
    // Sanitize options[commit] (default is yes)
    $options['commit'] = sanitize_YN($options['commit'], 'N');
    // Return the usage summary if we need to
    if ($options['help'] or !($options['subnet'] and $options['server'])) {
        // 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_server_del-v{$version}
Removes a subnet record from a DHCP server

  Synopsis: dhcp_server_del [KEY=VALUE] ...

  Required:
    subnet=NAME or ID               subnet name or ID
    server=NAME[.DOMAIN] or ID      server name or ID

  Optional:
    commit=[Y|N]                    commit db transaction (no)

  Notes:
    DOMAIN will default to {$conf['dns_defaultdomain']} if not specified


EOM
);
    }
    // Determine the entry itself exists
    list($status, $rows, $subnet) = ona_find_subnet($options['subnet']);
    // Test to see that we were able to find the specified record
    if (!$subnet['id']) {
        printmsg("DEBUG => Unable to find the subnet record using {$options['subnet']}!", 3);
        $self['error'] = "ERROR => Unable to find the subnet record using {$options['subnet']}!";
        return array(4, $self['error'] . "\n");
    }
    printmsg("DEBUG => dhcp_server_del(): Found subnet, {$subnet['name']}", 3);
    if ($options['server']) {
        // Determine the server is valid
        list($status, $rows, $host) = ona_find_host($options['server']);
        if (!$host['id']) {
            printmsg("DEBUG => The server ({$options['server']}) does not exist!", 3);
            $self['error'] = "ERROR => The server specified, {$options['server']}, does not exist!";
            return array(2, $self['error'] . "\n");
        }
    }
    //printmsg("DEBUG => dhcp_server_del(): Found server, {$host['FQDN']}", 3);
    // Test that this subnet is even assigned to the server
    list($status, $rows, $dhcpserver) = ona_get_dhcp_server_subnet_record(array('host_id' => $host['id'], 'subnet_id' => $subnet['id']));
    if (!$rows) {
        printmsg("DEBUG => Unable to find {$subnet['name']} on server {$host['fqdn']}", 3);
        $self['error'] = "ERROR => Unable to find {$subnet['name']} on server {$host['fqdn']}";
        return array(11, $self['error'] . "\n");
    }
    // If "commit" is yes, delete the record
    if ($options['commit'] == 'Y') {
        // Check permissions
        if (!auth('advanced') or !authlvl($host['LVL']) or !authlvl($subnet['LVL'])) {
            $self['error'] = "Permission denied!";
            printmsg($self['error'], 0);
            return array(10, $self['error'] . "\n");
        }
        // check if allowed to remove subnet from server
        // check for pool assigned to the server itself
        list($status, $rows, $pools) = db_get_records($onadb, 'dhcp_pools', array('subnet_id' => $subnet['id']));
        foreach ($pools as $pool) {
            if ($pool['dhcp_failover_group_id']) {
                $foundfg = 0;
                list($status, $rows, $primary) = ona_get_dhcp_failover_group_record(array('id' => $pool['dhcp_failover_group_id'], 'primary_server_id' => $host['id']));
                if ($rows) {
                    $foundfg++;
                }
                list($status, $rows, $secondary) = ona_get_dhcp_failover_group_record(array('id' => $pool['dhcp_failover_group_id'], 'secondary_server_id' => $host['id']));
                if ($rows) {
                    $foundfg++;
                }
                // if a subnet/server pair is found in dhcp pools, don't allow removal
                if ($foundfg > 0) {
                    printmsg("DEBUG => Subnet ({$subnet['name']}) has a pool assigned to this Server ({$host['fqdn']}), which is part of a failover group.  The server must be removed from the failover group first.", 3);
                    $self['error'] = "ERROR => Subnet ({$subnet['name']}) has a pool assigned to this Server ({$host['fqdn']}), which is part of a failover group.  The server must be removed from the failover group first.";
                    return array(12, $self['error'] . "\n");
                }
            }
        }
        // MP: remove this after testing.  dhcp options should not stop us from dis-associating a subnet from a server
        //     Not really sure why I have this.. probably left over cruft from old thoughts
        //         // check if there are any DHCP parameters assigned to the subnet
        //         list($status, $rows, $tmp) = ona_get_dhcp_option_entry_record(array('subnet_id' => $subnet['id']));
        //
        //         // if so, check that this is not the last DHCP server that services this subnet
        //         if ($rows > 0) {
        //             list($status, $rows, $tmp) = ona_get_dhcp_server_subnet_record(array('subnet_id' => $subnet['id']));
        //
        //             // If this is the last DHCP server that services this subnet, don't allow removal until DHCP parameters are removed
        //             if($rows <= 1){
        //                 printmsg("DEBUG => Subnet ({$subnet['name']}) has DHCP parameters assigned which need to be removed first",3);
        //                 $self['error'] = "ERROR => Subnet ({$subnet['name']}) has DHCP parameters assigned which need to be removed first";
        //                 return(array(12, $self['error'] . "\n"));
        //             }
        //         }
        // delete record from dhcp_server_subnets
        list($status, $rows) = db_delete_records($onadb, 'dhcp_server_subnets', array('id' => $dhcpserver['id']));
        if ($status) {
            $self['error'] = "ERROR => dhcp_server_del() SQL Query failed:" . $self['error'];
            printmsg($self['error'], 0);
            return array(9, $self['error'] . "\n");
        }
        // Return the success notice
        $self['error'] = "INFO => DHCP Subnet/Server Pair DELETED: {$subnet['name']}/{$host['fqdn']} ";
        printmsg($self['error'], 0);
        return array(0, $self['error'] . "\n");
    }
    // Otherwise display the record that would have been deleted
    $text = <<<EOL
    Record(s) NOT DELETED (see "commit" option)
    Displaying record(s) that would have been removed:

    {$subnet['name']} from: {$host['fqdn']}

EOL;
    return array(6, $text);
}
Example #23
0
 if ($has_trans) {
     printmsg("DEBUG => Starting transaction", 2);
     $onadb->StartTrans();
 }
 // Run the SQL
 printmsg("DEBUG => Installing {$modname} plugin SQL statements.", 4);
 $i = 0;
 while ($i < count($statements) - 1) {
     // The SQL statements are split above based on a ; character.
     // This may not always work but should cover most things, just be aware.
     //$window['html'] .= $statements[$i].'---<br><br>';
     $ok = $onadb->Execute($statements[$i] . ';');
     $error = $onadb->ErrorMsg();
     if ($ok === false or $error) {
         if ($has_trans) {
             printmsg("INFO => There was a module error, marking transaction for a Rollback!", 1);
             $onadb->FailTrans();
         }
         break;
     }
     $i++;
 }
 // Report any errors
 if ($ok === false or $error) {
     $window['html'] .= <<<EOL
     <br><b>Installing database updates:</b><br>
     <img src='{$images}/silk/error.png' border='0'> <font color="red">ERROR => SQL statements failed:</font><br><pre>{$error}</pre>
     <br><img src='{$images}/silk/error.png' border='0'> Unable to automatically process SQL statements<br>
     &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<font color="orange">Please try again, or add the following SQL statements manually:</font>
     <pre>
     {$sqlcontent}
Example #24
0
function window_submit($window_name, $form = '', $function = '')
{
    // Instantiate the xajaxResponse object
    $response = new xajaxResponse();
    if (!$window_name or !$form) {
        return $response->getXML();
    }
    $js = "";
    printmsg("DEBUG => webwin_submit() Window: {$window_name} Function: {$function} Form: {$form}", 1);
    // If a function name wasn't provided, we look for a function called:
    //   $window_name . '_submit'
    if (!$function) {
        $function = "{$window_name}_submit";
    }
    $function = 'ws_' . $function;
    // If the function exists, run it and return it's output (an xml response)
    if (function_exists($function)) {
        return $function($window_name, $form);
    }
    // Try looking for the same function in an include file
    $file = window_find_include($window_name);
    if ($file) {
        require_once $file;
    } else {
        $response->addAssign("work_space_content", "innerHTML", "<br><center><font color=\"red\"><b>Invalid window requested: {$window_name}</b></font></center>");
    }
    // Now see if our function is available...
    if (function_exists($function)) {
        return $function($window_name, $form);
    }
    // Ok, I couldn't find anything to do.. just return an empty XML response
    printmsg("NOTICE => webwin_submit() invalid function called! Window: {$window_name} Function: {$function}", 0);
    return $response->getXML();
}
Example #25
0
function quick_search($q)
{
    global $conf, $self;
    //
    // *** Quick Search ***
    //
    //     If it's an IP or MAC address (string or numeric):
    //         Look for an interface and display associated host record
    //         Look for the subnet that IP is on and display a single subnet record
    //     If it's a string:
    //         Look for a hostname
    //         Look for an alias name (and display associated hosts)
    //         Look for a subnet name
    printmsg("DEBUG => quick_search({$q}) called", 3);
    // Check to see if it is a MAC.. do it here instead of in the next interface section
    // so that we can properly find multiple hosts with the same mac
    $mac = mac_mangle($q, 1);
    if ($mac != -1) {
        printmsg("DEBUG => quick_search() Looks like a MAC, Returning mac = {$q}", 3);
        return array('hosts', array('mac' => $q));
    }
    // See if $q identifies an interface record (by IP, MAC, etc)
    list($status, $rows, $record) = ona_find_interface($q);
    // If it was, display the associated host record
    if ($rows) {
        printmsg("DEBUG => quick_search() returning host match (ID={$record['host_id']})", 3);
        return array('hosts', array('host_id' => $record['host_id']));
    }
    // See if $q identifies a subnet record (by IP, ID, or Description)
    list($status, $rows, $record) = ona_find_subnet($q);
    // If it was, display the associated subnet record
    if ($rows) {
        printmsg("DEBUG => quick_search() returning subnet match (ID={$record['id']})", 3);
        return array('subnets', array('subnet_id' => $record['id']));
    }
    // Well, I guess we'll assume $q is a hostname/alias search
    printmsg("DEBUG => quick_search() found no subnet or host match. Returning hostname = {$q}", 3);
    return array('hosts', array('hostname' => $q));
}
Example #26
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();
}
Example #27
0
function ona_find_vlan($vlan_search = "", $campus_search = "")
{
    global $self;
    if (!$vlan_search and !$campus_search) {
        return array(1, 0, array());
    }
    // If we got a vlan campus search string, let's look for that first.
    if ($campus_search) {
        $campus_search = strtoupper($campus_search);
        // Do a few sql queries and see if we can get a unique match
        $search = $campus_search;
        foreach (array('name', 'id') as $field) {
            list($status, $rows, $campus) = ona_get_vlan_campus_record(array($field => $search));
            if (!$status and $rows == 1) {
                printmsg("DEBUG => ona_find_vlan() found vlan campus record by {$field}", 2);
                break;
            } else {
                $campus = array();
            }
        }
    }
    // Search by a vlan number
    if (is_numeric($vlan_search)) {
        $where = array('number' => $vlan_search);
    } else {
        // Search for a vlan by NAME, use the campus[ID] if we have one
        $vlan_search = strtoupper($vlan_search);
        $where = array('name' => $vlan_search);
    }
    if ($campus['id']) {
        $where['vlan_campus_id'] = $campus['id'];
    }
    list($status, $rows, $vlan) = ona_get_vlan_record($where);
    if (!$status and $rows == 1) {
        return array($status, $rows, $vlan);
    }
    // We didn't find it - return and error code, 0 matches, and an empty record.
    $self['error'] = "NOTICE => couldn't find a unique vlan record with specified search criteria";
    printmsg($self['error'], 1);
    return array(2, 0, array());
}
Example #28
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();
}
Example #29
0
<?php

// Lets do some initial install related stuff
if (file_exists(dirname(__FILE__) . "/install.php")) {
    printmsg("DEBUG => Found install file for " . basename(dirname(__FILE__)) . " plugin.", 1);
    include dirname(__FILE__) . "/install.php";
} else {
    // Place initial popupwindow content here if this plugin uses one.
}
Example #30
0
File: dcm.php Project: edt82/ona
    list($status, $js) = get_authentication($DCMUSER, $_SERVER['PHP_AUTH_PW']);
    $errmsg = substr($js, 27);
    if ($status == 0) {
        $PERMSTAT = get_perms($DCMUSER);
        printmsg("INFO => [{$type}] {$_SESSION['ona']['auth']['user']['username']} has logged in", 3);
    } else {
        printmsg("ERROR => DCM: Unknown user {$DCMUSER}", 4);
        print "ERROR => [{$DCMUSER}]: {$errmsg}\nSee -l and -p options within dcm.pl.\n";
        // clear the session
        // FIXME: should I do a sess_destroy or sess_close instead?  to clear crap from the DB
        unset($_SESSION['ona']['auth']);
        exit;
    }
}
// Display the current debug level if it's above 1
printmsg("DEBUG => debug level: {$conf['debug']}", 1);
/* ----------- RUN A MODULE IF NEEDED ------------ */
if (isset($_REQUEST['module'])) {
    // Run the module
    list($status, $output) = run_module($_REQUEST['module'], $_REQUEST['options']);
}
// process various types of output formats
if (strstr($_REQUEST['options'], "format=json")) {
    output_formatter('json', 'json_encode');
} elseif (strstr($_REQUEST['options'], "format=yaml")) {
    output_formatter('yaml', 'yaml_emit');
} else {
    // Assume default text format
    // Send the module status code and output to dcm.pl
    print $status . "\r\n";
    print $output;