Exemple #1
0
    def action(self):
        delname = html.request.var("_delete")
        if delname and html.transaction_valid():
            if delname in watolib.timeperiods.builtin_timeperiods():
                raise MKUserError("_delete",
                                  _("Builtin timeperiods can not be modified"))

            usages = self._find_usages_of_timeperiod(delname)
            if usages:
                message = "<b>%s</b><br>%s:<ul>" % \
                            (_("You cannot delete this timeperiod."),
                             _("It is still in use by"))
                for title, link in usages:
                    message += '<li><a href="%s">%s</a></li>\n' % (link, title)
                message += "</ul>"
                raise MKUserError(None, message)

            c = wato_confirm(
                _("Confirm deletion of time period %s") % delname,
                _("Do you really want to delete the time period '%s'? I've checked it: "
                  "it is not being used by any rule or user profile right now."
                  ) % delname)
            if c:
                del self._timeperiods[delname]
                watolib.timeperiods.save_timeperiods(self._timeperiods)
                watolib.add_change("edit-timeperiods",
                                   _("Deleted timeperiod %s") % delname)
            elif c is False:
                return ""
Exemple #2
0
    def action(self) -> ActionResult:
        if not html.transaction_valid():
            return None

        action_var = html.request.get_str_input("_action")
        if action_var is None:
            return None

        if action_var != "delete":
            return self._handle_custom_action(action_var)

        if not html.check_transaction():
            return redirect(mode_url(self._mode_type.list_mode_name()))

        entries = self._store.load_for_modification()

        ident = html.request.get_ascii_input("_delete")
        if ident not in entries:
            raise MKUserError("_delete",
                              _("This %s does not exist.") % self._mode_type.name_singular())

        if ident not in self._store.filter_editable_entries(entries):
            raise MKUserError(
                "_delete",
                _("You are not allowed to delete this %s.") % self._mode_type.name_singular())

        self._validate_deletion(ident, entries[ident])

        entry = entries.pop(ident)
        self._add_change("delete", entry,
                         _("Removed the %s '%s'") % (self._mode_type.name_singular(), ident))
        self._store.save(entries)

        flash(_("The %s has been deleted.") % self._mode_type.name_singular())
        return redirect(mode_url(self._mode_type.list_mode_name()))
Exemple #3
0
    def action(self):
        if html.request.var("_update_dns_cache"):
            if not html.check_transaction():
                return None
            config.user.need_permission("wato.update_dns_cache")
            num_updated, failed_hosts = watolib.check_mk_automation(
                self._host.site_id(), "update-dns-cache", [])
            infotext = _(
                "Successfully updated IP addresses of %d hosts.") % num_updated
            if failed_hosts:
                infotext += "<br><br><b>Hostnames failed to lookup:</b> " \
                          + ", ".join(["<tt>%s</tt>" % h for h in failed_hosts])
            return None, infotext

        if html.request.var("delete"):  # Delete this host
            if not html.transaction_valid():
                return "folder"
            return delete_host_after_confirm(self._host.name())

        if html.check_transaction():
            attributes = watolib.collect_attributes(
                "host" if not self._is_cluster() else "cluster", new=False)
            watolib.Host.host(self._host.name()).edit(
                attributes, self._get_cluster_nodes())
            self._host = watolib.Folder.current().host(self._host.name())

        if html.request.var("services"):
            return "inventory"
        if html.request.var("diag_host"):
            html.request.set_var("_start_on_load", "1")
            return "diag_host"
        return "folder"
Exemple #4
0
    def action(self) -> ActionResult:
        if not html.check_transaction():
            return redirect(self.mode_url())

        if html.request.var("_delete"):
            delid = html.request.get_ascii_input_mandatory("_delete")

            if delid not in self._roles:
                raise MKUserError(None, _("This role does not exist."))

            if html.transaction_valid() and self._roles[delid].get('builtin'):
                raise MKUserError(None,
                                  _("You cannot delete the builtin roles!"))

            users = userdb.load_users()
            for user in users.values():
                if delid in user["roles"]:
                    raise MKUserError(
                        None,
                        _("You cannot delete roles, that are still in use (%s)!"
                          % delid))

            self._rename_user_role(delid, None)  # Remove from existing users
            del self._roles[delid]
            self._save_roles()
            watolib.add_change("edit-roles",
                               _("Deleted role '%s'") % delid,
                               sites=config.get_login_sites())

        elif html.request.var("_clone"):
            cloneid = html.request.get_ascii_input_mandatory("_clone")

            try:
                cloned_role = self._roles[cloneid]
            except KeyError:
                raise MKUserError(None, _("This role does not exist."))

            newid = cloneid
            while newid in self._roles:
                newid += "x"

            new_role = {}
            new_role.update(cloned_role)

            new_alias = new_role["alias"]
            while not watolib.is_alias_used("roles", newid, new_alias)[0]:
                new_alias += _(" (copy)")
            new_role["alias"] = new_alias

            if cloned_role.get("builtin"):
                new_role["builtin"] = False
                new_role["basedon"] = cloneid

            self._roles[newid] = new_role
            self._save_roles()
            watolib.add_change("edit-roles",
                               _("Created new role '%s'") % newid,
                               sites=config.get_login_sites())

        return redirect(self.mode_url())
Exemple #5
0
    def action(self):
        if not html.transaction_valid():
            return "folder"

        attributes = watolib.collect_attributes(self._host_type_name(), new=True)
        cluster_nodes = self._get_cluster_nodes()

        hostname = html.request.get_ascii_input_mandatory("host")
        Hostname().validate_value(hostname, "host")

        if html.check_transaction():
            watolib.Folder.current().create_hosts([(hostname, attributes, cluster_nodes)])

        self._host = watolib.Folder.current().host(hostname)

        inventory_url = watolib.folder_preserving_link([
            ("mode", "inventory"),
            ("host", self._host.name()),
            ("_scan", "1"),
        ])

        create_msg = None if self._host.is_ping_host() else (
            _('Successfully created the host. Now you should do a '
              '<a href="%s">service discovery</a> in order to auto-configure '
              'all services to be checked on this host.') % inventory_url)

        if html.request.var("services"):
            raise HTTPRedirect(inventory_url)

        if html.request.var("diag_host"):
            html.request.set_var("_try", "1")
            return "diag_host", create_msg

        return "folder", create_msg
Exemple #6
0
def edit_dictionaries(dictionaries: 'Sequence[Tuple[str, Union[Transform, Dictionary]]]',
                      value: Dict[str, Any],
                      focus: Optional[str] = None,
                      hover_help: bool = True,
                      validate: Optional[Callable[[Any], None]] = None,
                      title: Optional[str] = None,
                      method: str = "GET",
                      preview: bool = False,
                      varprefix: str = "",
                      formname: str = "form",
                      consume_transid: bool = True):

    if html.request.get_ascii_input("filled_in") == formname and html.transaction_valid():
        if not preview and consume_transid:
            html.check_transaction()

        messages: List[str] = []
        new_value: Dict[str, Dict[str, Any]] = {}
        for keyname, vs_dict in dictionaries:
            dict_varprefix = varprefix + keyname
            new_value[keyname] = {}
            try:
                edited_value = vs_dict.from_html_vars(dict_varprefix)
                vs_dict.validate_value(edited_value, dict_varprefix)
                new_value[keyname].update(edited_value)
            except MKUserError as e:
                messages.append("%s: %s" % (vs_dict.title() or _("Properties"), e))
                html.add_user_error(e.varname, e)
            except Exception as e:
                messages.append("%s: %s" % (vs_dict.title() or _("Properties"), e))
                html.add_user_error(None, e)

            if validate and not html.has_user_errors():
                try:
                    validate(new_value[keyname])
                except MKUserError as e:
                    messages.append("%s" % e)
                    html.add_user_error(e.varname, e)

        if messages:
            messages_joined = "".join(["%s<br>\n" % m for m in messages])
            if not preview:
                html.show_error(messages_joined)
            else:
                raise MKUserError(None, messages_joined)
        else:
            return new_value

    html.begin_form(formname, method=method)
    for keyname, vs_dict in dictionaries:
        dict_varprefix = varprefix + keyname
        subvalue = value.get(keyname, {})
        vs_dict.render_input_as_form(dict_varprefix, subvalue)

    end()
    # Should be ignored be hidden_fields, but I do not dare to change it there
    html.request.del_var("filled_in")
    html.hidden_fields()
    html.end_form()
Exemple #7
0
    def action(self):
        if html.transaction_valid():
            if html.request.has_var("_do_upload"):
                self._upload_csv_file()

            self._read_csv_file()

            if html.request.var("_do_import"):
                return self._import()
Exemple #8
0
    def action(self) -> ActionResult:
        if not html.transaction_valid():
            return redirect(mode_url(self._mode_type.list_mode_name()))

        vs = self.valuespec()

        config = vs.from_html_vars("_edit")
        vs.validate_value(config, "_edit")

        if "ident" in config:
            self._ident = config.pop("ident")
        self._entry = config

        entries = self._store.load_for_modification()

        if self._new and self._ident in entries:
            raise MKUserError(
                "ident",
                _("This ID is already in use. Please choose another one."))

        if not self._new and self._ident not in self._store.filter_editable_entries(
                entries):
            raise MKUserError(
                "ident",
                _("You are not allowed to edit this %s.") %
                self._mode_type.name_singular())

        if self._new:
            entries[self._ident] = self._entry
            self._add_change(
                action="add",
                text=_("Added the %s '%s'") %
                (self._mode_type.name_singular(), self._ident),
                affected_sites=self._mode_type.affected_sites(self._entry),
            )
        else:
            current_sites = self._mode_type.affected_sites(self._entry)
            previous_sites = self._mode_type.affected_sites(
                entries[self._ident])

            affected_sites = (None if current_sites is None
                              or previous_sites is None else sorted(
                                  {*previous_sites, *current_sites}))

            entries[self._ident] = self._entry

            self._add_change(
                action="edit",
                text=_("Edited the %s '%s'") %
                (self._mode_type.name_singular(), self._ident),
                affected_sites=affected_sites,
            )

        self._save(entries)

        return redirect(mode_url(self._mode_type.list_mode_name()))
Exemple #9
0
    def action(self) -> ActionResult:
        if html.transaction_valid():
            if html.request.has_var("_do_upload"):
                self._upload_csv_file()

            csv_reader = self._open_csv_file()

            if html.request.var("_do_import"):
                return self._import(csv_reader)
        return None
Exemple #10
0
def handle_edit_annotations():
    # Avoid reshowing edit form after edit and reload
    if html.is_transaction() and not html.transaction_valid():
        return False
    if html.request.var("anno_host") and not html.request.var("_delete_annotation"):
        finished = edit_annotation()
    else:
        finished = False

    return finished
Exemple #11
0
    def action(self):
        if html.request.var("_delete"):
            delid = html.request.var("_delete")

            if delid not in self._roles:
                raise MKUserError(None, _("This role does not exist."))

            if html.transaction_valid() and self._roles[delid].get('builtin'):
                raise MKUserError(None,
                                  _("You cannot delete the builtin roles!"))

            c = wato_confirm(
                _("Confirm deletion of role %s") % delid,
                _("Do you really want to delete the role %s?") % delid)
            if c:
                self._rename_user_role(delid,
                                       None)  # Remove from existing users
                del self._roles[delid]
                self._save_roles()
                watolib.add_change("edit-roles",
                                   _("Deleted role '%s'") % delid,
                                   sites=config.get_login_sites())
            elif c is False:
                return ""

        elif html.request.var("_clone"):
            if html.check_transaction():
                cloneid = html.request.var("_clone")

                try:
                    cloned_role = self._roles[cloneid]
                except KeyError:
                    raise MKUserError(None, _("This role does not exist."))

                newid = cloneid
                while newid in self._roles:
                    newid += "x"

                new_role = {}
                new_role.update(cloned_role)

                new_alias = new_role["alias"]
                while not watolib.is_alias_used("roles", newid, new_alias)[0]:
                    new_alias += _(" (copy)")
                new_role["alias"] = new_alias

                if cloned_role.get("builtin"):
                    new_role["builtin"] = False
                    new_role["basedon"] = cloneid

                self._roles[newid] = new_role
                self._save_roles()
                watolib.add_change("edit-roles",
                                   _("Created new role '%s'") % newid,
                                   sites=config.get_login_sites())
Exemple #12
0
def edit_valuespec(
        vs,  # type: Dictionary
        value,  # type: Dict[str, Any]
        buttontext=None,  # type: Optional[Text]
        method="GET",  # type: str
        varprefix="",  # type: str
        validate=None,  # type: Optional[Callable[[Dict[str, Any]], None]]
        formname="form",  # type: str
        consume_transid=True,  # type: bool
        focus=None  # type: Optional[str]
):
    # type: (...) -> Optional[Dict[str, Any]]

    if html.request.get_ascii_input(
            "filled_in") == formname and html.transaction_valid():
        if consume_transid:
            html.check_transaction()

        messages = []
        try:
            new_value = vs.from_html_vars(varprefix)
            vs.validate_value(new_value, varprefix)

        except MKUserError as e:
            messages.append("%s: %s" % (vs.title(), e.message))
            html.add_user_error(e.varname, e.message)

        if validate and not html.has_user_errors():
            try:
                validate(new_value)
            except MKUserError as e:
                messages.append(e.message)
                html.add_user_error(e.varname, e.message)

        if messages:
            html.show_error("".join(["%s<br>\n" % m for m in messages]))
        else:
            return new_value

    html.begin_form(formname, method=method)
    html.help(vs.help())
    vs.render_input(varprefix, value)
    if buttontext is None:
        buttontext = _("Save")
    html.button("save", buttontext)
    # Should be ignored be hidden_fields, but I do not dare to change it there
    html.request.del_var("filled_in")
    html.hidden_fields()
    if focus:
        html.set_focus(focus)
    else:
        vs.set_focus(varprefix)
    html.end_form()
    return None
Exemple #13
0
    def _action(self):
        if not html.transaction_valid():
            return

        action_handler = gui_background_job.ActionHandler()

        if action_handler.handle_actions() and action_handler.did_delete_job():
            raise HTTPRedirect(
                html.makeuri_contextless([
                    ("host", self._request.host.name()),
                    ("type", self._request.agent_type),
                    ("back_url", self._back_url),
                ]))
Exemple #14
0
    def _action(self) -> None:
        if not html.transaction_valid():
            return

        action_handler = gui_background_job.ActionHandler(
            self._breadcrumb(self._title()))

        if action_handler.handle_actions() and action_handler.did_delete_job():
            raise HTTPRedirect(
                makeuri_contextless(
                    global_request,
                    [
                        ("host", self._request.host.name()),
                        ("type", self._request.agent_type),
                        ("back_url", self._back_url),
                    ],
                ))
Exemple #15
0
    def action(self):
        if not html.transaction_valid():
            return

        action_var = html.request.get_str_input("_action")
        if action_var is None:
            return

        if action_var != "delete":
            return self._handle_custom_action(action_var)

        confirm = wato_confirm(_("Confirm deletion"),
                               self._delete_confirm_message())
        if confirm is False:
            return False
        if not confirm:
            return
        html.check_transaction()  # invalidate transid

        entries = self._store.load_for_modification()

        ident = html.request.get_ascii_input("_delete")
        if ident not in entries:
            raise MKUserError(
                "_delete",
                _("This %s does not exist.") % self._mode_type.name_singular())

        if ident not in self._store.filter_editable_entries(entries):
            raise MKUserError(
                "_delete",
                _("You are not allowed to delete this %s.") %
                self._mode_type.name_singular())

        self._validate_deletion(ident, entries[ident])

        entry = entries.pop(ident)
        self._add_change(
            "delete", entry,
            _("Removed the %s '%s'") %
            (self._mode_type.name_singular(), ident))
        self._store.save(entries)

        return None, _(
            "The %s has been deleted.") % self._mode_type.name_singular()
Exemple #16
0
    def action(self):
        if not html.transaction_valid():
            return self._mode_type.list_mode_name()

        vs = self.valuespec()

        config = vs.from_html_vars("_edit")
        vs.validate_value(config, "_edit")

        if "ident" in config:
            self._ident = config.pop("ident")
        self._entry = config

        entries = self._store.load_for_modification()

        if self._new and self._ident in entries:
            raise MKUserError(
                "ident",
                _("This ID is already in use. Please choose another one."))

        if not self._new and self._ident not in self._store.filter_editable_entries(
                entries):
            raise MKUserError(
                "ident",
                _("You are not allowed to edit this %s.") %
                self._mode_type.name_singular())

        entries[self._ident] = self._entry

        if self._new:
            self._add_change(
                "add", self._entry,
                _("Added the %s '%s'") %
                (self._mode_type.name_singular(), self._ident))
        else:
            self._add_change(
                "edit", self._entry,
                _("Edited the %s '%s'") %
                (self._mode_type.name_singular(), self._ident))

        self._save(entries)

        return self._mode_type.list_mode_name()
Exemple #17
0
    def action(self) -> ActionResult:
        if html.request.var("_search"):  # just commit to search form
            return None

        folder_url = self._folder.url()

        # Operations on SUBFOLDERS

        if html.request.var("_delete_folder"):
            if html.check_transaction():
                self._folder.delete_subfolder(html.request.var("_delete_folder"))
            return redirect(folder_url)

        if html.request.has_var("_move_folder_to"):
            if html.check_transaction():
                what_folder = watolib.Folder.folder(html.request.var("_ident"))
                target_folder = watolib.Folder.folder(html.request.var("_move_folder_to"))
                watolib.Folder.current().move_subfolder_to(what_folder, target_folder)
            return redirect(folder_url)

        # Operations on HOSTS

        # Deletion of single hosts
        delname = html.request.var("_delete_host")
        if delname and watolib.Folder.current().has_host(delname):
            watolib.Folder.current().delete_hosts([delname])
            return redirect(folder_url)

        # Move single hosts to other folders
        if html.request.has_var("_move_host_to"):
            hostname = html.request.var("_ident")
            if hostname and watolib.Folder.current().has_host(hostname):
                target_folder = watolib.Folder.folder(html.request.var("_move_host_to"))
                watolib.Folder.current().move_hosts([hostname], target_folder)
                return redirect(folder_url)

        # bulk operation on hosts
        if not html.transaction_valid():
            return redirect(folder_url)

        # Host table: No error message on search filter reset
        if html.request.var("_hosts_reset_sorting") or html.request.var("_hosts_sort"):
            return None

        selected_host_names = get_hostnames_from_checkboxes()
        if not selected_host_names:
            raise MKUserError(None,
                              _("Please select some hosts before doing bulk operations on hosts."))

        # Move
        if html.request.var("_bulk_move"):
            target_folder_path = html.request.var("_bulk_moveto",
                                                  html.request.var("_top_bulk_moveto"))
            if target_folder_path == "@":
                raise MKUserError("_bulk_moveto", _("Please select the destination folder"))
            target_folder = watolib.Folder.folder(target_folder_path)
            watolib.Folder.current().move_hosts(selected_host_names, target_folder)
            flash(_("Moved %d hosts to %s") % (len(selected_host_names), target_folder.title()))
            return redirect(folder_url)

        # Move to target folder (from import)
        if html.request.var("_bulk_movetotarget"):
            self._move_to_imported_folders(selected_host_names)
            return redirect(folder_url)

        # Deletion
        if html.request.var("_bulk_delete"):
            return self._delete_hosts(selected_host_names)

        search_text = html.request.get_unicode_input_mandatory("search", "")
        for request_var, mode_name in [
            ("_bulk_inventory", "bulkinventory"),
            ("_parentscan", "parentscan"),
            ("_bulk_edit", "bulkedit"),
            ("_bulk_cleanup", "bulkcleanup"),
        ]:
            if html.request.var(request_var):
                return redirect(
                    self._folder.url(add_vars=[
                        ("mode", mode_name),
                        ("search", search_text),
                        ("selection", weblib.selection_id()),
                    ]))

        return None
Exemple #18
0
def edit_dictionaries(dictionaries,
                      value,
                      focus=None,
                      hover_help=True,
                      validate=None,
                      buttontext=None,
                      title=None,
                      buttons=None,
                      method="GET",
                      preview=False,
                      varprefix="",
                      formname="form",
                      consume_transid=True):

    # Convert list of entries/dictionaries
    sections = []
    for keyname, d in dictionaries:
        if isinstance(d, list):
            sections.append((keyname, title or _("Properties"), d))
        else:
            sections.append((keyname, None,
                             d))  # valuespec Dictionary, title used from dict

    if html.request.var("filled_in") == formname and html.transaction_valid():
        if not preview and consume_transid:
            html.check_transaction()

        messages = []
        new_value = {}
        for keyname, _section_title, entries in sections:
            if isinstance(entries, list):
                new_value[keyname] = value.get(keyname, {}).copy()
                for name, vs in entries:
                    if len(sections) == 1:
                        vp = varprefix
                    else:
                        vp = keyname + "_" + varprefix
                    try:
                        v = vs.from_html_vars(vp + name)
                        vs.validate_value(v, vp + name)
                        new_value[keyname][name] = v
                    except MKUserError as e:
                        messages.append("%s: %s" % (vs.title(), e))
                        html.add_user_error(e.varname, e)

            else:
                new_value[keyname] = {}
                try:
                    edited_value = entries.from_html_vars(keyname)
                    entries.validate_value(edited_value, keyname)
                    new_value[keyname].update(edited_value)
                except MKUserError as e:
                    messages.append("%s: %s" %
                                    (entries.title() or _("Properties"), e))
                    html.add_user_error(e.varname, e)
                except Exception as e:
                    messages.append("%s: %s" %
                                    (entries.title() or _("Properties"), e))
                    html.add_user_error(None, e)

            if validate and not html.has_user_errors():
                try:
                    validate(new_value[keyname])
                except MKUserError as e:
                    messages.append(e)
                    html.add_user_error(e.varname, e)

        if messages:
            messages_joined = "".join(["%s<br>\n" % m for m in messages])
            if not preview:
                html.show_error(messages_joined)
            else:
                raise MKUserError(None, messages_joined)
        else:
            return new_value

    html.begin_form(formname, method=method)
    for keyname, title1, entries in sections:
        subvalue = value.get(keyname, {})
        if isinstance(entries, list):
            header(title1)
            first = True
            for name, vs in entries:
                section(vs.title())
                html.help(vs.help())
                if name in subvalue:
                    v = subvalue[name]
                else:
                    v = vs.default_value()
                if len(sections) == 1:
                    vp = varprefix
                else:
                    vp = keyname + "_" + varprefix
                vs.render_input(vp + name, v)
                if (not focus and first) or (name == focus):
                    vs.set_focus(vp + name)
                    first = False
        else:
            entries.render_input_as_form(keyname, subvalue)

    end()
    if buttons:
        for name, button_title, _icon in buttons:
            html.button(name, button_title)
    else:
        if buttontext is None:
            buttontext = _("Save")
        html.button("save", buttontext)
    # Should be ignored be hidden_fields, but I do not dare to change it there
    html.request.del_var("filled_in")
    html.hidden_fields()
    html.end_form()
Exemple #19
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
Exemple #20
0
    def action(self):
        if html.request.var("_search"):  # just commit to search form
            return

        # Operations on SUBFOLDERS

        if html.request.var("_delete_folder"):
            if html.transaction_valid():
                return self._delete_subfolder_after_confirm(
                    html.request.var("_delete_folder"))
            return

        elif html.request.has_var("_move_folder_to"):
            if html.check_transaction():
                what_folder = watolib.Folder.folder(html.request.var("_ident"))
                target_folder = watolib.Folder.folder(
                    html.request.var("_move_folder_to"))
                watolib.Folder.current().move_subfolder_to(
                    what_folder, target_folder)
            return

        # Operations on HOSTS

        # Deletion of single hosts
        delname = html.request.var("_delete_host")
        if delname and watolib.Folder.current().has_host(delname):
            return delete_host_after_confirm(delname)

        # Move single hosts to other folders
        if html.request.has_var("_move_host_to"):
            hostname = html.request.var("_ident")
            if hostname:
                target_folder = watolib.Folder.folder(
                    html.request.var("_move_host_to"))
                watolib.Folder.current().move_hosts([hostname], target_folder)
                return

        # bulk operation on hosts
        if not html.transaction_valid():
            return

        # Host table: No error message on search filter reset
        if html.request.var("_hosts_reset_sorting") or html.request.var(
                "_hosts_sort"):
            return

        selected_host_names = get_hostnames_from_checkboxes()
        if len(selected_host_names) == 0:
            raise MKUserError(
                None,
                _("Please select some hosts before doing bulk operations on hosts."
                  ))

        if html.request.var("_bulk_inventory"):
            return "bulkinventory"

        elif html.request.var("_parentscan"):
            return "parentscan"

        # Deletion
        if html.request.var("_bulk_delete"):
            return self._delete_hosts_after_confirm(selected_host_names)

        # Move
        elif html.request.var("_bulk_move"):
            target_folder_path = html.request.var(
                "bulk_moveto", html.request.var("_top_bulk_moveto"))
            if target_folder_path == "@":
                raise MKUserError("bulk_moveto",
                                  _("Please select the destination folder"))
            target_folder = watolib.Folder.folder(target_folder_path)
            watolib.Folder.current().move_hosts(selected_host_names,
                                                target_folder)
            return None, _("Moved %d hosts to %s") % (len(selected_host_names),
                                                      target_folder.title())

        # Move to target folder (from import)
        elif html.request.var("_bulk_movetotarget"):
            return self._move_to_imported_folders(selected_host_names)

        elif html.request.var("_bulk_edit"):
            return "bulkedit"

        elif html.request.var("_bulk_cleanup"):
            return "bulkcleanup"
Exemple #21
0
def edit_dictionaries(
        dictionaries,  # type: List[Tuple[str, Union[Transform, Dictionary]]]
        value,  # type: Dict[str, Any]
        focus=None,  # type: Optional[str]
        hover_help=True,  # type: bool
        validate=None,  # type: Optional[Callable[[Any], None]]
        buttontext=None,  # type: Optional[Text]
        title=None,  # type: Optional[Text]
        buttons=None,  # type: List[Tuple[str, Text, str]]
        method="GET",  # type: str
        preview=False,  # type: bool
        varprefix="",  # type: str
        formname="form",  # type: str
        consume_transid=True  # type: bool
):

    if html.request.get_ascii_input(
            "filled_in") == formname and html.transaction_valid():
        if not preview and consume_transid:
            html.check_transaction()

        messages = []  # type: List[Text]
        new_value = {}  # type: Dict[str, Dict[str, Any]]
        for keyname, vs_dict in dictionaries:
            dict_varprefix = varprefix + keyname
            new_value[keyname] = {}
            try:
                edited_value = vs_dict.from_html_vars(dict_varprefix)
                vs_dict.validate_value(edited_value, dict_varprefix)
                new_value[keyname].update(edited_value)
            except MKUserError as e:
                messages.append("%s: %s" %
                                (vs_dict.title() or _("Properties"), e))
                html.add_user_error(e.varname, e)
            except Exception as e:
                messages.append("%s: %s" %
                                (vs_dict.title() or _("Properties"), e))
                html.add_user_error(None, e)

            if validate and not html.has_user_errors():
                try:
                    validate(new_value[keyname])
                except MKUserError as e:
                    messages.append("%s" % e)
                    html.add_user_error(e.varname, e)

        if messages:
            messages_joined = "".join(["%s<br>\n" % m for m in messages])
            if not preview:
                html.show_error(messages_joined)
            else:
                raise MKUserError(None, messages_joined)
        else:
            return new_value

    html.begin_form(formname, method=method)
    for keyname, vs_dict in dictionaries:
        dict_varprefix = varprefix + keyname
        subvalue = value.get(keyname, {})
        vs_dict.render_input_as_form(dict_varprefix, subvalue)

    end()
    if buttons:
        for name, button_title, _icon in buttons:
            html.button(name, button_title)
    else:
        if buttontext is None:
            buttontext = _("Save")
        html.button("save", buttontext)
    # Should be ignored be hidden_fields, but I do not dare to change it there
    html.request.del_var("filled_in")
    html.hidden_fields()
    html.end_form()