Example #1
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 #2
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 #3
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 #4
0
function tag_del($options = "")
{
    // The important globals
    global $conf, $self, $onadb;
    // Version - UPDATE on every edit!
    $version = '1.00';
    printmsg("DEBUG => tag_del({$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['tag']) {
        // NOTE: Help message lines should not exceed 80 characters for proper display on a console
        $self['error'] = 'ERROR => Insufficient parameters';
        return array(1, <<<EOM

tag_del-v{$version}
Deletes an tag from the database

  Synopsis: tag_del [KEY=VALUE] ...

  Required:
    tag=ID             ID of the tag to delete

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



EOM
);
    }
    // Sanitize options[commit] (default is no)
    $options['commit'] = sanitize_YN($options['commit'], 'N');
    // If the tag provided is numeric, check to see if it's an tag
    if (is_numeric($options['tag'])) {
        // See if it's a tag_id
        list($status, $rows, $tag) = db_get_record($onadb, 'tags', array('id' => $options['tag']));
    }
    if (!$tag['id']) {
        printmsg("DEBUG => Unable to find tag ({$options['tag']})!", 3);
        $self['error'] = "ERROR => Unable to find tag ({$options['tag']})!";
        return array(2, $self['error'] . "\n");
    }
    // If "commit" is yes, delete the record
    if ($options['commit'] == 'Y') {
        // Check permissions
        if (!(auth('host_del') or auth('subnet_del'))) {
            $self['error'] = "Permission denied!";
            printmsg($self['error'], 0);
            return array(10, $self['error'] . "\n");
        }
        list($status, $rows) = db_delete_records($onadb, 'tags', array('id' => $tag['id']));
        if ($status or !$rows) {
            $self['error'] = "ERROR => tag_del() SQL Query failed: " . $self['error'];
            printmsg($self['error'], 0);
            return array(4, $self['error'] . "\n");
        }
        // Return the success notice
        $self['error'] = "INFO => TAG DELETED: {$tag['name']} from {$tag['type']}[{$tag['reference']}]";
        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 deleted:

    NAME:      {$tag['name']}
    TYPE:      {$tag['type']}
    REFERENCE: {$tag['reference']}


EOL;
    return array(6, $text);
}
Example #5
0
function ws_editor($window_name, $form = '')
{
    global $conf, $self, $onadb;
    global $font_family, $color, $style, $images;
    // Check permissions
    if (!auth('advanced')) {
        $response = new xajaxResponse();
        $response->addScript("alert('Permission denied!');");
        return $response->getXML();
    }
    // Set a few parameters for the "results" window we're about to create
    $window = array('title' => 'DHCP Option Editor', 'html' => '', 'js' => '');
    $window['js'] .= <<<EOL
        /* Put a minimize icon in the title bar */
        el('{$window_name}_title_r').innerHTML =
            '&nbsp;<a onClick="toggle_window(\\'{$window_name}\\');" title="Minimize window" style="cursor: pointer;"><img src="{$images}/icon_minimize.gif" border="0" /></a>' +
            el('{$window_name}_title_r').innerHTML;

        /* Put a help icon in the title bar */
        el('{$window_name}_title_r').innerHTML =
            '&nbsp;<a href="{$_ENV['help_url']}{$window_name}" target="null" title="Help" style="cursor: pointer;"><img src="{$images}/silk/help.png" border="0" /></a>' +
            el('{$window_name}_title_r').innerHTML;
EOL;
    // If we got an option, load it for display
    $overwrite = 'no';
    if (is_numeric($form)) {
        list($status, $rows, $record) = db_get_record($onadb, 'dhcp_options', array('id' => $form));
        if (!$status and $rows) {
            $overwrite = 'yes';
        }
    }
    // Internal tag type array, there is no table for this
    $type = array("L" => "IP Address List", "S" => "String", "N" => "Numeric", "I" => "IP Address", "B" => "Boolean");
    // Build tag type list
    while ($tag = current($type)) {
        $selected = "";
        // If this entry matches the record you are editing, set it to selected
        if (key($type) == $record['type']) {
            $selected = "SELECTED=\"selected\"";
        }
        if (key($type)) {
            $type_list .= "<option {$selected} value=\"" . key($type) . "\">{$tag}</option>\n";
        }
        next($type);
    }
    // Escape data for display in html
    foreach (array_keys((array) $record) as $key) {
        $record[$key] = htmlentities($record[$key], ENT_QUOTES, $conf['php_charset']);
    }
    // Load some html into $window['html']
    $window['html'] .= <<<EOL

    <!-- Simple Edit Form -->
    <form id="dhcp_option_edit_form" onSubmit="return false;">
    <input name="id" type="hidden" value="{$record['id']}">
    <table cellspacing="0" border="0" cellpadding="0" style="background-color: {$color['window_content_bg']}; padding-left: 20px; padding-right: 20px; padding-top: 5px; padding-bottom: 5px;">
        <tr>
            <td align="right" nowrap="true">
                Display Name
            </td>
            <td class="padding" align="left" width="100%">
                <input
                    name="display_name"
                    alt="Description"
                    value="{$record['display_name']}"
                    class="edit"
                    type="text"
                    size="30" maxlength="30"
                >
            </td>
        </tr>

        <tr>
            <td align="right">
                Option Name
            </td>
            <td class="padding" align="left" width="100%">
                <input
                    name="name"
                    alt="Name"
                    value="{$record['name']}"
                    class="edit"
                    type="text"
                    size="30" maxlength="30"
                >
            </td>
        </tr>

        <tr>
            <td align="right">
                Number
            </td>
            <td class="padding" align="left" width="100%">
                <input
                    name="number"
                    alt="DHCP Number"
                    value="{$record['number']}"
                    class="edit"
                    type="text"
                    size="5" maxlength="10"
                >
            </td>
        </tr>

        <tr>
            <td nowrap="yes" align="right">
                Option type
            </td>
            <td class="padding" align="left" width="100%">
                <select id="type" name="type" class="edit" accesskey="t">
                    {$type_list}
                </select>
            </td>
        </tr>


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

    </table>
    </form>

EOL;
    // Lets build a window and display the results
    return window_open($window_name, $window);
}
Example #6
0
function ws_editor($window_name, $form = '')
{
    global $conf, $self, $onadb;
    global $font_family, $color, $style, $images;
    // Check permissions
    if (!auth('advanced')) {
        $response = new xajaxResponse();
        $response->addScript("alert('Permission denied!');");
        return $response->getXML();
    }
    // Set a few parameters for the "results" window we're about to create
    $window = array('title' => 'DNS View Editor', 'html' => '', 'js' => '');
    $window['js'] .= <<<EOL
        /* Put a minimize icon in the title bar */
        el('{$window_name}_title_r').innerHTML =
            '&nbsp;<a onClick="toggle_window(\\'{$window_name}\\');" title="Minimize window" style="cursor: pointer;"><img src="{$images}/icon_minimize.gif" border="0" /></a>' +
            el('{$window_name}_title_r').innerHTML;

        /* Put a help icon in the title bar */
        el('{$window_name}_title_r').innerHTML =
            '&nbsp;<a href="{$_ENV['help_url']}{$window_name}" target="null" title="Help" style="cursor: pointer;"><img src="{$images}/silk/help.png" border="0" /></a>' +
            el('{$window_name}_title_r').innerHTML;
EOL;
    // If an array in a string was provided, build the array and store it in $form
    $form = parse_options_string($form);
    // If we got a view, load it for display
    if (is_numeric($form['id'])) {
        list($status, $rows, $record) = db_get_record($onadb, 'dns_views', array('id' => $form['id']));
    }
    // Escape data for display in html
    foreach (array_keys((array) $record) as $key) {
        $record[$key] = htmlentities($record[$key], ENT_QUOTES, $conf['php_charset']);
    }
    // Load some html into $window['html']
    $window['html'] .= <<<EOL

    <!-- Simple class types Edit Form -->
    <form id="dns_view_edit_form" onSubmit="return false;">
    <input name="id" type="hidden" value="{$record['id']}">
    <table cellspacing="0" border="0" cellpadding="0" style="background-color: {$color['window_content_bg']}; padding-left: 20px; padding-right: 20px; padding-top: 5px; padding-bottom: 5px;">
        <tr>
            <td class="input_required" align="right">
                Name
            </td>
            <td class="padding" align="left" width="100%">
                <input
                    name="dns_view_name"
                    alt="DNS View Name"
                    value="{$record['name']}"
                    class="edit"
                    type="text"
                    size="30" maxlength="64"
                >
            </td>
        </tr>

        <tr>
            <td class="input_required" align="right">
                Description
            </td>
            <td class="padding" align="left" width="100%">
                <input
                    name="dns_view_description"
                    alt="DNS View Description"
                    value="{$record['description']}"
                    class="edit"
                    type="text"
                    size="30" maxlength="64"
                >
            </td>
        </tr>

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

    </table>
    </form>

EOL;
    // Lets build a window and display the results
    return window_open($window_name, $window);
}
Example #7
0
function ws_save($window_name, $form = '')
{
    global $conf, $self, $mysql;
    // Make sure they have permission
    if (!auth('admin')) {
        $response = new xajaxResponse();
        $response->addScript("alert('Permission denied!');");
        return $response->getXML();
    }
    // Don't allow this in the demo account!
    if ($_SESSION['auth']['client']['url'] == 'demo') {
        $response = new xajaxResponse();
        $response->addScript("alert('Feature disabled in this demo!');");
        return $response->getXML();
    }
    // Instantiate the xajaxResponse object
    $response = new xajaxResponse();
    $js = '';
    // Make sure they're logged in
    if (!loggedIn()) {
        return $response->getXML();
    }
    // Validate input
    if (!$form['fname'] or !$form['lname'] or !$form['username']) {
        $js .= "alert('Error! First name, last name, and username are required fields!');";
        $response->addScript($js);
        return $response->getXML();
    }
    if (!$form['id'] and !$form['passwd']) {
        $js .= "alert('Error! A password is required to create a new employee!');";
        $response->addScript($js);
        return $response->getXML();
    }
    // Usernames are stored in lower case
    $form['username'] = strtolower($form['username']);
    // md5sum the password if there is one
    if ($form['passwd']) {
        $form['passwd'] = md5($form['passwd']);
    }
    // Create a new record?
    if (!$form['id']) {
        list($status, $rows) = db_insert_record($mysql, 'users', array('client_id' => $_SESSION['auth']['client']['id'], 'active' => 1, 'fname' => $form['fname'], 'lname' => $form['lname'], 'username' => $form['username'], 'passwd' => $form['passwd'], 'ctime' => date_mangle(time()), 'mtime' => date_mangle(time())));
        printmsg("NOTICE => Added new user: {$form['username']} client url: {$_SESSION['auth']['client']['url']}", 0);
    } else {
        list($status, $rows, $record) = db_get_record($mysql, 'users', array('id' => $form['id'], 'client_id' => $_SESSION['auth']['client']['id']));
        if ($rows != 1 or $record['id'] != $form['id']) {
            $js .= "alert('Error! The record requested could not be loaded from the database!');";
            $response->addScript($js);
            return $response->getXML();
        }
        if (strlen($form['passwd']) < 32) {
            $form['passwd'] = $record['passwd'];
        }
        list($status, $rows) = db_update_record($mysql, 'users', array('id' => $form['id']), array('fname' => $form['fname'], 'lname' => $form['lname'], 'username' => $form['username'], 'passwd' => $form['passwd'], 'mtime' => date_mangle(time()), 'active' => 1));
        printmsg("NOTICE => Updated user: {$form['username']} client url: {$_SESSION['auth']['client']['url']}", 0);
    }
    // If the module returned an error code display a popup warning
    if ($status) {
        printmsg("ERROR => User add/edit failed! {$self['error']}", 0);
        $js .= "alert('Save failed. Contact the webmaster if this problem persists.');";
        $response->addScript($js);
        return $response->getXML();
    }
    $js .= "removeElement('{$window_name}');";
    $js .= "xajax_window_submit('user_list', xajax.getFormValues('user_list_filter_form'), 'display_list');";
    // Handle the "admin" flag
    list($status, $rows, $user) = db_get_record($mysql, 'users', array('username' => $form['username'], 'client_id' => $_SESSION['auth']['client']['id'], 'active' => 1));
    list($status, $rows, $perm) = db_get_record($mysql, 'permissions', array('name' => 'admin'));
    list($status, $rows, $acl) = db_get_record($mysql, 'acl', array('user_id' => $user['id'], 'perm_id' => $perm['id']));
    if ($form['admin'] and !$acl['id'] and $user['id'] and $perm['id']) {
        // Give the user the permission
        list($status, $rows) = db_insert_record($mysql, 'acl', array('user_id' => $user['id'], 'perm_id' => $perm['id']));
    } else {
        if (!$form['admin'] and $acl['id'] and $user['id'] and $perm['id'] and $_SESSION['auth']['user']['id'] != $user['id']) {
            // Take the permission away, UNLESS THEY ARE TRYING TO MODIFY THEIR OWN ACCOUNT!
            list($status, $rows) = db_delete_record($mysql, 'acl', array('user_id' => $user['id'], 'perm_id' => $perm['id']));
        } else {
            if ($_SESSION['auth']['user']['id'] == $user['id']) {
                // IF they did try to remove their own admin status, give them a popup and tell them they can't do that.
                $js .= "alert('WARNING => You can\\'t change your own admin status!');";
            }
        }
    }
    // Insert the new table into the window
    $response->addScript($js);
    return $response->getXML();
}
Example #8
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 #9
0
function ws_save($window_name, $form = '')
{
    global $conf, $self, $onadb;
    // Check permissions
    if (!auth('user_admin')) {
        $response = new xajaxResponse();
        $response->addScript("alert('Permission denied!');");
        return $response->getXML();
    }
    // Instantiate the xajaxResponse object
    $response = new xajaxResponse();
    $js = '';
    $exit_status = 0;
    // Validate input
    if (!$form['username']) {
        $js .= "alert('Error! All fields are required!');";
        $response->addScript($js);
        return $response->getXML();
    }
    if (!preg_match('/^[A-Za-z0-9.\\-_]+$/', $form['username'])) {
        $js .= "alert('Invalid username! Valid characters: A-Z 0-9 .-_');";
        $response->addScript($js);
        return $response->getXML();
    }
    // Create a new record?
    if (!$form['user_id']) {
        list($status, $rows) = db_insert_record($onadb, 'users', array('username' => $form['username'], 'password' => $form['password']));
        if ($status or !$rows) {
            $self['error'] = "ERROR => user_edit_add ws_save()  SQL Query failed: " . $self['error'];
            printmsg($self['error'], 0);
        } else {
            $self['error'] = "INFO => User ADDED: {$form['username']} ";
            printmsg($self['error'], 0);
        }
    } else {
        list($status, $rows, $user) = db_get_record($onadb, 'users', array('id' => $form['user_id']));
        if ($rows != 1 or $user['id'] != $form['user_id']) {
            $js .= "alert('Error! The record requested could not be loaded from the database!');";
            $response->addScript($js);
            return $response->getXML();
        }
        list($status, $rows) = db_update_record($onadb, 'users', array('id' => $user['id']), array('username' => $form['username'], 'password' => $form['password']));
        if ($status) {
            $self['error'] = "ERROR => user_edit update ws_save()  SQL Query failed: " . $self['error'];
            printmsg($self['error'], 0);
        } else {
            list($status, $rows, $new_record) = db_get_record($onadb, 'users', array('id' => $user['id']));
            // Return the success notice
            $self['error'] = "INFO => User UPDATED:{$user['id']}: {$new_record['username']}";
            $log_msg = "INFO => User UPDATED:{$user['id']}: ";
            $more = "";
            foreach (array_keys($user) as $key) {
                if ($user[$key] != $new_record[$key]) {
                    $log_msg .= $more . $key . "[" . $user[$key] . "=>" . $new_record[$key] . "]";
                    $more = ";";
                }
            }
        }
    }
    // Make sure we can load the user record from the db
    list($status, $rows, $user) = db_get_record($onadb, 'users', array('username' => $form['username']));
    if ($status or $rows != 1) {
        $js .= "alert('Save failed: " . trim($self['error']) . "');";
        // Return some javascript to the browser
        $response->addScript($js);
        return $response->getXML();
    }
    // This is a bit tricky because we want to make sure the user has all the groups
    // that are checked in the form, but no others.  And of course we want to make as
    // few sql queries as possible.  It's tricky because the form only submits us the
    // groups that are checked.
    // Get a list of every group
    list($status, $rows, $groups) = db_get_records($onadb, 'groups', 'id > 0');
    // Loop through each group
    foreach ($groups as $group) {
        // See if the user is assigned to this group or not
        list($status, $rows, $tmp) = db_get_record($onadb, 'group_assignments', array('user_id' => $user['id'], 'group_id' => $group['id']));
        $exit_status += $status;
        // If the user is supposed to be assigned to this group, make sure she is.
        if (array_key_exists($group['name'], $form['groups'])) {
            if ($status == 0 and $rows == 0) {
                list($status, $rows) = db_insert_record($onadb, 'group_assignments', array('user_id' => $user['id'], 'group_id' => $group['id']));
                $log_msg .= $more . "group_add[" . $group['name'] . "]";
                $more = ";";
                $exit_status += $status;
            }
        } else {
            if ($status == 0 and $rows == 1) {
                list($status, $rows) = db_delete_records($onadb, 'group_assignments', array('user_id' => $user['id'], 'group_id' => $group['id']));
                $log_msg .= $more . "group_del[" . $group['name'] . "]";
                $more = ";";
                $exit_status += $status;
            }
        }
    }
    // If the module returned an error code display a popup warning
    if ($status) {
        $js .= "alert('Save failed: " . trim($self['error']) . "');";
    } else {
        // only print to logfile if a change has been made to the record
        if ($more != '') {
            printmsg($self['error'], 0);
            printmsg($log_msg, 0);
        }
        $js .= "removeElement('{$window_name}');";
        $js .= "xajax_window_submit('app_user_list', xajax.getFormValues('app_user_list_filter_form'), 'display_list');";
    }
    // Return some javascript to the browser
    $response->addScript($js);
    return $response->getXML();
}
Example #10
0
function ws_save($window_name, $form = '')
{
    global $conf, $self, $onadb;
    // Check permissions
    if (!auth('user_admin')) {
        $response = new xajaxResponse();
        $response->addScript("alert('Permission denied!');");
        return $response->getXML();
    }
    // Instantiate the xajaxResponse object
    $response = new xajaxResponse();
    $js = '';
    // Validate input
    if (!$form['name']) {
        $js .= "alert('Error! All fields are required!');";
        $response->addScript($js);
        return $response->getXML();
    }
    if (!preg_match('/^[A-Za-z0-9.\\-_ ]+$/', $form['name'])) {
        $js .= "alert('Invalid group name! Valid characters: A-Z 0-9 .-_ and space');";
        $response->addScript($js);
        return $response->getXML();
    }
    //MP: zero out the level for now
    //TODO: fix or remove level at some point
    $form['level'] = 0;
    // Create a new record?
    if (!$form['id']) {
        list($status, $rows) = db_insert_record($onadb, 'groups', array('name' => $form['name'], 'description' => $form['description'], 'level' => $form['level']));
        if ($status or !$rows) {
            $self['error'] = "ERROR => group_edit add ws_save()  SQL Query failed: " . $self['error'];
            printmsg($self['error'], 0);
        } else {
            $self['error'] = "INFO => Group ADDED: {$form['name']} ";
            printmsg($self['error'], 0);
        }
    } else {
        list($status, $rows, $record) = db_get_record($onadb, 'groups', array('id' => $form['id']));
        if ($rows != 1 or $record['id'] != $form['id']) {
            $js .= "alert('Error! The record requested could not be loaded from the database!');";
            $response->addScript($js);
            return $response->getXML();
        }
        list($status, $rows) = db_update_record($onadb, 'groups', array('id' => $form['id']), array('name' => $form['name'], 'description' => $form['description']));
        if ($status or !$rows) {
            $self['error'] = "ERROR => group_edit update ws_save()  SQL Query failed: " . $self['error'];
            printmsg($self['error'], 0);
        } else {
            list($status, $rows, $new_record) = db_get_record($onadb, 'groups', array('id' => $form['id']));
            // Return the success notice
            $self['error'] = "INFO => Group UPDATED:{$record['id']}: {$record['name']}";
            $log_msg = "INFO => Group UPDATED:{$record['id']}: ";
            $more = "";
            foreach (array_keys($record) as $key) {
                if ($record[$key] != $new_record[$key]) {
                    $log_msg .= $more . $key . "[" . $record[$key] . "=>" . $new_record[$key] . "]";
                    $more = ";";
                }
            }
            // only print to logfile if a change has been made to the record
            if ($more != '') {
                printmsg($self['error'], 0);
                printmsg($log_msg, 0);
            }
        }
    }
    // If the module returned an error code display a popup warning
    if ($status) {
        $js .= "alert('Save failed. Contact the webmaster if this problem persists.');";
    } else {
        $js .= "removeElement('{$window_name}');";
        $js .= "xajax_window_submit('app_group_list', xajax.getFormValues('app_group_list_filter_form'), 'display_list');";
    }
    // Insert the new table into the window
    $response->addScript($js);
    return $response->getXML();
}
Example #11
0
function load_module($name = '')
{
    global $conf, $self, $onadb;
    if (!$name) {
        $self['error'] = "ERROR => load_module() No module specified!";
        return 1;
    }
    // If the module is already loaded, return success
    if (function_exists($name)) {
        return 0;
    }
    // Make sure we're connected to the DB
    // require_once($conf['inc_functions_db']);
    // Use cache if possible
    if (!is_array($self['cache']['modules']) or !array_key_exists('get_module_list', $self['cache']['modules'])) {
        // Get a list of the valid "modules" and their descriptions.
        require_once $conf['dcm_module_dir'] . '/get_module_list.inc.php';
        list($status, $self['cache']['modules']) = get_module_list('type=array');
    }
    // Make sure the user requested a valid "module"
    if (!array_key_exists($name, $self['cache']['modules'])) {
        // Otherwise print an error
        $self['error'] = "ERROR => The requested module is not valid!";
        return 1;
    }
    // Make sure the include file containing the function(s)/module(s) requested exists..
    // We have to find out which file it's in.
    list($status, $rows, $module) = db_get_record($onadb, 'dcm_module_list', array('name' => $name));
    if ($status or $rows != 1) {
        $self['error'] = 'ERROR => The specified module does not exist';
        return 1;
    }
    $file = $conf['dcm_module_dir'] . '/' . $module['file'];
    if (!is_file($file)) {
        // Otherwise print an error
        $self['error'] = "ERROR => The include file ({$file}) for the {$name} module doesn't exist!";
        return 1;
    }
    // Include the file
    // The file should define a function called generate_config() to which we pass a node-name,
    // and receive a configuration file.
    require_once $file;
    // Test that the module function existed in the file we just loaded
    if (!function_exists($name)) {
        $self['error'] = "ERROR => The module function {$name} doesn't exist in file: {$file}";
        return 1;
    }
    return 0;
}
Example #12
0
function subnet_nextip($options = "")
{
    global $conf, $self, $onadb;
    // Version - UPDATE on every edit!
    $version = '1.00';
    printmsg('DEBUG => subnet_del(' . $options . ') called', 3);
    // Parse incoming options string to an array
    $options = parse_options($options);
    // Sanitize options[commit] (default is no)
    $options['commit'] = sanitize_YN($options['commit'], 'N');
    // Return the usage summary if we need to
    if ($options['help'] or !$options['subnet']) {
        // NOTE: Help message lines should not exceed 80 characters for proper display on a console
        $self['error'] = 'ERROR => Insufficient parameters';
        return array(1, <<<EOM

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

  Synopsis: subnet_nextip [KEY=VALUE] ...

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

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


EOM
);
    }
    // Find the subnet record we're deleting
    list($status, $rows, $subnet) = ona_find_subnet($options['subnet']);
    if ($status or !$rows) {
        $self['error'] = "ERROR => Subnet not found";
        return array(2, $self['error'] . "\n");
    }
    // Create a few variables that will be handy later
    $num_ips = 0xffffffff - $subnet['ip_mask'];
    $last_ip = $subnet['ip_addr'] + $num_ips - 1;
    // check that offset is a number
    if (isset($options['offset']) and !is_numeric($options['offset'])) {
        $self['error'] = "ERROR => Offset must be a numeric number";
        return array(3, $self['error'] . "\n");
    } else {
        $offsetmsg = " beyond offset {$options['offset']}";
    }
    // make sure the offset does not extend beyond the specified subnet
    if ($options['offset'] >= $num_ips - 1) {
        $self['error'] = "ERROR => Offset extends beyond specified subnet boundary";
        return array(4, $self['error'] . "\n");
    }
    if (!isset($options['output'])) {
        $options['output'] = '1';
    } else {
        if ($options['output'] != 'dotted' && $options['output'] != 'numeric') {
            $self['error'] = "ERROR => Output option must be 'dotted' or 'numeric'";
            return array(5, $self['error'] . "\n");
        }
    }
    // Find the first number based on our subnet and offset
    $ip = $subnet['ip_addr'] + $options['offset'];
    // Make sure we skip past the subnet IP to the first usable IP
    if ($ip == $subnet['ip_addr']) {
        $ip++;
    }
    // Start looping through our IP addresses until we find an available one
    while ($ip <= $last_ip) {
        // Find out if the ip is used in an interface
        list($status, $rows, $interfaces) = db_get_records($onadb, 'interfaces', array('ip_addr' => $ip));
        // If we find a free address.. check that it is not in a DHCP pool
        if (!$rows) {
            list($status, $rows, $pool) = db_get_record($onadb, 'dhcp_pools', "{$ip} >= ip_addr_start AND {$ip} <= ip_addr_end");
            if ($rows) {
                $ip = $pool['ip_addr_end'];
            } else {
                break;
            }
        }
        $ip++;
        // increment by one and check again
    }
    // If we checked all the IPs, make sure we are not on the broadcast IP of the subnet
    if ($ip == $last_ip + 1) {
        $self['error'] = "ERROR => No available IP addresses found on subnet{$offsetmsg}";
        return array(5, $self['error'] . "\n");
    }
    // return the IP
    return array(0, ip_mangle($ip, $options['output']) . "\n");
}
Example #13
0
function dhcp_pool_modify($options = "")
{
    // The important globals
    global $conf, $self, $onadb;
    // Version - UPDATE on every edit!
    $version = '1.03';
    printmsg("DEBUG => dhcp_pool_modify({$options}) called", 3);
    // Parse incoming options string to an array
    $options = parse_options($options);
    // Return the usage summary if we need to
    if ($options['help'] or !($options['pool'] and ($options['set_failover_group'] or $options['set_start'] or $options['set_end'] or $options['set_llength'] or $options['set_lgrace'] or $options['set_lrenewal'] or $options['set_lrebind']))) {
        // 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_pool_modify-v{$version}
Updates a dhcp pool in the database pointing to the specified identifier

  Synopsis: dhcp_pool_modify [KEY=VALUE] ...

  Where:
    pool=ID                             Table ID for the pool

  Optional:
    set_failover_group=ID               group identifier
    set_server=NAME[.DOMAIN] or ID      server identifier
    set_start=IP                        Start ip address of pool
    set_end=IP                          End IP of pool
    set_llength=NUMBER                  Lease Time. Default ({$conf['dhcp_pool']['llength']})
    set_lgrace=NUMBER                   Lease Grace Period. Default ({$conf['dhcp_pool']['lgrace']})
    set_lrenewal=NUMBER                 Lease Renewal. Default ({$conf['dhcp_pool']['lrenewal']})
    set_lrebind=NUMBER                  Lease Rebind. Default ({$conf['dhcp_pool']['lrebind']})



EOM
);
    }
    // get the existing pool to edit
    list($status, $rows, $pool) = db_get_record($onadb, 'dhcp_pools', array('id' => $options['pool']));
    if (!$rows) {
        printmsg("DEBUG => Unable to find the DHCP pool record using id: {$options['id']}!", 3);
        $self['error'] = "ERROR => Unable to find a pool using id: {$options['pool']}";
        return array(1, $self['error'] . "\n");
    }
    // set the pool id in the set variable
    $SET['id'] = $pool['id'];
    // NOTE: currently modify pool does not allow you to change subnets
    // Get subnet info..
    list($status, $rows, $subnet) = ona_find_subnet($pool['subnet_id']);
    $SET['subnet_id'] = $subnet['id'];
    // make sure that the start address is actually part of an existing subnet
    if ($options['set_start']) {
        list($status, $rows, $subnetstart) = ona_find_subnet(ip_mangle($options['set_start'], 'dotted'));
        if (!$rows) {
            printmsg("DEBUG => Unable to find a subnet related to starting address ({$options['set_start']})!", 3);
            $self['error'] = "ERROR => Unable to find a subnet related to your starting address of {$options['set_start']}.";
            return array(1, $self['error'] . "\n");
        }
        if ($subnetstart['id'] != $pool['subnet_id']) {
            printmsg("DEBUG => The starting address ({$options['set_start']}) is not on the same subnet of the pool ({$pool['id']}) you are editing!", 3);
            $self['error'] = "ERROR => The starting address ({$options['set_start']}) is not on the same subnet of the pool ({$pool['id']}) you are editing!";
            return array(1, $self['error'] . "\n");
        }
    }
    // make sure that the end address is actually part of an existing subnet
    if ($options['set_end']) {
        list($status, $rows, $subnetend) = ona_find_subnet(ip_mangle($options['set_end'], 'dotted'));
        if (!$rows) {
            printmsg("DEBUG => Unable to find a subnet related to ending address ({$options['set_end']})!", 3);
            $self['error'] = "ERROR => Unable to find a subnet related to your ending address of {$options['set_end']}.";
            return array(1, $self['error'] . "\n");
        }
        if ($subnetend['id'] != $pool['subnet_id']) {
            printmsg("DEBUG => The ending address ({$options['set_end']}) is not on the same subnet of the pool ({$pool['id']}) you are editing!", 3);
            $self['error'] = "ERROR => The ending address ({$options['set_end']}) is not on the same subnet of the pool ({$pool['id']}) you are editing!";
            return array(1, $self['error'] . "\n");
        }
    }
    // Assign which failover group to use
    if ($options['set_failover_group'] == 0) {
        $desc = 'Not using a failover group';
        $SET['dhcp_failover_group_id'] = 0;
    } else {
        list($status, $rows, $fg) = ona_get_dhcp_failover_group_record(array('id' => $options['set_failover_group']));
        if (!$fg['id']) {
            printmsg("DEBUG => The failover_group specified ({$options['set_failover_group']}) does not exist", 3);
            $self['error'] = "ERROR => The failover_group specified ({$options['set_failover_group']}) does not exist!";
            return array(4, $self['error'] . "\n");
        }
        // get the server names for the two servers
        list($fail_host1, $fail_zone1) = ona_find_host($fg['primary_server_id']);
        list($fail_host2, $fail_zone2) = ona_find_host($fg['secondary_server_id']);
        $desc = $fail_host1['fqdn'] . '/' . $fail_host2['fqdn'];
        $SET['dhcp_failover_group_id'] = $fg['id'];
    }
    // check that start and end are not the same
    //if ($options['set_start'] and $options['set_end'] and $options['set_start'] == $options['set_end']) {
    //    printmsg("DEBUG => The start and end IP addresses (" . ip_mangle($options['set_start'],'dotted') . ") cannot be the same!",3);
    //    $self['error'] = "ERROR => The start and end IP addresses (" . ip_mangle($options['set_start'],'dotted') . ") cannot be the same!";
    //    return(array(2, $self['error'] . "\n"));
    //}
    if ($options['set_start']) {
        $start_dec = ip_mangle($options['set_start'], 'numeric');
    } else {
        $start_dec = $pool['ip_addr_start'];
    }
    if ($options['set_end']) {
        $end_dec = ip_mangle($options['set_end'], 'numeric');
    } else {
        $end_dec = $pool['ip_addr_end'];
    }
    $net_end = 4294967295 - $subnet['ip_mask'] + $subnet['ip_addr'];
    // Validate that the IP address supplied isn't the base or broadcast of the subnet
    if ($start_dec == $subnet['ip_addr'] or $end_dec == $subnet['ip_addr']) {
        printmsg("DEBUG => IP address can't be a subnet's base address (" . ip_mangle($subnet['ip_addr'], 'dotted') . ")!", 3);
        $self['error'] = "ERROR => IP address can't be a subnet's base address (" . ip_mangle($subnet['ip_addr'], 'dotted') . ")!";
        return array(7, $self['error'] . "\n");
    }
    if ($start_dec == $net_end or $end_dec == $net_end) {
        printmsg("DEBUG => IP address can't be a subnet's broadcast address (" . ip_mangle($net_end, 'dotted') . ")!", 3);
        $self['error'] = "ERROR => IP address can't be the subnet broadcast address(" . ip_mangle($net_end, 'dotted') . ")!";
        return array(8, $self['error'] . "\n");
    }
    // check that start is not after the end
    if ($start_dec > $end_dec) {
        printmsg("DEBUG => The start IP addresses (" . ip_mangle($start_dec, 'dotted') . ") falls after the end IP address (" . ip_mangle($end_dec, 'dotted') . ")!", 3);
        $self['error'] = "ERROR => The start IP addresses (" . ip_mangle($start_dec, 'dotted') . ") falls after the end IP address(" . ip_mangle($end_dec, 'dotted') . ")!";
        return array(2, $self['error'] . "\n");
    }
    // check for existing hosts inside the pool range
    list($status, $rows, $interface) = db_get_records($onadb, 'interfaces', 'subnet_id = ' . $subnet['id'] . ' AND ip_addr BETWEEN ' . $start_dec . ' AND ' . $end_dec, '', 0);
    if ($rows) {
        printmsg("DEBUG => IP conflict: Specified range (" . ip_mangle($start_dec, 'dotted') . "-" . ip_mangle($end_dec, 'dotted') . ") encompasses {$rows} host(s)!", 3);
        $self['error'] = "ERROR => IP conflict: Specified range (" . ip_mangle($start_dec, 'dotted') . "-" . ip_mangle($end_dec, 'dotted') . ") encompasses {$rows} host(s)";
        return array(4, $self['error'] . "\n");
    }
    // *** Check to see if the new pool overlaps any existing pools *** //
    // Look for overlaps like this (where new pool address starts inside an existing pool):
    //            [ -- new pool -- ]
    //    [ -- old pool --]
    list($status, $rows, $tmp) = db_get_record($onadb, 'dhcp_pools', 'id != ' . $SET['id'] . ' AND ' . $start_dec . ' BETWEEN ip_addr_start AND ip_addr_end');
    if ($rows != 0) {
        printmsg("DEBUG =>  Pool address conflict: New pool (" . ip_mangle($start_dec, 'dotted') . "-" . ip_mangle($end_dec, 'dotted') . ") starts inside an existing pool!", 3);
        $self['error'] = "ERROR => Pool address conflict! New pool (" . ip_mangle($start_dec, 'dotted') . "-" . ip_mangle($end_dec, 'dotted') . ") starts inside an existing pool.";
        return array(5, $self['error'] . "\n" . "INFO  => Conflicting pool record ID: {$tmp['id']}\n");
    }
    // Look for overlaps like this (where the new pool ends inside an existing pool):
    //    [ -- new pool -- ]
    //           [ -- old pool --]
    list($status, $rows, $tmp) = db_get_record($onadb, 'dhcp_pools', 'id != ' . $SET['id'] . ' AND ' . $end_dec . ' BETWEEN ip_addr_start AND ip_addr_end');
    if ($rows != 0) {
        printmsg("DEBUG =>  Pool address conflict: New pool (" . ip_mangle($start_dec, 'dotted') . "-" . ip_mangle($end_dec, 'dotted') . ") ends inside an existing pool!", 3);
        $self['error'] = "ERROR => Pool address conflict! New pool (" . ip_mangle($start_dec, 'dotted') . "-" . ip_mangle($end_dec, 'dotted') . ") ends inside an existing pool.";
        return array(6, $self['error'] . "\n" . "INFO  => Conflicting pool record ID: {$tmp['id']}\n");
    }
    // Look for overlaps like this (where the new pool entirely overlaps an existing pool):
    //    [ -------- new pool --------- ]
    //           [ -- old pool --]
    list($status, $rows, $tmp) = db_get_record($onadb, 'dhcp_pools', 'id != ' . $SET['id'] . ' AND (ip_addr_start BETWEEN ' . $start_dec . ' AND ' . $end_dec . ' OR ip_addr_end BETWEEN ' . $start_dec . ' AND ' . $end_dec . ')');
    if ($rows != 0) {
        printmsg("DEBUG =>  Pool address conflict: New pool (" . ip_mangle($start_dec, 'dotted') . "-" . ip_mangle($end_dec, 'dotted') . ") would encompass an existing pool!", 3);
        $self['error'] = "ERROR => Pool address conflict! New pool (" . ip_mangle($start_dec, 'dotted') . "-" . ip_mangle($end_dec, 'dotted') . ") would encompass an existing pool.";
        return array(7, $self['error'] . "\n" . "INFO  => Conflicting pool record ID: {$tmp['id']}\n");
    }
    // Check permissions
    if (!auth('advanced') or !authlvl($subnet['lvl'])) {
        $self['error'] = "Permission denied!";
        printmsg($self['error'], 0);
        return array(8, $self['error'] . "\n");
    }
    // define the remaining entries
    if (array_key_exists('set_lgrace', $options)) {
        $SET['lease_grace_period'] = $options['set_lgrace'];
    }
    if (array_key_exists('set_llength', $options)) {
        $SET['lease_length'] = $options['set_llength'];
    }
    if (array_key_exists('set_lrenewal', $options)) {
        $SET['lease_renewal_time'] = $options['set_lrenewal'];
    }
    if (array_key_exists('set_lrebind', $options)) {
        $SET['lease_rebind_time'] = $options['set_lrebind'];
    }
    // Set the IPs if you got this far
    $SET['ip_addr_start'] = $start_dec;
    $SET['ip_addr_end'] = $end_dec;
    // Get the DHCP pool record before updating (logging)
    list($status, $rows, $original_pool) = ona_get_dhcp_pool_record(array('id' => $SET['id']));
    // Update the record
    list($status, $rows) = db_update_record($onadb, 'dhcp_pools', array('id' => $SET['id']), $SET);
    if ($status or !$rows) {
        $self['error'] = "ERROR => dhcp_pool_modify() SQL Query failed: " . $self['error'];
        printmsg($self['error'], 0);
        return array(6, $add_to_error . $self['error'] . "\n");
    }
    $success_start = ip_mangle($SET['ip_addr_start'], 'dotted');
    $success_end = ip_mangle($SET['ip_addr_end'], 'dotted');
    // Get the DHCP pool record after updating (logging)
    list($status, $rows, $new_pool) = ona_get_dhcp_pool_record(array('id' => $SET['id']));
    // Return the success notice
    $self['error'] = "INFO => DHCP pool UPDATED:{$original_pool['id']}: {$success_start}-{$success_end} on {$subnet['name']}.";
    $log_msg = "INFO => DHCP pool UPDATED:{$original_pool['id']}: ";
    $more = "";
    foreach (array_keys($original_pool) as $key) {
        if ($original_pool[$key] != $new_pool[$key]) {
            $log_msg .= $more . $key . "[" . $original_pool[$key] . "=>" . $new_pool[$key] . "]";
            $more = ";";
        }
    }
    // only print to logfile if a change has been made to the record
    if ($more != '') {
        printmsg($self['error'], 0);
        printmsg($log_msg, 0);
    }
    return array(0, $add_to_error . $self['error'] . "\n");
}
Example #14
0
function ws_change_user_password($window_name, $form)
{
    global $conf, $self, $onadb;
    $username = $_SESSION['ona']['auth']['user']['username'];
    // Instantiate the xajaxResponse object
    $response = new xajaxResponse();
    $js = "el('passchangemsg').innerHTML = '<span style=\"color: green;\">Changed!</span>'";
    $exit_status = 0;
    // Validate the userid was passed and is "clean"
    if (!preg_match('/^[A-Za-z0-9.\\-_]+$/', $username)) {
        $js = "el('passchangemsg').innerHTML = 'Invalid username format';";
        $response->addScript($js);
        return $response->getXML();
    }
    list($status, $rows, $user) = db_get_record($onadb, 'users', "username LIKE '{$username}'");
    if (!$rows) {
        $js = "el('passchangemsg').innerHTML = 'Unknown user';";
        // Return some javascript to the browser
        $response->addScript($js);
        return $response->getXML();
    }
    if ($user['password'] != $form['old']) {
        $js = "el('passchangemsg').innerHTML = 'Password incorrect (old)';";
        // Return some javascript to the browser
        $response->addScript($js);
        return $response->getXML();
    }
    if ($form['new1'] != $form['new2']) {
        $js = "el('passchangemsg').innerHTML = 'New passwords dont match.';";
        // Return some javascript to the browser
        $response->addScript($js);
        return $response->getXML();
    }
    list($status, $rows) = db_update_record($onadb, 'users', array('username' => $username), array('password' => $form['new2']));
    // If the module returned an error code display a popup warning
    if ($status) {
        $js = "alert('Save failed: " . trim($self['error']) . "');";
    }
    if ($js) {
        $response->addScript($js);
    }
    return $response->getXML();
}
Example #15
0
function ws_display_list($window_name, $form)
{
    global $conf, $self, $mysql;
    global $font_family, $color, $style, $images;
    // Instantiate the xajaxResponse object
    $response = new xajaxResponse();
    // Make sure they're logged in
    if (!loggedIn()) {
        return $response->getXML();
    }
    // If the user supplied an array in a string, build the array and store it in $form
    $form = parse_options_string($form);
    // Find out what page we're on
    $page = 1;
    if ($form['page'] and is_numeric($form['page'])) {
        $page = $form['page'];
    }
    printmsg("INFO => Displaying user list page: {$page} client url: {$_SESSION['auth']['client']['url']}", 0);
    // Calculate the SQL query offset (based on the page being displayed)
    $offset = $conf['search_results_per_page'] * ($page - 1);
    if ($offset == 0) {
        $offset = -1;
    }
    $where = "`client_id` = {$_SESSION['auth']['client']['id']} AND `active` = 1";
    if (is_array($form) and $form['filter']) {
        $where .= ' AND `username` LIKE ' . $mysql->qstr('%' . $form['filter'] . '%');
    }
    // Get our employees
    list($status, $rows, $records) = db_get_records($mysql, 'users', $where, 'username', $conf['search_results_per_page'], $offset);
    // If we got less than serach_results_per_page, add the current offset to it
    // so that if we're on the last page $rows still has the right number in it.
    if ($rows > 0 and $rows < $conf['search_results_per_page']) {
        $rows += $conf['search_results_per_page'] * ($page - 1);
    } else {
        if ($rows >= $conf['search_results_per_page']) {
            list($status, $rows, $tmp) = db_get_records($mysql, 'users', $where, '', 0);
        }
    }
    $count = $rows;
    // Add a table header
    $html = <<<EOL
    
    <!-- Results Table -->
    <table id="{$form['form_id']}_host_list" class="list-box" cellspacing="0" border="0" cellpadding="0" width="100%">
        
        <!-- Table Header -->
        <tr>
            <td class="list-header" align="center" style="border-right: 1px solid {$color['border']};">Username</td>
            <td class="list-header" align="center" style="border-right: 1px solid {$color['border']};">Full Name</td>
            <td class="list-header" align="center" style="border-right: 1px solid {$color['border']};">Company</td>
            <td class="list-header" align="center" style="border-right: 1px solid {$color['border']};">Admin</td>
            <td class="list-header" align="center">&nbsp</td>
        </tr>
        
EOL;
    // Loop through and display the records
    foreach ($records as $record) {
        list($status, $rows, $client) = db_get_record($mysql, 'clients', array('id' => $record['client_id']));
        $record['company_name'] = $client['company_name'];
        // Escape data for display in html
        foreach (array_keys($record) as $key) {
            $record[$key] = htmlentities($record[$key], ENT_QUOTES, $conf['php_charset']);
        }
        // If the user is an admin, set some extra html
        $admin_html = "";
        if (empty($perm)) {
            list($status, $rows, $perm) = db_get_record($mysql, 'permissions', array('name' => 'admin'));
        }
        list($status, $rows, $acl) = db_get_record($mysql, 'acl', array('user_id' => $record['id'], 'perm_id' => $perm['id']));
        if ($acl['id']) {
            $admin_html = "<img src=\"{$images}/silk/tick.png\" border=\"0\">";
        }
        $html .= <<<EOL
        <tr onMouseOver="this.className='row-highlight';" onMouseOut="this.className='row-normal';">
            
            <td class="list-row">
                <a title="Edit"
                   class="act"
                   onClick="xajax_window_submit('user_edit', '{$record['id']}', 'editor');"
                >{$record['username']}</a>&nbsp;
            </td>
            
            <td class="list-row" align="left">
                {$record['fname']} {$record['lname']}&nbsp;
            </td>
            
            <td class="list-row" align="left">
                {$record['company_name']}&nbsp;
            </td>
            
            <td class="list-row" align="left">
                {$admin_html}&nbsp;
            </td>
            
            <td class="list-row" align="right">
                <a title="Edit"
                    class="act"
                    onClick="xajax_window_submit('user_edit', '{$record['id']}', 'editor');"
                ><img src="{$images}/silk/page_edit.png" border="0"></a>&nbsp;
            
                <a title="Delete employee"
                    class="act"
                    onClick="var doit=confirm('Are you sure you want to delete this employee?');
                            if (doit == true)
                                xajax_window_submit('{$window_name}', '{$record['id']}', 'delete');"
                ><img src="{$images}/silk/delete.png" border="0"></a>&nbsp;
            </td>
            
        </tr>
EOL;
    }
    $html .= <<<EOL
        <!-- Add a new employee -->
        <tr>
            <td colspan="99" class="list-header">
                <a title="New employee"
                   class="act"
                   onClick="xajax_window_submit('user_edit', ' ', 'editor');"
                ><img src="{$images}/silk/page_add.png" border="0"></a>&nbsp;
                
                <a title="New employee"
                   class="act"
                   onClick="xajax_window_submit('user_edit', ' ', 'editor');"
                >Add new employee</a>&nbsp;
            </td>
        </tr>
    
    </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 table into the window
    $response->addAssign("{$form['form_id']}_employees_count", "innerHTML", "({$count})");
    $response->addAssign("{$form['content_id']}", "innerHTML", $html);
    // $response->addScript($js);
    return $response->getXML();
}
Example #16
0
function dhcp_failover_group_del($options = "")
{
    global $conf, $self, $onadb;
    printmsg("DEBUG => dhcp_failover_group_del({$options}) called", 3);
    // Version - UPDATE on every edit!
    $version = '1.00';
    // 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['id']) {
        // 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_failover_group_del-v{$version}
Deletes a DHCP failover group from the database

  Synopsis: dhcp_failover_group_del [KEY=VALUE] ...

  Required:
    id=id               id of the failover group to delete

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


EOM
);
    }
    // Test that the group actually exists.
    list($status, $tmp_rows, $entry) = ona_get_dhcp_failover_group_record(array('id' => $options['id']));
    if (!$entry['id']) {
        printmsg("DEBUG => Unable to find a DHCP failover group record using id {$options['id']}!", 3);
        $self['error'] = "ERROR => Unable to find a DHCP failover group record using id {$options['id']}!";
        return array(4, $self['error'] . "\n");
    }
    // Debugging
    printmsg("DEBUG => DHCP failover group selected: {$entry['id']}", 3);
    // Display an error if pools are using this zone
    list($status, $rows, $pool) = db_get_record($onadb, 'dhcp_pools', array('id' => $entry['id']));
    if ($rows) {
        printmsg("DEBUG => DHCP failover group ({$entry['id']}) can't be deleted, it is in use on 1 or more pools!", 3);
        $self['error'] = "ERROR => DHCP failover group ({$entry['id']}) can't be deleted, it is in use on 1 or more pools!";
        return array(5, $self['error'] . "\n");
    }
    list($status, $rows, $pri_host) = ona_find_host($entry['primary_server_id']);
    list($status, $rows, $sec_host) = ona_find_host($entry['secondary_server_id']);
    // If "commit" is yes, delete the record
    if ($options['commit'] == 'Y') {
        // Check permissions
        if (!auth('advanced')) {
            $self['error'] = "Permission denied!";
            printmsg($self['error'], 0);
            return array(10, $self['error'] . "\n");
        }
        // Delete actual zone
        list($status, $rows) = db_delete_records($onadb, 'dhcp_failover_groups', array('id' => $entry['id']));
        if ($status) {
            $self['error'] = "ERROR => dhcp_failover_group_del() SQL Query failed: {$self['error']}";
            printmsg($self['error'], 0);
            return array(9, $self['error'] . "\n");
        }
        // Return the success notice
        $self['error'] = "INFO => DHCP failover group DELETED: {$entry['id']} => PRI:{$pri_host['fqdn']} SEC:{$sec_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 deleted:

     NAME:  {$entry['id']}
  PRIMARY:  {$pri_host['fqdn']}
SECONDARY:  {$sec_host['fqdn']}


EOL;
    return array(6, $text);
}
function ws_editor($window_name, $form = '')
{
    global $conf, $self, $onadb;
    global $font_family, $color, $style, $images;
    // Check permissions
    if (!auth('advanced')) {
        $response = new xajaxResponse();
        $response->addScript("alert('Permission denied!');");
        return $response->getXML();
    }
    // Set a few parameters for the "results" window we're about to create
    $window = array('title' => 'Custom Attribute Editor', 'html' => '', 'js' => '');
    $window['js'] .= <<<EOL
        /* Put a minimize icon in the title bar */
        el('{$window_name}_title_r').innerHTML =
            '&nbsp;<a onClick="toggle_window(\\'{$window_name}\\');" title="Minimize window" style="cursor: pointer;"><img src="{$images}/icon_minimize.gif" border="0" /></a>' +
            el('{$window_name}_title_r').innerHTML;

        /* Put a help icon in the title bar */
        el('{$window_name}_title_r').innerHTML =
            '&nbsp;<a href="{$_ENV['help_url']}{$window_name}" target="null" title="Help" style="cursor: pointer;"><img src="{$images}/silk/help.png" border="0" /></a>' +
            el('{$window_name}_title_r').innerHTML;
EOL;
    // If we got type, load it for display
    $overwrite = 'no';
    if (is_numeric($form)) {
        list($status, $rows, $record) = db_get_record($onadb, 'custom_attribute_types', array('id' => $form));
        if (!$status and $rows) {
            $overwrite = 'yes';
        }
    }
    // Escape data for display in html
    foreach (array_keys((array) $record) as $key) {
        $record[$key] = htmlentities($record[$key], ENT_QUOTES, $conf['php_charset']);
    }
    // Load some html into $window['html']
    $window['html'] .= <<<EOL

    <!-- Simple class types Edit Form -->
    <form id="custom_attribute_type_edit_form" onSubmit="return false;">
    <input name="id" type="hidden" value="{$record['id']}">
    <table cellspacing="0" border="0" cellpadding="0" style="background-color: {$color['window_content_bg']}; padding-left: 20px; padding-right: 20px; padding-top: 5px; padding-bottom: 5px;">
        <tr>
            <td align="right">
                Name
            </td>
            <td class="padding" align="left" width="100%">
                <input
                    name="cust_attrib_type_name"
                    alt="Custom Attribute Type Name"
                    value="{$record['name']}"
                    class="edit"
                    type="text"
                    size="30" maxlength="63"
                >
            </td>
        </tr>

        <tr>
            <td align="right">
                Field Validaiton Rule
            </td>
            <td class="padding" align="left" width="100%">
                <textarea
                    name="field_validation_rule"
                    alt="Field Validaiton Rule"
                    class="edit"
                    rows="2"
                    cols="40"
                >{$record['field_validation_rule']}</textarea>
            </td>
        </tr>

        <tr>
            <td align="right">
                Failed Rule Text
            </td>
            <td class="padding" align="left" width="100%">
                <textarea
                    name="failed_rule_text"
                    alt="Failed Rule Text"
                    class="edit"
                    rows="2"
                    cols="40"
                >{$record['failed_rule_text']}</textarea>
            </td>
        </tr>

        <tr>
            <td align="right">
                Notes
            </td>
            <td class="padding" align="left" width="100%">
                <textarea
                    name="notes"
                    alt="Notes"
                    class="edit"
                    rows="2"
                    cols="40"
                >{$record['notes']}</textarea>
            </td>
        </tr>

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

    </table>
    </form>

EOL;
    // Lets build a window and display the results
    return window_open($window_name, $window);
}
Example #18
0
function ws_editor($window_name, $form = '')
{
    global $conf, $self, $onadb;
    global $font_family, $color, $style, $images;
    // Check permissions
    if (!auth('advanced')) {
        $response = new xajaxResponse();
        $response->addScript("alert('Permission denied!');");
        return $response->getXML();
    }
    // Set a few parameters for the "results" window we're about to create
    $window = array('title' => 'Device Model Editor', 'html' => '', 'js' => '');
    $window['js'] .= <<<EOL
        /* Put a minimize icon in the title bar */
        el('{$window_name}_title_r').innerHTML =
            '&nbsp;<a onClick="toggle_window(\\'{$window_name}\\');" title="Minimize window" style="cursor: pointer;"><img src="{$images}/icon_minimize.gif" border="0" /></a>' +
            el('{$window_name}_title_r').innerHTML;

        /* Put a help icon in the title bar */
        el('{$window_name}_title_r').innerHTML =
            '&nbsp;<a href="{$_ENV['help_url']}{$window_name}" target="null" title="Help" style="cursor: pointer;"><img src="{$images}/silk/help.png" border="0" /></a>' +
            el('{$window_name}_title_r').innerHTML;
EOL;
    // If we got a device model, load it for display
    $overwrite = 'no';
    if (is_numeric($form)) {
        list($status, $rows, $record) = db_get_record($onadb, 'models', array('id' => $form));
        if (!$status and $rows) {
            $overwrite = 'yes';
        }
    }
    // Build manufacturer list
    // TODO: this needs to be made more efficent
    list($status, $rows, $manufacturer) = db_get_records($onadb, 'manufacturers', 'id >= 1', 'name');
    $manufacturer_list = '<option value="">&nbsp;</option>\\n';
    $manufacturer['name'] = htmlentities($manufacturer['name']);
    foreach ($manufacturer as $entry) {
        $selected = "";
        // If this entry matches the record you are editing, set it to selected
        if ($entry['id'] == $record['manufacturer_id']) {
            $selected = "SELECTED=\"selected\"";
        }
        if ($entry['id']) {
            $manufacturer_list .= "<option {$selected} value=\"{$entry['id']}\">{$entry['name']}</option>\n";
        }
    }
    // Escape data for display in html
    foreach (array_keys((array) $record) as $key) {
        $record[$key] = htmlentities($record[$key], ENT_QUOTES, $conf['php_charset']);
    }
    // Load some html into $window['html']
    $window['html'] .= <<<EOL

    <!-- Simple device models Edit Form -->
    <form id="device_model_edit_form" onSubmit="return false;">
    <input name="id" type="hidden" value="{$record['id']}">
    <table cellspacing="0" border="0" cellpadding="0" style="background-color: {$color['window_content_bg']}; padding-left: 20px; padding-right: 20px; padding-top: 5px; padding-bottom: 5px;">

        <tr>
            <td nowrap="yes" align="right">
                Manufacturer
            </td>
            <td class="padding" align="left" width="100%">
                <select id="manufacturer_id" name="manufacturer_id" class="edit" accesskey="m">
                    {$manufacturer_list}
                </select>
            </td>
        </tr>

        <tr>
            <td nowrap="yes" align="right">
                Model
            </td>
            <td class="padding" align="left" width="100%">
                <input
                    name="model_description"
                    alt="Device Model Description"
                    value="{$record['name']}"
                    class="edit"
                    type="text"
                    size="30" maxlength="30"
                >
            </td>
        </tr>

        <tr>
            <td nowrap="yes" align="right">
                SNMP sysobjectid
            </td>
            <td class="padding" align="left" width="100%">
                <input
                    name="snmp_sysobjectid"
                    alt="SNMP sysobjectid"
                    value="{$record['snmp_sysobjectid']}"
                    class="edit"
                    type="text"
                    size="30" maxlength="30"
                >
            </td>
        </tr>

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

    </table>
    </form>

EOL;
    // Lets build a window and display the results
    return window_open($window_name, $window);
}
Example #19
0
function host_del($options = "")
{
    global $conf, $self, $onadb;
    printmsg("DEBUG => host_del({$options}) called", 3);
    // Version - UPDATE on every edit!
    $version = '1.19';
    // Parse incoming options string to an array
    $options = parse_options($options);
    // Sanitize options[commit] (default is no)
    $options['commit'] = sanitize_YN($options['commit'], 'N');
    // Return the usage summary if we need to
    if ($options['help'] or !$options['host']) {
        // NOTE: Help message lines should not exceed 80 characters for proper display on a console
        $self['error'] = 'ERROR => Insufficient parameters';
        return array(1, <<<EOM

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

  Synopsis: host_del [KEY=VALUE] ...

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

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

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


EOM
);
    }
    // Find the host (and domain) record from $options['host']
    list($status, $rows, $host) = ona_find_host($options['host']);
    printmsg("DEBUG => host_del() Host: {$host['fqdn']} ({$host['id']})", 3);
    if (!$host['id']) {
        printmsg("DEBUG => Unknown host: {$host['fqdn']}", 3);
        $self['error'] = "ERROR => Unknown host: {$host['fqdn']}";
        return array(2, $self['error'] . "\n");
    }
    // Check permissions
    if (!auth('host_del') or !authlvl($host['LVL'])) {
        $self['error'] = "Permission denied!";
        printmsg($self['error'], 0);
        return array(10, $self['error'] . "\n");
    }
    // If "commit" is yes, delete the host
    if ($options['commit'] == 'Y') {
        $text = "";
        $add_to_error = "";
        $add_to_status = 0;
        // SUMMARY:
        //   Don't allow a delete if it is performing server duties
        //   Don't allow a delete if config text entries exist
        //   Delete Interfaces
        //   Delete interface cluster entries
        //   Delete dns records
        //   Delete custom attributes
        //   Delete DHCP entries
        //   Delete device record if it is the last host associated with it.
        //
        // IDEA: If it's the last host in a domain (maybe do the same for or a networks & vlans in the interface delete)
        //       It could just print a notice or something.
        // Check that it is the host is not performing server duties
        // FIXME: MP mostly fixed..needs testing
        $serverrow = 0;
        // check ALL the places server_id is used and remove the entry from server_b if it is not used
        list($status, $rows, $srecord) = db_get_record($onadb, 'dhcp_server_subnets', array('host_id' => $host['id']));
        if ($rows) {
            $serverrow++;
        }
        list($status, $rows, $srecord) = db_get_record($onadb, 'dhcp_failover_groups', array('primary_server_id' => $host['id']));
        if ($rows) {
            $serverrow++;
        }
        list($status, $rows, $srecord) = db_get_record($onadb, 'dhcp_failover_groups', array('secondary_server_id' => $host['id']));
        if ($rows) {
            $serverrow++;
        }
        if ($serverrow > 0) {
            printmsg("DEBUG => Host ({$host['fqdn']}) cannot be deleted, it is performing duties as a DHCP server!", 3);
            $self['error'] = "ERROR => Host ({$host['fqdn']}) cannot be deleted, it is performing duties as a DHCP server!";
            return array(5, $self['error'] . "\n");
        }
        // Check if host is a dns server
        $serverrow = 0;
        list($status, $rows, $srecord) = db_get_record($onadb, 'dns_server_domains', array('host_id' => $host['id']));
        if ($rows) {
            $serverrow++;
        }
        if ($serverrow > 0) {
            printmsg("DEBUG => Host ({$host['fqdn']}) cannot be deleted, it is performing duties as a DNS server!", 3);
            $self['error'] = "ERROR => Host ({$host['fqdn']}) cannot be deleted, it is performing duties as a DNS server!";
            return array(5, $self['error'] . "\n");
        }
        // Display an error if it has any entries in configurations
        list($status, $rows, $server) = db_get_record($onadb, 'configurations', array('host_id' => $host['id']));
        if ($rows) {
            printmsg("DEBUG => Host ({$host['fqdn']}) cannot be deleted, it has config archives!", 3);
            $self['error'] = "ERROR => Host ({$host['fqdn']}) cannot be deleted, it has config archives!";
            return array(5, $self['error'] . "\n");
        }
        // Delete interface(s)
        // get list for logging
        $clustcount = 0;
        $dnscount = 0;
        list($status, $rows, $interfaces) = db_get_records($onadb, 'interfaces', array('host_id' => $host['id']));
        // Cant delete if one of the interfaces is primary for a cluster
        foreach ($interfaces as $int) {
            list($status, $rows, $records) = db_get_records($onadb, 'interface_clusters', array('interface_id' => $int['id']));
            $clustcount = $clustcount + $rows;
        }
        if ($clustcount) {
            $self['error'] = "ERROR => host_del() An interface on this host is primary for some interface shares, delete the share or move the interface first.";
            printmsg($self['error'], 0);
            return array(5, $self['error'] . "\n");
        }
        // do the interface_cluster delete.  This just removes this host from the cluster, not the whole cluster itself
        // It will error out as well if this interface is the primary in the cluster
        list($status, $rows) = db_delete_records($onadb, 'interface_clusters', array('host_id' => $host['id']));
        if ($status) {
            $self['error'] = "ERROR => host_del() interface_cluster delete SQL Query failed: {$self['error']}";
            printmsg($self['error'], 0);
            return array(5, $self['error'] . "\n");
        }
        // log deletions
        printmsg("INFO => {$rows} Shared interface(s) DELETED from {$host['fqdn']}", 0);
        $add_to_error .= "INFO => {$rows} Shared interface(s) DELETED from {$host['fqdn']}\n";
        // Delete each DNS record associated with this hosts interfaces.
        //         foreach ($interfaces as $int) {
        //             // Loop through each dns record associated with this interface.
        //             list($status, $rows, $records) = db_get_records($onadb, 'dns', array('interface_id' => $int['id']));
        //             if ($rows) {
        //                 foreach($records as $record) {
        //                     // Run the module
        //                     list($status, $output) = run_module('dns_record_del', array('name' => $record['id'], 'type' => $record['type'], 'commit' => 'Y', 'delete_by_module' => 'Y'));
        //                     $add_to_error .= $output;
        //                     $add_to_status = $add_to_status + $status;
        //                 }
        //             }
        //         }
        // Delete messages
        // get list for logging
        list($status, $rows, $records) = db_get_records($onadb, 'messages', array('table_name_ref' => 'hosts', 'table_id_ref' => $host['id']));
        // do the delete
        list($status, $rows) = db_delete_records($onadb, 'messages', array('table_name_ref' => 'hosts', 'table_id_ref' => $host['id']));
        if ($status) {
            $self['error'] = "ERROR => host_del() message delete SQL Query failed: {$self['error']}";
            printmsg($self['error'], 0);
            return array(5, $self['error'] . "\n");
        }
        // log deletions
        printmsg("INFO => {$rows} Message(s) DELETED from {$host['fqdn']}", 0);
        $add_to_error .= "INFO => {$rows} Message(s) DELETED from {$host['fqdn']}\n";
        // Delete the interfaces.. this should delete dns names and other things associated with interfaces..
        foreach ($interfaces as $record) {
            // Run the module
            list($status, $output) = run_module('interface_del', array('interface' => $record['id'], 'commit' => 'on', 'delete_by_module' => 'Y'));
            $add_to_error .= $output;
            $add_to_status = $add_to_status + $status;
        }
        // Delete device record
        // Count how many hosts use this same device
        list($status, $rows, $records) = db_get_records($onadb, 'hosts', array('device_id' => $host['device_id']));
        // if device count is just 1 do the delete
        if ($rows == 1) {
            list($status, $rows) = db_delete_records($onadb, 'devices', array('id' => $host['device_id']));
            if ($status) {
                $self['error'] = "ERROR => host_del() device delete SQL Query failed: {$self['error']}";
                printmsg($self['error'], 0);
                return array(5, $add_to_error . $self['error'] . "\n");
            }
            // log deletions
            printmsg("INFO => Device record DELETED: [{$record['id']}] no remaining hosts using this device", 0);
        } else {
            printmsg("INFO => Device record NOT DELETED: [{$record['id']}] there are other hosts using this device.", 1);
        }
        // Delete tag entries
        list($status, $rows, $records) = db_get_records($onadb, 'tags', array('type' => 'host', 'reference' => $host['id']));
        $log = array();
        $i = 0;
        foreach ($records as $record) {
            $log[$i] = "INFO => Tag DELETED: {$record['name']} from {$host['fqdn']}";
            $i++;
        }
        //do the delete
        list($status, $rows) = db_delete_records($onadb, 'tags', array('type' => 'host', 'reference' => $host['id']));
        if ($status) {
            $self['error'] = "ERROR => host_del() Tag delete SQL Query failed: {$self['error']}";
            printmsg($self['error'], 0);
            return array(5, $add_to_error . $self['error'] . "\n");
        }
        //log deletions
        foreach ($log as $log_msg) {
            printmsg($log_msg, 0);
            $add_to_error .= $log_msg . "\n";
        }
        // Delete custom attribute entries
        // get list for logging
        list($status, $rows, $records) = db_get_records($onadb, 'custom_attributes', array('table_name_ref' => 'hosts', 'table_id_ref' => $host['id']));
        $log = array();
        $i = 0;
        foreach ($records as $record) {
            list($status, $rows, $ca) = ona_get_custom_attribute_record(array('id' => $record['id']));
            $log[$i] = "INFO => Custom Attribute DELETED: {$ca['name']} ({$ca['value']}) from {$host['fqdn']}";
            $i++;
        }
        //do the delete
        list($status, $rows) = db_delete_records($onadb, 'custom_attributes', array('table_name_ref' => 'hosts', 'table_id_ref' => $host['id']));
        if ($status) {
            $self['error'] = "ERROR => host_del() Custom attribute delete SQL Query failed: {$self['error']}";
            printmsg($self['error'], 0);
            return array(5, $add_to_error . $self['error'] . "\n");
        }
        //log deletions
        foreach ($log as $log_msg) {
            printmsg($log_msg, 0);
            $add_to_error .= $log_msg . "\n";
        }
        // Delete DHCP options
        // get list for logging
        list($status, $rows, $records) = db_get_records($onadb, 'dhcp_option_entries', array('host_id' => $host['id']));
        $log = array();
        $i = 0;
        foreach ($records as $record) {
            list($status, $rows, $dhcp) = ona_get_dhcp_option_entry_record(array('id' => $record['id']));
            $log[$i] = "INFO => DHCP entry DELETED: {$dhcp['display_name']}={$dhcp['value']} from {$host['fqdn']}";
            $i++;
        }
        // do the delete
        list($status, $rows) = db_delete_records($onadb, 'dhcp_option_entries', array('host_id' => $host['id']));
        if ($status) {
            $self['error'] = "ERROR => host_del() DHCP option entry delete SQL Query failed: {$self['error']}";
            printmsg($self['error'], 0);
            return array(5, $add_to_error . $self['error'] . "\n");
        }
        // log deletions
        foreach ($log as $log_msg) {
            printmsg($log_msg, 0);
            $add_to_error .= $log_msg . "\n";
        }
        // Delete the host
        list($status, $rows) = db_delete_records($onadb, 'hosts', array('id' => $host['id']));
        if ($status) {
            $self['error'] = "ERROR => host_del() host delete SQL Query failed: {$self['error']}";
            printmsg($self['error'], 0);
            return array(5, $add_to_error . $self['error'] . "\n");
        }
        // Return the success notice
        if ($add_to_status == 0) {
            $self['error'] = "INFO => Host DELETED: {$host['fqdn']}";
        }
        printmsg($self['error'], 0);
        return array($add_to_status, $add_to_error . $self['error'] . "\n");
    }
    //
    // We are just displaying records that would have been deleted
    //
    // SUMMARY:
    //   Display a warning if it is a server
    //   Display a warning if it has config text entries
    //   Display Interfaces
    //   Display dns records
    //   Display custom attributes
    //   Display DHCP entries
    // Otherwise just display the host record for the host we would have deleted
    $text = "Record(s) NOT DELETED (see \"commit\" option)\n" . "Displaying record(s) that would have been deleted:\n";
    // Display a warning if host is performing server duties
    list($status, $rows, $srecord) = db_get_record($onadb, 'dhcp_server_subnets', array('host_id' => $host['id']));
    if ($rows) {
        $text .= "\nWARNING!  This host is a DHCP server for {$rows} subnet(s)\n";
    }
    list($status, $rows, $srecord) = db_get_record($onadb, 'dns_server_domains', array('host_id' => $host['id']));
    if ($rows) {
        $text .= "\nWARNING!  This host is a DNS server for one or more domains!\n";
    }
    list($status, $rows, $srecord) = db_get_record($onadb, 'dhcp_failover_groups', array('primary_server_id' => $host['id']));
    if ($rows) {
        $text .= "\nWARNING!  This host is a server that is primary in a DHCP failover group\n";
    }
    list($status, $rows, $srecord) = db_get_record($onadb, 'dhcp_failover_groups', array('secondary_server_id' => $host['id']));
    if ($rows) {
        $text .= "\nWARNING!  This host is a server that is secondary in a DHCP failover group\n";
    }
    // Display a warning if it has any configurations
    list($status, $rows, $server) = db_get_record($onadb, 'configurations', array('host_id' => $host['id']));
    if ($rows) {
        $text .= "\nWARNING!  Host can not be deleted, it has config archives!\n";
    }
    if ($rows) {
        $text .= "\nWARNING!  Host will NOT be deleted, due to previous warnings!\n";
    }
    // Display the Host's complete record
    list($status, $tmp) = host_display("host={$host['id']}&verbose=N");
    $text .= "\n" . $tmp;
    // Display count of messages
    list($status, $rows, $records) = db_get_records($onadb, 'messages', array('table_name_ref' => 'hosts', 'table_id_ref' => $host['id']));
    if ($rows) {
        $text .= "\nASSOCIATED MESSAGE RECORDS ({$rows}):\n";
    }
    // Display associated interface(s)
    list($status, $int_rows, $interfaces) = db_get_records($onadb, 'interfaces', array('host_id' => $host['id']));
    // show the dns records associated
    foreach ($interfaces as $record) {
        list($status, $rows, $dnsrec) = db_get_records($onadb, 'dns', array('interface_id' => $record['id']));
        if ($rows) {
            $text .= "\nASSOCIATED DNS RECORDS ({$rows}) ON INTERFACE (" . ip_mangle($record['ip_addr'], 'dotted') . "):\n";
            foreach ($dnsrec as $rec) {
                // show AAAA or A type as needed
                if ($record['ip_addr'] > 4294967295 and $rec['type'] == 'A') {
                    $rec['type'] = 'AAAA';
                }
                $text .= "  TYPE: [ID:{$rec['id']}] {$rec['type']}, {$rec['name']} -> " . ip_mangle($record['ip_addr'], 'dotted') . "\n";
            }
        }
    }
    if ($int_rows) {
        $text .= "\nASSOCIATED INTERFACE RECORDS ({$int_rows}):\n";
    }
    foreach ($interfaces as $record) {
        $text .= "  [ID:{$record['id']}] " . ip_mangle($record['ip_addr'], 'dotted') . "\n";
    }
    // Display associated interface_clusters(s)
    list($status, $clust_rows, $interfaceclusters) = db_get_records($onadb, 'interface_clusters', array('host_id' => $host['id']));
    if ($clust_rows) {
        $text .= "\nASSOCIATED SHARED INTERFACE RECORDS ({$clust_rows}):\n";
    }
    foreach ($interfaceclusters as $record) {
        list($status, $rows, $int) = ona_get_interface_record(array('id' => $record['interface_id']));
        $text .= "  [ID:{$int['id']}] {$int['ip_addr_text']}\n";
    }
    // Display associated tags
    list($status, $rows, $records) = db_get_records($onadb, 'tags', array('type' => 'host', 'reference' => $host['id']));
    if ($rows) {
        $text .= "\nASSOCIATED TAG RECORDS ({$rows}):\n";
    }
    foreach ($records as $record) {
        $text .= "  {$record['name']}\n";
    }
    // Display associated custom attributes
    list($status, $rows, $records) = db_get_records($onadb, 'custom_attributes', array('table_name_ref' => 'hosts', 'table_id_ref' => $host['id']));
    if ($rows) {
        $text .= "\nASSOCIATED CUSTOM ATTRIBUTE RECORDS ({$rows}):\n";
    }
    foreach ($records as $record) {
        list($status, $rows, $ca) = ona_get_custom_attribute_record(array('id' => $record['id']));
        $text .= "  {$ca['name']} => {$ca['value']}\n";
    }
    // Display associated DHCP entries
    list($status, $rows, $records) = db_get_records($onadb, 'dhcp_option_entries', array('host_id' => $host['id']));
    if ($rows) {
        $text .= "\nASSOCIATED DHCP OPTION RECORDS ({$rows}):\n";
    }
    foreach ($records as $record) {
        list($status, $rows, $dhcp) = ona_get_dhcp_option_entry_record(array('id' => $record['id']));
        $text .= "  {$dhcp['display_name']} => {$dhcp['value']}\n";
    }
    return array(7, $text);
}
Example #20
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 hosts 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 HOST SEARCH ***
    //       FIND RESULT SET
    //
    // Start building the "where" clause for the sql query to find the hosts to display
    $where = "";
    $and = "";
    $orderby = "";
    $from = 'hosts h';
    // enable or disable wildcards
    $wildcard = '%';
    if ($form['nowildcard']) {
        $wildcard = '';
    }
    // DISPLAY ALL
    // MP: I dont think this is used.. remove it if you can
    if ($form['all_flag']) {
        $where .= $and . "h.id > 0";
        $and = " AND ";
    }
    // HOST ID
    if ($form['host_id']) {
        $where .= $and . "h.id = " . $onadb->qstr($form['host_id']);
        $and = " AND ";
    }
    // DEVICE ID
    if ($form['device_id']) {
        $where .= $and . "h.device_id = " . $onadb->qstr($form['device_id']);
        $and = " AND ";
    }
    // HOSTNAME
    if ($form['hostname']) {
        // Find the domain name piece of the hostname assuming it was passed in as an fqdn.
        // FIXME: MP this was taken from the ona_find_domain function. make that function have the option
        // to NOT return a default domain.
        // lets test out if it has a / in it to strip the view name portion
        $view['id'] = 0;
        if (strstr($form['hostname'], '/')) {
            list($dnsview, $form['hostname']) = explode('/', $form['hostname']);
            list($status, $viewrows, $view) = db_get_record($onadb, 'dns_views', array('name' => strtoupper($dnsview)));
            if (!$viewrows) {
                $view['id'] = 0;
            }
        }
        // Split it up on '.' and put it in an array backwards
        $parts = array_reverse(explode('.', $form['hostname']));
        // Find the domain name that best matches
        $name = '';
        $domain = array();
        foreach ($parts as $part) {
            if (!$rows) {
                if (!$name) {
                    $name = $part;
                } else {
                    $name = "{$part}.{$name}";
                }
                list($status, $rows, $record) = ona_get_domain_record(array('name' => $name));
                if ($rows) {
                    $domain = $record;
                }
            } else {
                list($status, $rows, $record) = ona_get_domain_record(array('name' => $part, 'parent_id' => $domain['id']));
                if ($rows) {
                    $domain = $record;
                }
            }
        }
        $withdomain = '';
        $hostname = $form['hostname'];
        // If you found a domain in the query, add it to the search, and strip the domain from the host portion.
        if (array_key_exists('id', $domain) and !$form['domain']) {
            $withdomain = "AND b.domain_id = {$domain['id']}";
            // Now find what the host part of $search is
            $hostname = str_replace(".{$domain['fqdn']}", '', $form['hostname']);
        }
        // If we have a hostname and a domain name then use them both
        if ($form['domain']) {
            list($status, $rows, $record) = ona_find_domain($form['domain']);
            if ($record['id']) {
                $withdomain = "AND b.domain_id = {$record['id']}";
            }
            // Now find what the host part of $search is
            $hostname = trim($form['hostname']);
        }
        // MP: Doing the many select IN statements was too slow.. I did this kludge:
        //  1. get a list of all the interfaces
        //  2. loop through the array and build a list of comma delimited host_ids to use in the final select
        list($status, $rows, $tmp) = db_get_records($onadb, 'interfaces a, dns b', "a.id = b.interface_id and b.name LIKE '{$wildcard}{$hostname}{$wildcard}' {$withdomain}");
        $commait = '';
        $hostids = '';
        foreach ($tmp as $item) {
            $hostids .= $commait . $item['host_id'];
            $commait = ',';
        }
        // Just look for the host itself
        list($status, $rows, $r) = ona_find_host($form['hostname']);
        if ($rows) {
            $hostids .= ',' . $r['id'];
        }
        // MP: this is the old, slow query for reference.
        //
        // TODO: MP this seems to be kinda slow (gee I wonder why).. look into speeding things up somehow.
        //       This also does not search for CNAME records etc.  only things with interface_id.. how to fix that issue.......?
        //        $where .= $and . "id IN (select host_id from interfaces where id in (SELECT interface_id " .
        //                                "  FROM dns " .
        //                                "  WHERE name LIKE '%{$hostname}%' {$withdomain} ))";
        // Trim off extra commas
        $hostids = trim($hostids, ",");
        // If we got a list of hostids from interfaces then use them
        if ($hostids) {
            $idqry = "h.id IN ({$hostids})";
        } else {
            $idqry = "";
        }
        $where .= $and . $idqry;
        $and = " AND ";
    }
    // DOMAIN
    if ($form['domain'] and !$form['hostname']) {
        // FIXME: does this clause work correctly?
        printmsg("FIXME: => Does \$form['domain'] work correctly in list_hosts.inc.php?", 2);
        // Find the domain name piece of the hostname.
        // FIXME: MP this was taken from the ona_find_domain function. make that function have the option
        // to NOT return a default domain.
        // Split it up on '.' and put it in an array backwards
        $parts = array_reverse(explode('.', $form['domain']));
        // Find the domain name that best matches
        $name = '';
        $domain = array();
        foreach ($parts as $part) {
            if (!$rows) {
                if (!$name) {
                    $name = $part;
                } else {
                    $name = "{$part}.{$name}";
                }
                list($status, $rows, $record) = ona_get_domain_record(array('name' => $name));
                if ($rows) {
                    $domain = $record;
                }
            } else {
                list($status, $rows, $record) = ona_get_domain_record(array('name' => $part, 'parent_id' => $domain['id']));
                if ($rows) {
                    $domain = $record;
                }
            }
        }
        if (array_key_exists('id', $domain)) {
            // Crappy way of writing the query but it makes it fast.
            $from = "(\nSELECT distinct a.*\nfrom hosts as a, interfaces as i, dns as d\nwhere a.id = i.host_id\nand i.id = d.interface_id\nand d.domain_id = " . $onadb->qstr($domain['id']) . "\n) h";
            $and = " AND ";
        }
    }
    // DOMAIN ID
    if ($form['domain_id'] and !$form['hostname']) {
        $where .= $and . "h.primary_dns_id IN ( SELECT id " . "  FROM dns " . "  WHERE domain_id = " . $onadb->qstr($form['domain_id']) . " )  ";
        $and = " AND ";
    }
    // MAC
    if ($form['mac']) {
        // Clean up the mac address
        $form['mac'] = strtoupper($form['mac']);
        $form['mac'] = preg_replace('/[^%0-9A-F]/', '', $form['mac']);
        // We do a sub-select to find interface id's that match
        $where .= $and . "h.id IN ( SELECT host_id " . "        FROM interfaces " . "        WHERE mac_addr LIKE " . $onadb->qstr($wildcard . $form['mac'] . $wildcard) . " ) ";
        $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 . "h.id IN ( SELECT host_id " . "        FROM interfaces " . "        WHERE ip_addr >= " . $onadb->qstr($ip) . " AND ip_addr <= " . $onadb->qstr($ip_end) . " )";
            $and = " AND ";
        }
    }
    // NOTES
    if ($form['notes']) {
        $where .= $and . "h.notes LIKE " . $onadb->qstr($wildcard . $form['notes'] . $wildcard);
        $and = " AND ";
    }
    // DEVICE MODEL
    if ($form['model_id']) {
        $where .= $and . "h.device_id in (select id from devices where device_type_id in (select id from device_types where model_id = {$form['model_id']}))";
        $and = " AND ";
    }
    if ($form['model']) {
        $where .= $and . "h.device_id in (select id from devices where device_type_id in (select id from device_types where model_id in (select id from models where name like '{$form['model']}')))";
        $and = " AND ";
    }
    // DEVICE TYPE
    if ($form['role']) {
        // Find model_id's that have a device_type_id of $form['role']
        list($status, $rows, $records) = db_get_records($onadb, 'roles', array('name' => $form['role']));
        // If there were results, add each one to the $where clause
        if ($rows > 0) {
            $where .= $and . " ( ";
            $and = " AND ";
            $or = "";
            foreach ($records as $record) {
                // Yes this is one freakin nasty query but it works.
                $where .= $or . "h.device_id in (select id from devices where device_type_id in (select id from device_types where role_id = " . $onadb->qstr($record['id']) . "))";
                $or = " OR ";
            }
            $where .= " ) ";
        }
    }
    // DEVICE MANUFACTURER
    if ($form['manufacturer']) {
        // Find model_id's that have a device_type_id of $form['manufacturer']
        if (is_numeric($form['manufacturer'])) {
            list($status, $rows, $records) = db_get_records($onadb, 'models', array('manufacturer_id' => $form['manufacturer']));
        } else {
            list($status, $rows, $manu) = db_get_record($onadb, 'manufacturers', array('name' => $form['manufacturer']));
            list($status, $rows, $records) = db_get_records($onadb, 'models', array('manufacturer_id' => $manu['id']));
        }
        // If there were results, add each one to the $where clause
        if ($rows > 0) {
            $where .= $and . " ( ";
            $and = " AND ";
            $or = "";
            foreach ($records as $record) {
                // Yes this is one freakin nasty query but it works.
                $where .= $or . "h.device_id in (select id from devices where device_type_id in (select id from device_types where model_id = " . $onadb->qstr($record['id']) . "))";
                $or = " OR ";
            }
            $where .= " ) ";
        }
    }
    // tag
    if ($form['tag_host']) {
        $where .= $and . "h.id in (select reference from tags where type like 'host' and name like " . $onadb->qstr($form['tag_host']) . ")";
        $and = " AND ";
    }
    // custom attribute type
    if ($form['custom_attribute_type']) {
        $where .= $and . "h.id in (select table_id_ref from custom_attributes where table_name_ref like 'hosts' and custom_attribute_type_id = (SELECT id FROM custom_attribute_types WHERE name = " . $onadb->qstr($form['custom_attribute_type']) . "))";
        $and = " AND ";
        $cavaluetype = "and custom_attribute_type_id = (SELECT id FROM custom_attribute_types WHERE name = " . $onadb->qstr($form['custom_attribute_type']) . ")";
    }
    // custom attribute value
    if ($form['ca_value']) {
        $where .= $and . "h.id in (select table_id_ref from custom_attributes where table_name_ref like 'hosts' {$cavaluetype} and value like " . $onadb->qstr($wildcard . $form['ca_value'] . $wildcard) . ")";
        $and = " AND ";
    }
    // LOCATION No.
    if ($form['location']) {
        list($status, $rows, $loc) = ona_find_location($form['location']);
        $where .= $and . "h.device_id in (select id from devices where location_id = " . $onadb->qstr($loc['id']) . ")";
        $and = " AND ";
    }
    // subnet ID
    if (is_numeric($form['subnet_id'])) {
        // We do a sub-select to find interface id's that match
        $from = "(\nSELECT distinct a.*\nfrom hosts as a, interfaces as b\nwhere a.id = b.host_id\nand b.subnet_id = " . $onadb->qstr($form['subnet_id']) . "\norder by b.ip_addr) h";
        $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 hosts 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 = 'h.id > 0';
    }
    // Do the SQL Query
    $filter = '';
    if ($form['filter']) {
        // Host names should always be lower case
        $form['filter'] = strtolower($form['filter']);
        // FIXME (MP) for now this uses primary_dns_id, this will NOT find multiple A records or other record types. Find a better way some day
        $filter = " AND h.primary_dns_id IN  (SELECT id " . " FROM dns " . " WHERE name LIKE " . $onadb->qstr('%' . $form['filter'] . '%') . " )  ";
    }
    list($status, $rows, $results) = db_get_records($onadb, $from, $where . $filter, $orderby, $conf['search_results_per_page'], $offset);
    // If we got less than serach_results_per_page, add the current offset to it
    // so that if we're on the last page $rows still has the right number in it.
    if ($rows > 0 and $rows < $conf['search_results_per_page']) {
        $rows += $conf['search_results_per_page'] * ($page - 1);
    } else {
        if ($rows >= $conf['search_results_per_page']) {
            list($status, $rows, $records) = db_get_records($onadb, $from, $where . $filter, "", 0);
        }
    }
    $count = $rows;
    //
    // *** BUILD HTML LIST ***
    //
    $html .= <<<EOL
        <!-- Host Results -->
        <table id="{$form['form_id']}_host_list" class="list-box" cellspacing="0" border="0" cellpadding="0">

            <!-- Table Header -->
            <tr>
                <td class="list-header" align="center" style="{$style['borderR']};">Name</td>
                <td class="list-header" align="center" style="{$style['borderR']};">Subnet</td>
                <td class="list-header" align="center" style="{$style['borderR']};">Interface</td>
                <td class="list-header" align="center" style="{$style['borderR']};">Device Type</td>
                <td class="list-header" align="center" style="{$style['borderR']};">Location</td>
                <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
    foreach ($results as $record) {
        // Get additional info about eash host record
        // If a subnet_id was passed use it as part of the search.  Used to display the IP of the subnet you searched
        if (is_numeric($form['subnet_id'])) {
            list($status, $interfaces, $interface) = ona_get_interface_record(array('host_id' => $record['id'], 'subnet_id' => $form['subnet_id']), '');
            // Count how many rows and assign it back to the interfaces variable
            list($status, $rows, $records) = db_get_records($onadb, 'interfaces', 'host_id = ' . $onadb->qstr($record['id']), "ip_addr", 0);
            $interfaces = $rows;
        } else {
            if (is_numeric($ip)) {
                list($status, $interfaces, $interface) = db_get_record($onadb, 'interfaces', 'host_id = ' . $onadb->qstr($record['id']) . ' AND ip_addr >= ' . $onadb->qstr($ip) . ' AND ip_addr <= ' . $onadb->qstr($ip_end), "ip_addr", 0);
                // Count how many rows and assign it back to the interfaces variable
                list($status, $rows, $records) = db_get_records($onadb, 'interfaces', 'host_id = ' . $onadb->qstr($record['id']), "ip_addr", 0);
                $interfaces = $rows;
            } else {
                // Interface (and find out how many there are)
                list($status, $interfaces, $interface) = ona_get_interface_record(array('host_id' => $record['id']), '');
            }
        }
        // bz: why did someone add this??  You especially want to show hosts with no interfaces so you can fix them!
        // if (!$interfaces) {$count -1; continue;}
        // get interface cluster info
        $clusterhtml = '';
        list($status, $intclusterrows, $intcluster) = db_get_records($onadb, 'interface_clusters', "interface_id = {$interface['id']}");
        if ($intclusterrows > 0) {
            $clusterscript = "onMouseOver=\"wwTT(this, event,\n                    'id', 'tt_interface_cluster_list_{$record['id']}',\n                    'type', 'velcro',\n                    'styleClass', 'wwTT_niceTitle',\n                    'direction', 'south',\n                    'javascript', 'xajax_window_submit(\\'tooltips\\', \\'tooltip=>interface_cluster_list,id=>tt_interface_cluster_list_{$record['id']},interface_id=>{$interface['id']}\\');'\n                    );\"";
            $clusterhtml .= <<<EOL
                <img src="{$images}/silk/sitemap.png" {$clusterscript} />
EOL;
        }
        $record['ip_addr'] = ip_mangle($interface['ip_addr'], 'dotted');
        $interface_style = '';
        if ($interfaces > 1) {
            $interface_style = 'font-weight: bold;';
        }
        // DNS A record
        list($status, $rows, $dns) = ona_get_dns_record(array('id' => $record['primary_dns_id']));
        $record['name'] = $dns['name'];
        // Domain Name
        list($status, $rows, $domain) = ona_get_domain_record(array('id' => $dns['domain_id']));
        $record['domain'] = $domain['fqdn'];
        // 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');
        // Device Description
        list($status, $rows, $device) = ona_get_device_record(array('id' => $record['device_id']));
        list($status, $rows, $device_type) = ona_get_device_type_record(array('id' => $device['device_type_id']));
        list($status, $rows, $model) = ona_get_model_record(array('id' => $device_type['model_id']));
        list($status, $rows, $role) = ona_get_role_record(array('id' => $device_type['role_id']));
        list($status, $rows, $manufacturer) = ona_get_manufacturer_record(array('id' => $model['manufacturer_id']));
        $record['devicefull'] = "{$manufacturer['name']}, {$model['name']} ({$role['name']})";
        $record['device'] = str_replace('Unknown', '?', $record['devicefull']);
        $record['notes_short'] = truncate($record['notes'], 40);
        // Get location_number from the location_id
        list($status, $rows, $location) = ona_get_location_record(array('id' => $device['location_id']));
        // Escape data for display in html
        foreach (array_keys($record) as $key) {
            $record[$key] = htmlentities($record[$key], ENT_QUOTES, $conf['php_charset']);
        }
        $primary_object_js = "xajax_window_submit('work_space', 'xajax_window_submit(\\'display_host\\', \\'host_id=>{$record['id']}\\', \\'display\\')');";
        $html .= <<<EOL
            <tr onMouseOver="this.className='row-highlight';" onMouseOut="this.className='row-normal';">

                <td class="list-row">
                    <a title="View host. ID: {$record['id']}"
                       class="nav"
                       onClick="{$primary_object_js}"
                    >{$record['name']}</a
                    >.<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">
                    <a title="View subnet. ID: {$subnet['id']}"
                         class="nav"
                         onClick="xajax_window_submit('work_space', 'xajax_window_submit(\\'display_subnet\\', \\'subnet_id=>{$subnet['id']}\\', \\'display\\')');"
                    >{$record['subnet']}</a>&nbsp;
                </td>

                <td class="list-row" align="left">
                    <span style="{$interface_style}"
EOL;
        if ($interfaces > 1) {
            $html .= <<<EOL
                          onMouseOver="wwTT(this, event,
                                            'id', 'tt_host_interface_list_{$record['id']}',
                                            'type', 'velcro',
                                            'styleClass', 'wwTT_niceTitle',
                                            'direction', 'south',
                                            'javascript', 'xajax_window_submit(\\'tooltips\\', \\'tooltip=>host_interface_list,id=>tt_host_interface_list_{$record['id']},host_id=>{$record['id']}\\');'
                                           );"
EOL;
        }
        $html .= <<<EOL
                    >{$record['ip_addr']}</span>&nbsp;
                    <span title="{$record['ip_mask']}">/{$record['ip_mask_cidr']}</span>
                    <span>{$clusterhtml}</span>
                </td>

                <td class="list-row" title="{$record['devicefull']}">{$record['device']}&nbsp;</td>

                <td class="list-row" align="right">
                    <span onMouseOver="wwTT(this, event,
                                            'id', 'tt_location_{$device['location_id']}',
                                            'type', 'velcro',
                                            'styleClass', 'wwTT_niceTitle',
                                            'direction', 'south',
                                            'javascript', 'xajax_window_submit(\\'tooltips\\', \\'tooltip=>location,id=>tt_location_{$device['location_id']},location_id=>{$device['location_id']}\\');'
                                           );"
                    >{$location['reference']}</span>&nbsp;
                </td>

                <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_host_{$record['id']}"
                        ><input type="hidden" name="host_id" value="{$record['id']}"
                        ><input type="hidden" name="js" value="{$refresh}"
                    ></form>&nbsp;
EOL;
        if (auth('host_modify')) {
            $html .= <<<EOL

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

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

            </tr>
EOL;
    }
    if ($count == 0 and $form['subnet_id'] and !$form['filter']) {
        $html .= <<<EOL
     <tr><td colspan="99" align="center" style="color: red;">Please add the gateway host (router) to this subnet</td></tr>
EOL;
    }
    $html .= <<<EOL
    </table>
EOL;
    // Build page links if there are any
    $html .= get_page_links($page, $conf['search_results_per_page'], $count, $window_name, $form['form_id']);
    // If there was only 1 result, and we're about to display results in the "Search Results" window, display it.
    if ($count == 1 and $form['content_id'] == 'search_results_list' and $form['filter'] == '') {
        $js .= $primary_object_js;
    }
    // Insert the new html into the content div specified
    // Instantiate the xajaxResponse object
    $response = new xajaxResponse();
    $response->addAssign("{$form['form_id']}_{$tab}_count", "innerHTML", "({$count})");
    $response->addAssign($form['content_id'], "innerHTML", $html);
    if ($js) {
        $response->addScript($js);
    }
    return $response->getXML();
}
Example #21
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, $subnet_type) = db_get_record($onadb, 'subnet_types', array('id' => $form));
    if ($status or !$rows) {
        $response->addScript("alert('Delete failed: Subnet type ID {$form} doesnt exist');");
        return $response->getXML();
    }
    // Get a list of subnets that use this subnet type
    list($status, $rows, $subnet) = db_get_records($onadb, 'subnets', array('subnet_type_id' => $form), '', 0);
    // Check that there are no parent records using this type
    if ($rows > 0) {
        $js .= "alert('Delete failed: There are {$rows} subnets using this subnet type.');";
    } else {
        // Delete the record
        list($status, $rows) = db_delete_records($onadb, 'subnet_types', array('id' => $subnet_type['id']));
        // If the module returned an error code display a popup warning
        if ($status != 0) {
            $js .= "alert('Delete failed: " . trim($self['error']) . "');";
        }
    }
    // 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 #22
0
function dns_record_del($options = "")
{
    global $conf, $self, $onadb;
    printmsg("DEBUG => dns_record_del({$options}) called", 3);
    // Version - UPDATE on every edit!
    $version = '1.03';
    // Parse incoming options string to an array
    $options = parse_options($options);
    // Sanitize options[commit] (default is no)
    $options['commit'] = sanitize_YN($options['commit'], 'N');
    // Return the usage summary if we need to
    if ($options['help'] or !$options['name']) {
        // NOTE: Help message lines should not exceed 80 characters for proper display on a console
        $self['error'] = 'ERROR => Insufficient parameters';
        return array(1, <<<EOM

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

  Synopsis: dns_record_del [KEY=VALUE] ...

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

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



EOM
);
    }
    /*
    thoughts on the flow of things:
    A records:
        remove any CNAMES using this A record
        remove any PTR records using this A record
        test that it is not a primary_dns_id, if it is, it must be reassigned
    should make a find_dns_record(s) function.  a find by host option would be good.
    need to do a better delete of DNS records when deleting a host.. currently its a problem.
    MP: TODO:  this delete will not handle DNS views unless you use the ID of the record to delete.  add a view option at some point.
    */
    // If the name we were passed has a leading . in it then remove the dot.
    $options['name'] = preg_replace("/^\\./", '', $options['name']);
    // FIXME: MP Fix this to use a find_dns_record function  ID only for now
    // Find the DNS record from $options['name']
    list($status, $rows, $dns) = ona_find_dns_record($options['name'], $options['type']);
    printmsg("DEBUG => dns_record_del() DNS record: {$options['name']}", 3);
    if (!$dns['id']) {
        printmsg("DEBUG => Unknown DNS record: {$options['name']} ({$options['type']})", 3);
        $self['error'] = "ERROR => Unknown DNS record: {$options['name']} ({$options['type']})";
        return array(2, $self['error'] . "\n");
    }
    // Check permissions
    if (!auth('host_del') or !authlvl($host['LVL'])) {
        $self['error'] = "Permission denied!";
        printmsg($self['error'], 0);
        return array(10, $self['error'] . "\n");
    }
    // If "commit" is yes, delete the host
    if ($options['commit'] == 'Y') {
        $text = "";
        $add_to_error = "";
        // SUMMARY:
        //   Display any associated PTR records for an A record
        //   Display any associated CNAMEs for an A record
        // Test if it is used as a primary_dns_id unless it is the host_del module calling
        if (!isset($options['delete_by_module'])) {
            list($status, $rows, $srecord) = db_get_record($onadb, 'hosts', array('primary_dns_id' => $dns['id']));
            if ($rows) {
                $self['error'] = "ERROR => dns_record_del() The DNS record, {$dns['name']}.{$dns['domain_fqdn']}[{$dns['id']}], is a primary A record for a host! You can not delete it until you associate a new primary record, or delete the host.";
                printmsg($self['error'], 0);
                return array(5, $self['error'] . "\n");
            }
        }
        // Delete related Points to records
        // get list for logging
        list($status, $rows, $records) = db_get_records($onadb, 'dns', array('dns_id' => $dns['id']));
        // do the delete
        list($status, $rows) = db_delete_records($onadb, 'dns', array('dns_id' => $dns['id']));
        if ($status) {
            $self['error'] = "ERROR => dns_record_del() Child record delete SQL Query failed: {$self['error']}";
            printmsg($self['error'], 0);
            return array(5, $self['error'] . "\n");
        }
        if ($rows) {
            // log deletions
            // FIXME: do better logging here
            printmsg("INFO => {$rows} child DNS record(s) DELETED from {$dns['fqdn']}", 0);
            $add_to_error .= "INFO => {$rows} child record(s) DELETED from {$dns['fqdn']}\n";
        }
        // TRIGGER: flag the domains for rebuild
        foreach ($records as $record) {
            list($status, $rows) = db_update_record($onadb, 'dns_server_domains', array('domain_id' => $record['domain_id']), array('rebuild_flag' => 1));
            if ($status) {
                $self['error'] = "ERROR => dns_record_del() Unable to update rebuild flags for domain.: {$self['error']}";
                printmsg($self['error'], 0);
                return array(7, $self['error'] . "\n");
            }
        }
        // Delete the DNS record
        list($status, $rows) = db_delete_records($onadb, 'dns', array('id' => $dns['id']));
        if ($status) {
            $self['error'] = "ERROR => dns_record_del() DNS record delete SQL Query failed: {$self['error']}";
            printmsg($self['error'], 0);
            return array(5, $add_to_error . $self['error'] . "\n");
        }
        // TRIGGER: flag the current dnsrecords domain for rebuild
        list($status, $rows) = db_update_record($onadb, 'dns_server_domains', array('domain_id' => $dns['domain_id']), array('rebuild_flag' => 1));
        if ($status) {
            $self['error'] = "ERROR => dns_record_del() Unable to update rebuild flags for domain.: {$self['error']}";
            printmsg($self['error'], 0);
            return array(7, $self['error'] . "\n");
        }
        // FIXME: if it is a NS or something display a proper FQDN message here
        // Display proper PTR information
        if ($dns['type'] == 'PTR') {
            list($status, $rows, $pointsto) = ona_get_dns_record(array('id' => $dns['dns_id']), '');
            list($status, $rows, $ptrint) = ona_get_interface_record(array('id' => $dns['interface_id']), '');
            $ipflip = ip_mangle($ptrint['ip_addr'], 'flip');
            $octets = explode(".", $ipflip);
            if (count($octets) > 4) {
                $arpa = '.ip6.arpa';
                $octcount = 31;
            } else {
                $arpa = '.in-addr.arpa';
                $octcount = 3;
            }
            $dns['fqdn'] = "{$ipflip}{$arpa} -> {$pointsto['fqdn']}";
        }
        // Return the success notice
        $self['error'] = "INFO => DNS {$dns['type']} record DELETED: {$dns['fqdn']}";
        printmsg($self['error'], 0);
        return array(0, $add_to_error . $self['error'] . "\n");
    }
    //
    // We are just displaying records that would have been deleted
    //
    // SUMMARY:
    //   Display any associated PTR records for an A record
    //   Display any associated CNAMEs for an A record
    // Otherwise just display the host record for the host we would have deleted
    $text = "Record(s) NOT DELETED (see \"commit\" option)\n" . "Displaying record(s) that would have been deleted:\n";
    // Test if it is used as a primary_dns_id
    list($status, $rows, $srecord) = db_get_record($onadb, 'hosts', array('primary_dns_id' => $dns['id']));
    if ($rows) {
        $text .= "\nWARNING!  This DNS record is a primary A record for a host\n";
    }
    // Display the complete dns record
    list($status, $tmp) = dns_record_display("name={$dns['id']}&verbose=N");
    $text .= "\n" . $tmp;
    // Display associated Child records
    list($status, $rows, $records) = db_get_records($onadb, 'dns', array('dns_id' => $dns['id']));
    if ($rows) {
        $text .= "\nASSOCIATED POINTS-TO RECORDS ({$rows}):\n";
    }
    foreach ($records as $record) {
        if ($record['type'] == 'NS') {
            $record['name'] = '';
        }
        // FIXME:I could fix this but I'm lazy
        if ($record['type'] == 'PTR') {
            $record['name'] = '??';
        }
        list($status, $rows, $domain) = ona_get_domain_record(array('id' => $record['domain_id']), '');
        $text .= " {$record['type']}: {$record['name']}.{$domain['fqdn']} -> {$dns['fqdn']}\n";
    }
    return array(7, $text);
}
Example #23
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 #24
0
 /**
  * Return user info [ MUST BE OVERRIDDEN ] or false
  *
  * Returns info about the given user needs to contain
  * at least these fields:
  *
  * username   string      name of the user
  * grps       array       list of groups the user is in
  *                        $user['grps']['groupname']=groupidnum
  *
  * sets a variable ($this->founduser) to show if a user was
  * found by this function
  *
  * @author  Matt Pascoe <*****@*****.**>
  * @return  array containing user data or false
  */
 function getUserData($login_name)
 {
     global $onadb;
     list($status, $rows, $user) = db_get_record($onadb, 'users', "username LIKE '{$login_name}'");
     if (!$rows) {
         $this->founduser = false;
         return false;
     } else {
         $this->founduser = true;
         // Update the access time for the user
         db_update_record($onadb, 'users', array('id' => $user['id']), array('atime' => date_mangle(time())));
         // Load the user's groups
         list($status, $rows, $records) = db_get_records($onadb, 'group_assignments', array('user_id' => $user['id']));
         foreach ($records as $record) {
             list($status, $rows, $group) = db_get_record($onadb, 'groups', array('id' => $record['group_id']));
             $user['grps'][$group['name']] = $group['id'];
             if ($group['level'] > $user['level']) {
                 $user['level'] = $group['level'];
             }
         }
         return $user;
     }
 }
Example #25
0
function get_class_c_html($ip = 0, $zoom = 2, $row_height)
{
    global $conf, $self, $onadb, $color, $style, $images;
    $html = '';
    if ($ip == 0) {
        return $html;
    }
    $ip_end = $ip + 255;
    $x_px_per_ip = $zoom;
    // Select all subnet records in this class C
    //$where = "ip_addr >= {$ip} AND ip_addr <= " . $ona->qstr($ip_end);
    $where = "ip_addr >= {$ip} AND ip_addr <= {$ip_end}";
    list($status, $num_subnets, $subnets) = db_get_records($onadb, 'subnets', $where, "ip_addr ASC");
    // If the first record isn't a subnet, see if the first IP is in another subnet
    if ($subnets[0]['ip_addr'] != $ip) {
        $where = "ip_addr < {$ip} AND ((4294967295 - ip_mask) + ip_addr) >= {$ip}";
        list($status, $rows, $subnet) = db_get_record($onadb, 'subnets', $where);
        if ($rows) {
            $num_subnets++;
            array_unshift($subnets, $subnet);
        }
    }
    $block_start = $ip;
    // Find the next block of addresses
    while ($block_start < $ip_end) {
        if (!is_array($subnet) or $block_start > $subnet['ip_addr']) {
            $subnet = array_shift($subnets);
            if (is_array($subnet)) {
                $subnet['SIZE'] = 0xffffffff - $subnet['ip_mask'] + 1;
                $subnet['ip_addr_end'] = $subnet['ip_addr'] + $subnet['SIZE'] - 1;
            } else {
                // pretend like the next subnet record is the next class C
                $subnet['SIZE'] = $ip_end - $block_start + 1;
                $subnet['ip_addr'] = $ip_end + 1;
            }
        }
        // If it's unallocated space
        if ($block_start < $subnet['ip_addr']) {
            $block_end = $subnet['ip_addr'] - 1;
            $block_color = $color['bgcolor_map_empty'];
        } else {
            $block_end = $subnet['ip_addr_end'];
            if ($block_end > $ip_end) {
                $block_end = $ip_end;
            }
            $block_color = $color['bgcolor_map_subnet'];
        }
        $block_size = $block_end - $block_start + 1;
        $block_size_total += $block_size;
        // $block_title = htmlentities($subnet['DESCRIPTION'] . " :: Size={$block_size}", ENT_QUOTES) . ' :: ' . ip_mangle($block_start, 'dotted') . " -> " . ip_mangle($block_end, 'dotted');
        // Display the current block (-1 for px border unless it's IE)
        $x = $block_size * $x_px_per_ip - 1;
        if (strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE') != false) {
            $x++;
        }
        $html .= <<<EOL
<div id="{$block_start}_block"
     style="
       clear: none; float: left;
       border-right: 1px solid #000000; background-color: {$block_color};
       width: {$x}px; height: {$row_height}px;"
     onMouseOver="
       wwTT(this, event,
         'id', 'tt_subnet_{$block_start}',
         'type', 'velcro',
         'styleClass', 'wwTT_niceTitle',
         'direction', 'south',
         'javascript', 'xajax_window_submit(\\'tooltips\\', \\'tooltip=>subnet,id=>tt_subnet_{$block_start},subnet_ip=>{$block_start}\\');'
       );"
></div>
EOL;
        $block_start = $block_end + 1;
    }
    return $html;
}
Example #26
0
function add_module($options = "")
{
    global $conf, $self, $onadb;
    printmsg('DEBUG => add_module(' . $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_module-v{$version}
Registers a new DCM module, this should be used by install scripts that are
creating new functionality that requires a registered module.

  Synopsis: add_module(OPTIONS)

  Options:
    name=STRING         Name of DCM module
    desc=STRING         Quoted string to describe this module
    file=STRING         Path to php file, relative to {$conf['dcm_module_dir']}



EOM
);
    }
    // Get a list of the valid "modules" and their descriptions.
    list($status, $rows, $modules) = db_get_record($onadb, 'dcm_module_list', array('name' => $options['name']), '');
    if ($rows) {
        $self['error'] = "ERROR => add_module() Module name already exists: {$options['name']}";
        printmsg($self['error'], 0);
        return array(1, $self['error'] . "\n");
    }
    // Add the record
    list($status, $rows) = db_insert_record($onadb, 'dcm_module_list', array('name' => $options['name'], 'description' => $options['desc'], 'file' => $options['file']));
    if ($status or !$rows) {
        $self['error'] = "ERROR => add_module() SQL Query failed: " . $self['error'];
        printmsg($self['error'], 0);
        return array(2, $self['error'] . "\n");
    }
    // Return the success notice
    $self['error'] = "INFO => Module ADDED: {$options['name']} [{$options['desc']}] => {$options['file']}";
    printmsg($self['error'], 0);
    return array(0, $self['error'] . "\n");
}
Example #27
0
function get_domain_suggestions($q, $max_results = 10)
{
    global $self, $conf, $onadb;
    $results = array();
    // wildcard the query before searching
    $q = $q . '%';
    $table = 'domains';
    $field = 'name';
    $where = "{$field} LIKE " . $onadb->qstr($q);
    $order = "{$field} ASC";
    // Search the db for results
    list($status, $rows, $records) = db_get_records($onadb, $table, $where, $order, $max_results);
    // If the query didn't work return the error message
    if ($status) {
        $results[] = "Internal Error: {$self['error']}";
    }
    foreach ($records as $record) {
        if ($record['parent_id']) {
            list($status, $rows, $domain) = db_get_record($onadb, 'domains', array('id' => $record['parent_id']));
            $results[] = $record[$field] . "." . ona_build_domain_name($domain['id']);
        } else {
            $results[] = $record[$field];
            // Also check if this record is a parent of others
            list($status, $rows, $precords) = db_get_records($onadb, $table, "{$record['id']} = parent_id", $order, $max_results);
            foreach ($precords as $precord) {
                $results[] = $precord[$field] . "." . ona_build_domain_name($record['id']);
            }
        }
    }
    // Return the records
    return $results;
}
Example #28
0
/**
 * Authorizes a user for specific permissions
 *
 * Populates session variable with permissions. no
 * data is returned to the calling function
 *
 * @author  Matt Pascoe <*****@*****.**>
 * @return  TRUE
 */
function get_perms($login_name = '')
{
    global $conf, $self, $onadb, $auth;
    // We'll be populating these arrays
    $user = array();
    $groups = array();
    $permissions = array();
    printmsg("INFO => Authorization Starting for {$login_name}", 1);
    // get user information and groups from the previously populated auth class
    $userinfo = $auth->getUserData($login_name);
    if ($userinfo === false) {
        printmsg("INFO => Failed to get user information for user: {$login_name}", 0);
    }
    // If this is the local auth type, check local user permissions
    // MP: This code should not be here but there is really not a better spot.
    //if ($conf['authtype'] == 'local') {
    // Load the users permissions based on their user_id.
    // this is specific permissions for user, outside of group permissions
    list($status, $rows, $records) = db_get_records($onadb, 'permission_assignments', array('user_id' => $userinfo['id']));
    foreach ($records as $record) {
        list($status, $rows, $perm) = db_get_record($onadb, 'permissions', array('id' => $record['perm_id']));
        $permissions[$perm['name']] = $perm['id'];
    }
    //}
    // Load the users permissions based on their group ids
    foreach ((array) $userinfo['grps'] as $group => $grpid) {
        // Look up the group id stored in local tables using the name
        list($status, $rows, $grp) = db_get_record($onadb, 'groups', array('name' => $group));
        // get permission assignments per group id
        list($status, $rows, $records) = db_get_records($onadb, 'permission_assignments', array('group_id' => $grp['id']));
        foreach ($records as $record) {
            list($status, $rows, $perm) = db_get_record($onadb, 'permissions', array('id' => $record['perm_id']));
            $permissions[$perm['name']] = $perm['id'];
        }
    }
    // Save stuff in the session
    unset($_SESSION['ona']['auth']);
    $_SESSION['ona']['auth']['user'] = $userinfo;
    $_SESSION['ona']['auth']['perms'] = $permissions;
    // Log that the user logged in
    printmsg("INFO => Loaded permissions for " . $login_name, 2);
    return true;
}
Example #29
0
function ona_find_dns_record($search = "", $type = '', $int_id = 0)
{
    global $conf, $self, $onadb;
    printmsg("DEBUG => ona_find_dns_record({$search}) called", 3);
    $type = strtoupper($type);
    $search = strtolower($search);
    // By record ID?
    if (is_numeric($search)) {
        list($status, $rows, $dns) = ona_get_dns_record(array('id' => $search));
        if ($rows) {
            printmsg("DEBUG => ona_find_dns_record({$search}) called, found: {$dns['fqdn']}({$dns['type']})", 3);
            return array($status, $rows, $dns);
        }
    }
    //
    // It's an FQDN, do a bunch of stuff!
    //
    // lets test out if it has a / in it to strip the view name portion
    $view['id'] = 0;
    if (strstr($search, '/')) {
        list($dnsview, $search) = explode('/', $search);
        list($status, $rows, $view) = db_get_record($onadb, 'dns_views', array('name' => strtoupper($dnsview)));
        if (!$rows) {
            $view['id'] = 0;
        }
    }
    // Find the domain name piece of $search
    list($status, $rows, $domain) = ona_find_domain($search);
    printmsg("DEBUG => ona_find_domain({$search}) returned: {$domain['fqdn']}", 3);
    // Now find what the host part of $search is
    $hostname = str_replace(".{$domain['fqdn']}", '', $search);
    // If the hostname we came up with and the domain name are the same, then assume this is
    // meant to be a domain specific record, like A, MX, NS type records.
    if ($hostname == $domain['fqdn']) {
        $hostname = '';
    }
    // Setup the search array
    $searcharray = array('domain_id' => $domain['id'], 'name' => $hostname, 'dns_view_id' => $view['id']);
    // If an interface_id was passed, add it to the array
    if ($int_id > 0) {
        $searcharray['interface_id'] = $int_id;
    }
    // If a type was passed, add it to the array
    if ($type) {
        $searcharray['type'] = $type;
    }
    // Let's see if that hostname is valid or not in $domain['id']
    list($status, $rows, $dns) = ona_get_dns_record($searcharray);
    if ($rows) {
        // Return good status, one row, and $dns array
        printmsg("DEBUG => ona_find_dns_record({$search}) called, found: {$dns['fqdn']}({$dns['type']})", 3);
        return array(0, 1, $dns);
    }
    // Otherwise, build a fake dns record with only a few entries in it and return that
    $dns = array('id' => 0, 'name' => $hostname, 'fqdn' => "{$hostname}.{$domain['fqdn']}", 'domain_id' => $domain['id'], 'domain_fqdn' => $domain['fqdn'], 'type' => '', 'dns_id' => 0);
    printmsg("DEBUG => ona_find_dns_record({$search}) called, Nothing found, returning fake entry: {$dns['fqdn']}({$dns['type']})", 3);
    return array(0, 1, $dns);
}
Example #30
0
function ws_delete($window_name, $form = '')
{
    global $conf, $self, $onadb;
    // Check permissions
    if (!auth('user_admin')) {
        $response = new xajaxResponse();
        $response->addScript("alert('Permission denied!');");
        return $response->getXML();
    }
    // Instantiate the xajaxResponse object
    $response = new xajaxResponse();
    $js = '';
    // Load the user record to make sure it exists
    list($status, $rows, $user) = db_get_record($onadb, 'users', array('id' => $form));
    if ($status or !$rows) {
        $response->addScript("alert('Delete failed: User ID {$form} doesnt exist');");
        return $response->getXML();
    }
    // Delete the user's group assignments
    do {
        list($status, $rows) = db_delete_records($onadb, 'group_assignments', array('user_id' => $user['id']));
    } while ($rows >= 1);
    // Delete the user's permission assignments
    do {
        list($status, $rows) = db_delete_records($onadb, 'permission_assignments', array('user_id' => $user['id']));
    } while ($rows >= 1);
    // Delete the user's record
    list($status, $rows) = db_delete_records($onadb, 'users', array('id' => $user['id']));
    // If the module returned an error code display a popup warning
    if ($status != 0) {
        $js .= "alert('Delete failed');";
        $self['error'] = "ERROR => user_list delete ws_save() SQL Query failed: " . $self['error'];
        printmsg($self['error'], 0);
    } else {
        $self['error'] = "INFO => User DELETED: {$user['username']} ";
        printmsg($self['error'], 0);
        // Refresh the current list of users.. 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();
}