Exemplo n.º 1
0
    def page(self) -> None:
        host_names = get_hostnames_from_checkboxes()
        hosts = {
            host_name: Folder.current().host(host_name)
            for host_name in host_names
        }
        current_host_hash = sha256(repr(hosts).encode()).hexdigest()

        # When bulk edit has been made with some hosts, then other hosts have been selected
        # and then another bulk edit has made, the attributes need to be reset before
        # rendering the form. Otherwise the second edit will have the attributes of the
        # first set.
        host_hash = request.var("host_hash")
        if not host_hash or host_hash != current_host_hash:
            request.del_vars(prefix="attr_")
            request.del_vars(prefix="bulk_change_")

        html.p("%s%s %s" % (
            _("You have selected <b>%d</b> hosts for bulk edit. You can now change "
              "host attributes for all selected hosts at once. ") % len(hosts),
            _("If a select is set to <i>don't change</i> then currenty not all selected "
              "hosts share the same setting for this attribute. "
              "If you leave that selection, all hosts will keep their individual settings."
              ),
            _("In case you want to <i>unset</i> attributes on multiple hosts, you need to "
              "use the <i>bulk cleanup</i> action instead of bulk edit."),
        ))

        html.begin_form("edit_host", method="POST")
        html.prevent_password_auto_completion()
        html.hidden_field("host_hash", current_host_hash)
        configure_attributes(False, hosts, "bulk", parent=Folder.current())
        forms.end()
        html.hidden_fields()
        html.end_form()
Exemplo n.º 2
0
    def _show_form(self) -> None:
        assert user.id is not None
        credentials = load_two_factor_credentials(user.id)

        credential_id = request.get_ascii_input_mandatory("_edit")
        credential = credentials["webauthn_credentials"].get(credential_id)
        if credential is None:
            raise MKUserError("_edit", _("The credential does not exist"))

        html.begin_form("profile", method="POST")
        html.prevent_password_auto_completion()
        html.open_div(class_="wato")

        self._valuespec(credential).render_input(
            "profile",
            {
                "registered_at": credential["registered_at"],
                "alias": credential["alias"],
            },
        )

        forms.end()
        html.close_div()
        html.hidden_field("_edit", credential_id)
        html.hidden_fields()
        html.end_form()
        html.footer()
Exemplo n.º 3
0
def _show_command_form(datasource: ABCDataSource, rows: Rows) -> None:
    what = datasource.infos[0]
    html.javascript(
        """
    $(document).ready(function() {
      $('.command_group').has('x').trigger('expand');
      $('x').children().css('background-color', '#f84');
    });
    """
    )

    one_shown = False
    html.open_div(**{"data-role": "collapsible-set"})
    for command_class in command_registry.values():
        command = command_class()
        if what in command.tables and user.may(command.permission.name):
            html.open_div(class_=["command_group"], **{"data-role": "collapsible"})
            html.h3(command.title)
            html.open_p()

            html.begin_form("actions")
            html.hidden_field("_do_actions", "yes")
            html.hidden_field("actions", "yes")
            command.render(what)
            html.hidden_fields()
            html.end_form()

            html.close_p()
            html.close_div()
            one_shown = True
    html.close_div()
    if not one_shown:
        html.write_text(_("No commands are possible in this view"))
Exemplo n.º 4
0
    def page(self):
        # Show search form
        html.begin_form("edit_host", method="POST")
        html.prevent_password_auto_completion()

        basic_attributes = [
            (
                "host_search_host",
                TextInput(title=_("Hostname", )),
                "",
            ),
        ]
        html.set_focus("host_search_host")

        # Attributes
        configure_attributes(
            new=False,
            hosts={},
            for_what="host_search",
            parent=None,
            varprefix="host_search_",
            basic_attributes=basic_attributes,
        )

        forms.end()
        html.hidden_field("host_search", "1")
        html.hidden_fields()
        html.end_form()
Exemplo n.º 5
0
def _show_filter_form(show_filters: List[Filter], context: VisualContext) -> None:
    # Sort filters
    s = sorted([(f.sort_index, f.title, f) for f in show_filters if f.available()])

    html.begin_form("filter")
    html.open_ul(**{"data-role": "listview", "data-inset": "false"})
    for _sort_index, title, f in s:
        html.open_li(**{"data-role": "fieldcontain"})
        html.legend(title)
        f.display(context.get(f.ident, {}))
        html.close_li()
    html.close_ul()
    html.hidden_fields()
    html.hidden_field("search", "Search")
    html.hidden_field("page", "data")
    html.form_has_submit_button = True  # a.results_button functions as a submit button
    html.end_form()
    html.final_javascript(
        """
        const filter_form = document.getElementById("form_filter");
        const results_button = document.getElementsByClassName("results_button")[0];

        cmk.forms.enable_select2_dropdowns(filter_form);
        results_button.onclick = function(event) {
            event.preventDefault();
            filter_form.submit();
        };
        """
    )
Exemplo n.º 6
0
def inpage_search_form(mode: Optional[str] = None, default_value: str = "") -> None:
    form_name = "inpage_search_form"
    reset_button_id = "%s_reset" % form_name
    was_submitted = request.get_ascii_input("filled_in") == form_name
    html.begin_form(form_name, add_transid=False)
    html.text_input(
        "search",
        size=32,
        default_value=default_value,
        placeholder=_("Filter"),
        required=True,
        title="",
    )
    html.hidden_fields()
    if mode:
        html.hidden_field("mode", mode, add_var=True)
    reset_url = request.get_ascii_input_mandatory("reset_url", requested_file_with_query(request))
    html.hidden_field("reset_url", reset_url, add_var=True)
    html.button("submit", "", cssclass="submit", help_=_("Apply"))
    html.buttonlink(reset_url, "", obj_id=reset_button_id, title=_("Reset"))
    html.end_form()
    html.javascript(
        "cmk.page_menu.inpage_search_init(%s, %s)"
        % (json.dumps(reset_button_id), json.dumps(was_submitted))
    )
Exemplo n.º 7
0
    def _activation_form(self):
        if not user.may("wato.activate"):
            html.show_warning(
                _("You are not permitted to activate configuration changes."))
            return

        if not self._changes:
            return

        if not user.may("wato.activateforeign"
                        ) and self._has_foreign_changes_on_any_site():
            html.show_warning(
                _("Sorry, you are not allowed to activate changes of other users."
                  ))
            return

        valuespec = _vs_activation(self.title(), self.has_foreign_changes())

        html.begin_form("activate", method="POST", action="")
        html.hidden_field("activate_until",
                          self._get_last_change_id(),
                          id_="activate_until")

        if valuespec:
            title = valuespec.title()
            assert title is not None
            forms.header(title)
            valuespec.render_input("activate", self._value)
            valuespec.set_focus("activate")
            html.help(valuespec.help())

        if self.has_foreign_changes():
            if user.may("wato.activateforeign"):
                html.show_warning(
                    _("There are some changes made by your colleagues that you will "
                      "activate if you proceed. You need to enable the checkbox above "
                      "to confirm the activation of these changes."))
            else:
                html.show_warning(
                    _("There are some changes made by your colleagues that you can not "
                      "activate because you are not permitted to. You can only activate "
                      "the changes on the sites that are not affected by these changes. "
                      "<br>"
                      "If you need to activate your changes on all sites, please contact "
                      "a permitted user to do it for you."))

        forms.end()
        html.hidden_field("selection_id", weblib.selection_id())
        html.hidden_fields()
        html.end_form()
        init_rowselect(self.name())
Exemplo n.º 8
0
def search_form(
    title: Optional[str] = None, mode: Optional[str] = None, default_value: str = ""
) -> None:
    html.begin_form("search", add_transid=False)
    if title:
        html.write_text(title + " ")
    html.text_input("search", size=32, default_value=default_value)
    html.hidden_fields()
    if mode:
        html.hidden_field("mode", mode, add_var=True)
    html.set_focus("search")
    html.write_text(" ")
    html.button("_do_seach", _("Search"))
    html.end_form()
Exemplo n.º 9
0
def show_create_view_dialog(next_url=None):
    vs_ds = DatasourceSelection()

    ds = "services"  # Default selection

    title = _("Create view")
    breadcrumb = visuals.visual_page_breadcrumb("views", title, "create")
    make_header(
        html,
        title,
        breadcrumb,
        make_simple_form_page_menu(
            _("View"),
            breadcrumb,
            form_name="create_view",
            button_name="_save",
            save_title=_("Continue"),
        ),
    )

    if request.var("_save") and transactions.check_transaction():
        try:
            ds = vs_ds.from_html_vars("ds")
            vs_ds.validate_value(ds, "ds")

            if not next_url:
                next_url = makeuri(
                    request,
                    [("datasource", ds)],
                    filename="create_view_infos.py",
                )
            else:
                next_url = next_url + "&datasource=%s" % ds
            raise HTTPRedirect(next_url)
        except MKUserError as e:
            html.user_error(e)

    html.begin_form("create_view")
    html.hidden_field("mode", "create")

    forms.header(_("Select Datasource"))
    forms.section(vs_ds.title())
    vs_ds.render_input("ds", ds)
    html.help(vs_ds.help())
    forms.end()

    html.hidden_fields()
    html.end_form()
    html.footer()
Exemplo n.º 10
0
def _render_werk_options_form(werk_table_options: Dict[str, Any]) -> HTML:
    with output_funnel.plugged():
        html.begin_form("werks")
        html.hidden_field("wo_set", "set")

        _show_werk_options_controls()

        html.open_div(class_="side_popup_content")
        for name, height, vs, _default_value in _werk_table_option_entries():

            def renderer(name=name,
                         vs=vs,
                         werk_table_options=werk_table_options) -> None:
                vs.render_input("wo_" + name, werk_table_options[name])

            html.render_floating_option(name, height, vs.title(), renderer)
        html.close_div()

        html.hidden_fields()
        html.end_form()

        return HTML(output_funnel.drain())
Exemplo n.º 11
0
def page_login() -> None:
    title = _("Checkmk Mobile")
    mobile_html_head(title)
    jqm_page_header(title, id_="login")
    html.div(_("Welcome to Checkmk Mobile."), id_="loginhead")

    html.begin_form("login", method="POST", add_transid=False)
    # Keep information about original target URL
    default_origtarget = (
        "index.py" if requested_file_name(request) in ["login", "logout"] else makeuri(request, [])
    )
    origtarget = request.get_url_input("_origtarget", default_origtarget)
    html.hidden_field("_origtarget", escaping.escape_attribute(origtarget))

    html.text_input("_username", label=_("Username:"******"username", id_="input_user")
    html.password_input(
        "_password",
        size=None,
        label=_("Password:"******"current-password",
        id_="input_pass",
    )
    html.br()
    html.button("_login", _("Login"))
    html.set_focus("_username")
    html.end_form()
    html.open_div(id_="loginfoot")
    html.img("themes/facelift/images/logo_cmk_small.png", class_="logomk")
    html.div(
        HTML(_('&copy; <a target="_blank" href="https://checkmk.com">tribe29 GmbH</a>')),
        class_="copyright",
    )
    html.close_div()  # close content-div
    html.close_div()
    html.close_div()  # close page-div
    mobile_html_foot()
Exemplo n.º 12
0
    def render_input(self, varprefix: str, value: dict[str, Any]) -> None:
        # The display mode differs when the valuespec is activated
        vars_copy = dict(request.itervars())

        # The timeperiod mode can be set by either the GUI switch or by the value itself
        # GUI switch overrules the information stored in the value
        if request.has_var(self.tp_toggle_var):
            is_active = self._is_switched_on()
        else:
            is_active = self.is_active(value)

        # Set the actual used mode
        html.hidden_field(self.tp_current_mode, "%d" % is_active)

        vars_copy[self.tp_toggle_var] = "%d" % (not is_active)

        url_vars: HTTPVariables = []
        url_vars += vars_copy.items()
        toggle_url = makeuri(request, url_vars)

        if is_active:
            value = self._get_timeperiod_value(value)
            self._get_timeperiod_valuespec().render_input(varprefix, value)
            html.buttonlink(
                toggle_url,
                _("Disable timespecific parameters"),
                class_=["toggle_timespecific_parameter"],
            )
        else:
            value = self._get_timeless_value(value)
            self._enclosed_valuespec.render_input(varprefix, value)
            html.buttonlink(
                toggle_url,
                _("Enable timespecific parameters"),
                class_=["toggle_timespecific_parameter"],
            )
Exemplo n.º 13
0
    def page(self):
        search = get_search_expression()

        html.begin_form("role", method="POST")

        # ID
        forms.header(_("Basic properties"), css="wide")
        forms.section(_("Internal ID"), simple="builtin" in self._role, is_required=True)
        if self._role.get("builtin"):
            html.write_text("%s (%s)" % (self._role_id, _("builtin role")))
            html.hidden_field("id", self._role_id)
        else:
            html.text_input("id", self._role_id)
            html.set_focus("id")

        # Alias
        forms.section(_("Alias"))
        html.help(_("An alias or description of the role"))
        html.text_input("alias", self._role.get("alias", ""), size=50)

        # Based on
        if not self._role.get("builtin"):
            forms.section(_("Based on role"))
            html.help(
                _(
                    "Each user defined role is based on one of the builtin roles. "
                    "When created it will start with all permissions of that role. When due to a software "
                    "update or installation of an addons new permissions appear, the user role will get or "
                    "not get those new permissions based on the default settings of the builtin role it's "
                    "based on."
                )
            )
            role_choices: Choices = [
                (i, r["alias"]) for i, r in self._roles.items() if r.get("builtin")
            ]
            html.dropdown(
                "basedon", role_choices, deflt=self._role.get("basedon", "user"), ordered=True
            )

        forms.end()

        html.h2(_("Permissions"))

        # Permissions
        base_role_id = self._role.get("basedon", self._role_id)

        html.help(
            _(
                "When you leave the permissions at &quot;default&quot; then they get their "
                "settings from the factory defaults (for builtin roles) or from the "
                "factory default of their base role (for user define roles). Factory defaults "
                "may change due to software updates. When choosing another base role, all "
                "permissions that are on default will reflect the new base role."
            )
        )

        for section in permission_section_registry.get_sorted_sections():
            # Now filter by the optional search term
            filtered_perms = []
            for perm in permission_registry.get_sorted_permissions(section):
                if search and (
                    search not in perm.title.lower() and search not in perm.name.lower()
                ):
                    continue

                filtered_perms.append(perm)

            if not filtered_perms:
                continue

            forms.header(section.title, isopen=search is not None, css="wide")
            for perm in filtered_perms:
                forms.section(perm.title)

                pvalue = self._role["permissions"].get(perm.name)
                def_value = base_role_id in perm.defaults

                choices: Choices = [
                    ("yes", _("yes")),
                    ("no", _("no")),
                    ("default", _("default (%s)") % (def_value and _("yes") or _("no"))),
                ]
                deflt = {True: "yes", False: "no"}.get(pvalue, "default")

                html.dropdown("perm_" + perm.name, choices, deflt=deflt, style="width: 130px;")
                html.help(perm.description)

        forms.end()
        html.hidden_fields()
        html.end_form()
Exemplo n.º 14
0
 def render_input(self, varprefix: str, value: Optional[str]) -> None:
     if value is not None:
         html.hidden_field(varprefix + "attr_" + self.name(), value)
         html.write_text(value)