예제 #1
0
def page_notify():
    if not config.user.may("general.notify"):
        raise MKAuthException(
            _("You are not allowed to use the notification module."))

    html.header(_('Notify Users'))

    html.begin_context_buttons()
    html.context_button(_("Users"), "wato.py?mode=users", "back")
    html.end_context_buttons()

    vs_notify = _vs_notify()

    if html.check_transaction():
        try:
            msg = vs_notify.from_html_vars("_notify")
            vs_notify.validate_value(msg, "_notify")
            _process_notify_message(msg)
        except MKUserError as e:
            html.user_error(e)

    html.begin_form("notify", method="POST")
    vs_notify.render_input_as_form("_notify", {})

    html.button("save", _("Send notification"))

    html.hidden_fields()
    html.end_form()
    html.footer()
예제 #2
0
파일: notify.py 프로젝트: PLUTEX/checkmk
def page_notify():
    if not user.may("general.notify"):
        raise MKAuthException(_("You are not allowed to use the notification module."))

    title = _("Notify users")
    breadcrumb = make_simple_page_breadcrumb(mega_menu_registry.menu_setup(), title)
    menu = _page_menu(breadcrumb)
    html.header(title, breadcrumb, menu)

    vs_notify = _vs_notify()

    if transactions.check_transaction():
        try:
            msg = vs_notify.from_html_vars("_notify")
            vs_notify.validate_value(msg, "_notify")
            _process_notify_message(msg)
        except MKUserError as e:
            html.user_error(e)

    html.begin_form("notify", method="POST")
    vs_notify.render_input_as_form("_notify", {})

    html.hidden_fields()
    html.end_form()
    html.footer()
예제 #3
0
def _render_werk_table_options():
    werk_table_options = {}  # type: Dict[str, Any]

    for name, height, vs, default_value in _werk_table_option_entries():
        value = default_value
        try:
            if html.request.has_var("wo_set"):
                value = vs.from_html_vars("wo_" + name)
                vs.validate_value(value, "wo_" + name)
        except MKUserError as e:
            html.user_error(e)

        werk_table_options.setdefault(name, value)

    html.begin_foldable_container("werks",
                                  "options",
                                  isopen=True,
                                  title=_("Searching and Filtering"),
                                  indent=False)
    html.begin_form("werks")
    html.hidden_field("wo_set", "set")
    html.begin_floating_options("werks", is_open=True)
    for name, height, vs, default_value in _werk_table_option_entries():
        html.render_floating_option(name, height, "wo_", vs,
                                    werk_table_options[name])
    html.end_floating_options(reset_url=html.makeuri([], remove_prefix=""))
    html.hidden_fields()
    html.end_form()
    html.end_foldable_container()

    from_date, until_date = Timerange().compute_range(
        werk_table_options["date"])[0]
    werk_table_options["date_range"] = from_date, until_date

    return werk_table_options
예제 #4
0
    def page(self) -> cmk.gui.pages.PageResult:
        """Renders an iframe to view the content of the RobotMK log file"""
        site_id, host_name, service_description = _get_mandatory_request_vars()

        breadcrumb: Breadcrumb = make_service_breadcrumb(
            HostName(host_name), service_description)
        title = self._title() + _(" of service %s on host %s") % (
            service_description, host_name)
        try:
            content = _get_html_from_livestatus(site_id, host_name,
                                                service_description)
        except MKLivestatusNotFoundError:
            html.header(
                title=title,
                breadcrumb=breadcrumb,
            )
            html.user_error(
                MKUserError(None,
                            _("You are not permitted to view this page")))
            return

        if not content[0]:
            html.header(
                title=title,
                breadcrumb=breadcrumb,
            )
            html.user_error(MKUserError(None, _("No logs could be found.")))
            return

        # Only render page menu with download option if content is not empty
        # and user is permitted
        html.header(
            title=title,
            breadcrumb=breadcrumb,
            page_menu=self._page_menu(breadcrumb, site_id, host_name,
                                      service_description),
        )

        iframe: str = "robotmk"
        html.iframe(
            content="",
            src=makeuri_contextless(
                request,
                [
                    ("site", site_id),
                    ("host", host_name),
                    ("service", service_description),
                ],
                filename="robotmk_report.py",
            ),
            name="robotmk_report",
            id_=iframe,
        )

        html.javascript('cmk.utils.content_scrollbar("main_page_content");')
        html.javascript(
            "cmk.utils.add_height_to_simple_bar_content_of_iframe(%s);" %
            json.dumps(iframe))
예제 #5
0
파일: werks.py 프로젝트: m3rlinux/checkmk
def _werk_table_options_from_request() -> Dict[str, Any]:
    if request.var("show_unack") and not request.has_var("wo_set"):
        return _default_werk_table_options()

    werk_table_options: Dict[str, Any] = {}
    for name, _height, vs, default_value in _werk_table_option_entries():
        value = default_value
        try:
            if request.has_var("wo_set"):
                value = vs.from_html_vars("wo_" + name)
                vs.validate_value(value, "wo_" + name)
        except MKUserError as e:
            html.user_error(e)

        werk_table_options.setdefault(name, value)

    from_date, until_date = Timerange.compute_range(werk_table_options["date"]).range
    werk_table_options["date_range"] = from_date, until_date

    return werk_table_options
예제 #6
0
    def render(
        self,
        rows: Rows,
        show_checkboxes: bool,
        num_columns: int,
        show_filters: List[Filter],
        unfiltered_amount_of_rows: int,
    ) -> None:
        view_spec = self.view.spec
        home = ("mobile.py", "Home", "home")

        page = request.var("page")
        if not page:
            if view_spec.get("mustsearch"):
                page = "filter"
            else:
                page = "data"

        title = views.view_title(self.view.spec, self.view.context)
        navbar = [
            ("data", _("Results"), "grid", "results_button"),
            ("filter", _("Filter"), "search", ""),
        ]
        if user.may("general.act"):
            navbar.append(("commands", _("Commands"), "gear", ""))

        # Should we show a page with context links?
        context_links = list(
            views.collect_context_links(self.view,
                                        rows,
                                        mobile=True,
                                        visual_types=["views"]))

        if context_links:
            navbar.append(("context", _("Context"), "arrow-r", ""))
        page_id = "view_" + view_spec["name"]

        if page == "filter":
            jqm_page_header(_("Filter / Search"),
                            left_button=home,
                            id_="filter")
            _show_filter_form(show_filters)
            jqm_page_navfooter(navbar, "filter", page_id)

        elif page == "commands":
            # Page: Commands
            if user.may("general.act"):
                jqm_page_header(_("Commands"),
                                left_button=home,
                                id_="commands")
                show_commands = True
                if request.has_var("_do_actions"):
                    try:
                        show_commands = do_commands(
                            self.view.datasource.infos[0], rows)
                    except MKUserError as e:
                        html.user_error(e)
                        show_commands = True
                if show_commands:
                    _show_command_form(self.view.datasource, rows)
                jqm_page_navfooter(navbar, "commands", page_id)

        elif page == "data":
            # Page: data rows of view
            jqm_page_header(
                title,
                left_button=home,
                right_button=("javascript:document.location.reload();",
                              _("Reload"), "refresh"),
                id_="data",
            )
            html.open_div(id_="view_results")
            if len(rows) == 0:
                html.write_text(_("No hosts/services found."))
            else:
                try:
                    if cmk.gui.view_utils.row_limit_exceeded(
                            unfiltered_amount_of_rows, self.view.row_limit):
                        cmk.gui.view_utils.query_limit_exceeded_warn(
                            self.view.row_limit, user)
                        del rows[self.view.row_limit:]
                    self.view.layout.render(
                        rows,
                        view_spec,
                        self.view.group_cells,
                        self.view.row_cells,
                        num_columns,
                        show_checkboxes and not html.do_actions(),
                    )
                except Exception as e:
                    logger.exception("error rendering mobile view")
                    html.write_text(_("Error showing view: %s") % e)
            html.close_div()
            jqm_page_navfooter(navbar, "data", page_id)

        # Page: Context buttons
        elif page == "context":
            jqm_page_header(_("Context"), left_button=home, id_="context")
            _show_context_links(context_links)
            jqm_page_navfooter(navbar, "context", page_id)
예제 #7
0
def edit_annotation():
    site_id = html.request.var("anno_site") or ""
    hostname = html.request.get_str_input_mandatory("anno_host")
    service = html.request.var("anno_service") or None
    fromtime = html.request.get_float_input_mandatory("anno_from")
    untiltime = html.request.get_float_input_mandatory("anno_until")
    site_host_svc = (site_id, hostname, service)

    # Find existing annotation with this specification
    annotations = availability.load_annotations()
    annotation = availability.find_annotation(annotations, site_host_svc,
                                              fromtime, untiltime)

    if annotation:
        value = annotation.copy()
    else:
        value = {
            "from": fromtime,
            "until": untiltime,
            "text": "",
        }

    value["host"] = hostname
    value["service"] = service
    value["site"] = site_id

    if html.check_transaction():
        try:
            vs = _vs_annotation()
            value = vs.from_html_vars("_editanno")
            vs.validate_value(value, "_editanno")

            site_host_svc = (value["site"], value["host"], value["service"])
            del value["site"]
            del value["host"]
            value["date"] = time.time()
            value["author"] = config.user.id
            availability.update_annotations(site_host_svc,
                                            value,
                                            replace_existing=annotation)
            html.request.del_var("filled_in")
            return False
        except MKUserError as e:
            html.user_error(e)

    title = _("Edit annotation of ") + hostname
    if service:
        title += "/" + service

    html.body_start(title)
    html.top_heading(title)

    html.begin_context_buttons()
    html.context_button(_("Abort"), html.makeuri([("anno_host", "")]), "abort")
    html.end_context_buttons()

    html.begin_form("editanno", method="GET")
    _vs_annotation().render_input_as_form("_editanno", value)

    html.button("save", _("Save"))

    html.hidden_fields()
    html.end_form()

    html.bottom_footer()
    html.body_end()
    return True
예제 #8
0
    def page_list(cls):
        cls.load()

        # custom_columns = []
        # render_custom_buttons = None
        # render_custom_columns = None
        # render_custom_context_buttons = None
        # check_deletable_handler = None

        cls.need_overriding_permission("edit")

        html.header(cls.phrase("title_plural"))
        html.begin_context_buttons()
        html.context_button(cls.phrase("new"), cls.create_url(), "new_" + cls.type_name())

        # TODO: Remove this legacy code as soon as views, dashboards and reports have been
        # moved to pagetypes.py
        html.context_button(_("Views"), "edit_views.py", "view")
        html.context_button(_("Dashboards"), "edit_dashboards.py", "dashboard")

        def has_reporting():
            try:
                # The suppression below is OK, we just want to check if the module is there.
                import cmk.gui.cee.reporting  # noqa: F401 # pylint: disable=unused-variable,redefined-outer-name
                return True
            except ImportError:
                return False

        if has_reporting():
            html.context_button(_("Reports"), "edit_reports.py", "report")

        # ## if render_custom_context_buttons:
        # ##     render_custom_context_buttons()

        for other_type_name, other_pagetype in page_types.items():
            if cls.type_name() != other_type_name:
                html.context_button(
                    other_pagetype.phrase("title_plural").title(), '%ss.py' % other_type_name,
                    other_type_name)
        html.end_context_buttons()

        # Deletion
        delname = html.request.var("_delete")
        if delname and html.transaction_valid():
            owner = UserId(html.request.get_unicode_input_mandatory('_owner', config.user.id))

            try:
                instance = cls.instance((owner, delname))
            except KeyError:
                raise MKUserError(
                    "_delete",
                    _("The %s you are trying to delete "
                      "does not exist.") % cls.phrase("title"))

            if not instance.may_delete():
                raise MKUserError("_delete", _("You are not permitted to perform this action."))

            try:
                if owner != config.user.id:
                    owned_by = _(" (owned by %s)") % owner
                else:
                    owned_by = ""
                c = html.confirm(
                    _("Please confirm the deletion of \"%s\"%s.") % (instance.title(), owned_by))
                if c:
                    cls.remove_instance((owner, delname))
                    cls.save_user_instances(owner)
                    html.reload_sidebar()
                elif c is False:
                    html.footer()
                    return
            except MKUserError as e:
                html.user_error(e)

        # Bulk delete
        if html.request.var("_bulk_delete_my") and html.transaction_valid():
            if cls._bulk_delete_after_confirm("my") is False:
                html.footer()
                return

        elif html.request.var("_bulk_delete_foreign") and html.transaction_valid():
            if cls._bulk_delete_after_confirm("foreign") is False:
                html.footer()
                return

        my_instances, foreign_instances, builtin_instances = cls.get_instances()
        for what, title, instances in [
            ("my", _('Customized'), my_instances),
            ("foreign", _('Owned by other users'), foreign_instances),
            ("builtin", _('Builtin'), builtin_instances),
        ]:
            if not instances:
                continue

            html.open_h3()
            html.write(title)
            html.close_h3()

            if what != "builtin":
                html.begin_form("bulk_delete_%s" % what, method="POST")

            with table_element(limit=None) as table:
                for instance in instances:
                    table.row()

                    if what != "builtin" and instance.may_delete():
                        table.cell(html.render_input(
                            "_toggle_group",
                            type_="button",
                            class_="checkgroup",
                            onclick="cmk.selection.toggle_all_rows(this.form);",
                            value='X'),
                                   sortable=False,
                                   css="checkbox")
                        html.checkbox("_c_%s+%s+%s" % (what, instance.owner(), instance.name()))

                    # Actions
                    table.cell(_('Actions'), css='buttons visuals')

                    # View
                    if isinstance(instance, PageRenderer):
                        html.icon_button(instance.page_url(), _("View"), "new_" + cls.type_name())

                    # Clone / Customize
                    html.icon_button(instance.clone_url(), _("Create a customized copy of this"),
                                     "clone")

                    # Delete
                    if instance.may_delete():
                        html.icon_button(instance.delete_url(), _("Delete!"), "delete")

                    # Edit
                    if instance.may_edit():
                        html.icon_button(instance.edit_url(), _("Edit"), "edit")

                    cls.custom_list_buttons(instance)

                    # Internal ID of instance (we call that 'name')
                    table.cell(_('ID'), instance.name(), css="narrow")

                    # Title
                    table.cell(_('Title'))
                    html.write_text(instance.render_title())
                    html.help(_u(instance.description()))

                    # Custom columns specific to that page type
                    instance.render_extra_columns(table)

                    # ## for title, renderer in custom_columns:
                    # ##     table.cell(title, renderer(visual))

                    # Owner
                    if instance.is_builtin():
                        ownertxt = html.render_i(_("builtin"))
                    else:
                        ownertxt = instance.owner()
                    table.cell(_('Owner'), ownertxt)
                    table.cell(_('Public'), _("yes") if instance.is_public() else _("no"))
                    table.cell(_('Hidden'), _("yes") if instance.is_hidden() else _("no"))

                    # FIXME: WTF?!?
                    # TODO: Haeeh? Another custom columns
                    # ## if render_custom_columns:
                    # ##     render_custom_columns(visual_name, visual)

            if what != "builtin":
                html.button("_bulk_delete_%s" % what,
                            _("Bulk delete"),
                            "submit",
                            style="margin-top:10px")
                html.hidden_fields()
                html.end_form()

        html.footer()
        return
예제 #9
0
def test_user_error(register_builtin_html):
    with html.plugged():
        html.user_error(
            MKUserError(None, "asd <script>alert(1)</script> <br> <b>"))
        c = html.drain()
    assert c == "<div class=\"error\">asd &lt;script&gt;alert(1)&lt;/script&gt; <br> <b></div>"
예제 #10
0
def test_user_error(request_context):
    with output_funnel.plugged():
        html.user_error(
            MKUserError(None, "asd <script>alert(1)</script> <br> <b>"))
        c = output_funnel.drain()
    assert c == '<div class="error">asd &lt;script&gt;alert(1)&lt;/script&gt; <br> <b></div>'