Example #1
0
 def __init__(self, rules):
     Menu.__init__(self)
     window = rules.window
     self.debug = window.debug
     self.create_before = self.add(":/icons/add.png",
         tr("Create before"), self.createAclBefore)
     self.create_after = self.add(":/icons/add.png",
         tr("Create after"), self.createAclAfter)
     self.edit = self.add(":/icons/edit.png",
         tr("Edit"), self.editAcl)
     self.up = self.add(":/icons/up.png",
         tr("Move up"), self.moveUp)
     if window.compatibility.has_move_rule:
         self.move_at = self.add(":/icons/updown.png",
             tr("Move to line..."), self.moveAt)
     else:
         self.move_at = None
     self.down = self.add(":/icons/down.png",
         tr("Move down"), self.moveDown)
     self.clone = self.add(":/icons/copy.png",
         tr("Clone"), self.cloneAcl)
     self.delete = self.add(":/icons/delete.png",
         tr("Delete"), self.deleteAcl)
     self.iptables = self.add(":/icons/apply_rules.png",
         tr("Iptables rules"), self.iptablesRules)
     self.ldap = self.add(":/icons/apply_rules.png",
         tr("LDAP rules"), self.ldapRules)
     self.rules = rules
     self.rule_id = None
     self.identifiers = None
Example #2
0
    def test_ldap(self):
        dc, base, uri, filter, password = self.specific_config.generateTest()
        if uri is None or uri == '':
            QMessageBox.critical(
                self,
                "Missing data",
                "Please fill URI field"
                )
            return
        if dc is None:
            dc == ''

        filter, ok = QInputDialog.getText(
            self,
            tr("LDAP Filter"),
            tr("Please enter a filter:"),
            QLineEdit.Normal,
            filter
            )

        if not ok:
            return

        async = self.mainwindow.client.async()
        async.call(
            'nuauth',
            'testLDAP',
            dc, base, uri, unicode(filter), password,
            callback = self.success_test,
            errback = self.error_test
            )
Example #3
0
 def _setethernetspeed(self, ethernet):
     if ethernet.eth_auto:
         cmd = "/usr/sbin/ethtool -s %s autoneg on" % ethernet.system_name
         self.responsible.feedback(
             tr("Setting up speed for interface %(DESCRIPTION)s: auto"),
             DESCRIPTION=ethernet.fullName()
             )
     else:
         args = {
         'name': ethernet.system_name,
         'duplex': "full" if ethernet.eth_duplex == Ethernet.FULL else "half",
         'speed': ethernet.eth_speed
         }
         cmd = "/usr/sbin/ethtool -s %(name)s autoneg off speed "\
             "%(speed)s duplex %(duplex)s" % args
         self.responsible.feedback(
             tr(
                 "Setting up speed for interface %(DESCRIPTION)s: "
                 "speed: %(SPEED)s, duplex: %(DUPLEX)s."),
             DESCRIPTION=ethernet.fullName(),
             SPEED=args['speed'],
             DUPLEX=args['duplex']
             )
     process = createProcess(self, cmd.split(),
         stdout=subprocess.PIPE,
         stderr=subprocess.STDOUT,
         env={})
     retcode, stdout, stderr = communicateProcess(self, process, 30)
     if retcode == 0:
         return
     else:
         self.responsible.feedback("Could not set speed.")
         #Explicitely catched
         raise EthernetSpeedError("Error while running [%s]." % cmd)
Example #4
0
 def printServerTime(self, time):
     server_time = unicode(datetime.fromtimestamp(float(time)))
     server_time = unicode(htmlBold(server_time))
     html = tr("Server time: %s") % server_time
     html = Html(html, escape=False)
     self.addToInfoArea(html)
     QMessageBox.information(self, tr("Server time"), tr("Server time: %s") % server_time)
Example #5
0
    def _update_gui(self):
        if self.last_updated == ADStatus.UNKNOWN:
            self.status_text.setText(ADStatus.UNKNOWN)
            for widget in (
                self.status_icon,
                self.additional_info,
                ):
                widget.hide()
            return

        if not self.status:
            self.status_icon.show()
            self.additional_info.hide()
            self.status_icon.setPixmap(ADStatus.NOT_MEMBER_PIXMAP)
            self.status_text.setText(ADStatus.NOT_MEMBER)

        for widget in (
            self.status_icon,
            self.additional_info,
            ):
            widget.show()

        self.status_text.setText(
            tr("AD information:")
        )
        info = (
            tr("Domain name: %s") % self.realm,
            tr("Parent server name: %s") % self.parent_server,
            tr("Last updated: %s") % self.last_updated,
            tr("EdenWall/Active Directory time delta: %s second(s)")
                % self.time_offset,
        )
        self.additional_info.setText("\n".join(info))
Example #6
0
    def isValid(self):
        self.message.setNoMessage()
        self.error_message = ''
        hasInvalidData = False
        for widget in [self.dns1, self.dns2]:
            if not widget.isValid():
                hasInvalidData = True
                error = "'%s' : must be '%s'<br />" % (widget.text(), widget.getFieldInfo())
                self.error_message += error
                self.message.setMessage('', "<ul>%s" % error, status=MessageArea.WARNING)

        confs = {
                tr("hostname"): self.qhostnamecfg.cfg,
                tr("DNS"): self.qresolvcfg.cfg
                }

        for name, item in confs.iteritems():
            if not item.isValid():
                hasInvalidData = True
                error = tr("%s configuration is invalid<br />") % name
                self.message.setMessage('', error, status=MessageArea.WARNING)
                self.error_message += error

        if not hasInvalidData:
            error = self.qresolvcfg.resolvcfg.isInvalid()
            if error:
                hasInvalidData = True
                self.error_message = error
                self.message.setMessage('', error, status=MessageArea.WARNING)

        if hasInvalidData:
            self.mainwindow.addToInfoArea(tr("'Hostname and DNS : invalid configuration'"))
            return False
        else:
            return True
Example #7
0
def check_join(logger, responsible):
    """
    'net ads testjoin' should be sufficient in most cases.
    'net rpc testjoin' is a fallback to 'net ads testjoin'
    """
    responsible.feedback(tr("Checking that the group mappings exist."))
    if not exists("/var/lib/samba/winbindd_idmap.tdb"):
        raise NuauthException(NO_MAPPING_EXISTS, "The group mappings don't exist")
    try:
        cmd = ('/usr/bin/net', 'ads', 'testjoin')
        runCommandAndCheck(logger, cmd)
    except RunCommandError:
        pass # another test
    else:
        responsible.feedback(tr("The junction to the Active Directory domain is functional"))
        return # ok

    try:
        cmd = ('/usr/bin/net', 'rpc', 'testjoin')
        runCommandAndCheck(logger, cmd)
    except RunCommandError:
        if responsible is not None:
            responsible.feedback(
                tr("No junction to an Active Directory domain.")
            )
        raise NuauthException(NUAUTH_INVALID_CONF,
            "Domain not available")
    responsible.feedback(tr("The junction to the Active Directory domain is functional"))
Example #8
0
def accept_suppression(dhcprange, parent_widget):
    """
    The net we refer to is not available anymore, do we want this or not
    Let the user choose.
    """
    deletable_tr = tr("Consequence: the following DHCP range will be deleted:")
    deletable_html = u"<ul>"
    deletable_html += "<li>%s %s: %s > %s</li>" % (
        deletable_tr,
        unicode(dhcprange.net),
        unicode(dhcprange.start),
        unicode(dhcprange.end)
        )
    deletable_html += u"</ul>"
    title = tr("DHCP configuration")
    message_box = QMessageBox(parent_widget)
    message_box.setWindowTitle(title)
    message_box.setText(_GENERIC_TEXT)
    message_box.setInformativeText(deletable_html)
    message_box.setStandardButtons(
        QMessageBox.Yes | QMessageBox.Cancel
    )

    clicked_button = message_box.exec_()
    if clicked_button == QMessageBox.Yes:
        return True, _DELETE_RANGE
    return False
Example #9
0
 def setupWindow(self):
     self.setButtons()
     self.setContainer(self.list)
     self.setMenu(UserGroupMenu(self,
         tr("New user group"),
         tr("Edit this user group"),
         tr("Delete this user group")))
Example #10
0
    def build(self, description):
        self.layout().addWidget(self.list)

        cancel = QPushButton(QIcon(":/icons/wrong.png"), tr("Cancel"), self)
        save = QPushButton(QIcon(":/icons/apply.png"), tr("OK"), self)
        save.setDefault(True)

        self.connect(cancel, SIGNAL("clicked()"), self.doClose)
        self.connect(save, SIGNAL("clicked()"), self.doSave)

        self.grid = QWidget(self)
        self.setMinimumWidth(700)
        QGridLayout(self.grid)
        self.grid.layout().addWidget(save, 0, 0, Qt.AlignHCenter)
        self.grid.layout().addWidget(cancel, 0, 1, Qt.AlignHCenter)
        self.layout().addWidget(self.grid)

        self.info.setReadOnly(True)
        if description:
            self.info.append(description)
        else:
            self.info.setVisible(False)

        self.error.setReadOnly(True)
        self.error.setVisible(False)

        self.grid.layout().addWidget(self.info, 1, 0, 1, 0, Qt.AlignHCenter)
        self.grid.layout().addWidget(self.error, 2, 0, 1, 0, Qt.AlignHCenter)
Example #11
0
    def buildInterface(self):
        frame = QFrame()
        layout = QVBoxLayout(frame)
        self.setWidget(frame)
        self.setWidgetResizable(True)

        title = u'<h1>%s</h1>' % self.tr('EdenWall activation keys')
        layout.addWidget(QLabel(title))

        sn = "<strong>%s</strong>" % self.ID
        self.IDLabel = QLabel(tr('This appliance serial number is %s.') % sn)
        self.IDLabel.setTextInteractionFlags(
            Qt.TextSelectableByKeyboard | Qt.TextSelectableByMouse)
        sendLicenseButton = NuConfPageKit.createButton(
            tr('Upload an activation key'), frame, self.mainwindow,
            self.chooseAndSendFile, QIcon(":/icons/up"))
        self.mainwindow.writeAccessNeeded(sendLicenseButton)

        self.table = QTableWidget(0, 4, frame)
        self.table.setEditTriggers(QAbstractItemView.NoEditTriggers)
        self.table.setSelectionMode(QAbstractItemView.NoSelection)
        self.table.horizontalHeader().setStretchLastSection(True)
        self.table.horizontalHeader().setResizeMode(QHeaderView.ResizeToContents)
        self.table.setHorizontalHeaderLabels([
                unicode(translate('MainWindow', 'Activation key owner')),
                unicode(translate('MainWindow', 'Valid until')),
                unicode(translate('MainWindow', 'Days left')),
                unicode(translate('MainWindow', 'Type'))])

        for widget in (self.IDLabel, sendLicenseButton, self.table):
            layout.addWidget(widget)
        layout.addStretch(100)
Example #12
0
    def createInformation(self):
        window = self.library.window
        networks = window.object_libraries["resources"]
        protocols = window.object_libraries["protocols"]

        title = tr("Platform")
        items = []
        for item in self["items"]:
            network = item["network"]
            network = networks[network]
            protocol = item["protocol"]
            protocol = protocols[protocol]
            html = "(%s, %s)" % (
                network.createHTML(tooltip=True, icon=False),
                protocol.createHTML(tooltip=True, icon=False),
            )
            html = Html(html, escape=False)
            items.append(html)
        items = BR.join(items)
        interface = networks[self["interface"]]
        options = [
            (tr("Identifier"), self["id"]),
            (tr("Interface"), interface.createHTML(tooltip=True)),
            (tr("Items"), items),
            (tr("References"), self.createReferencesHTML()),
        ]
        return (title, options)
Example #13
0
    def sort_label(self):
        """ With my args, get a label to say on what field my list is ordered. """

        if not self.args.has_key('sortby') or not arg_types.has_key(self.args['sortby']):
            return tr('No sorting')

        return tr(u'Sorted by %s') % (arg_types[self.args['sortby']].label)
Example #14
0
    def release(self, context, key):
        self.thread_lock.acquire()
        try:
            key = self.cleanKey(key)

            # Get the lock
            if key in self.permanent_locks:
                lock = self.permanent_locks[key]
            else:
                raise LockError(tr('The "%s" lock is not acquired!'), key)

            # PersistentLock owned by another user?
            if isinstance(lock, PersistentLock):
                session = context.getSession()
                lock_session = lock.getSession()
                if lock_session != session:
                    raise LockError(
                        tr('The "%s" lock, owned by %s, can not be released!'),
                        key, unicode(lock_session.user))
            elif isinstance(lock, ComponentLock):
                if lock.getComponentName() != context.component.name:
                    raise LockError(
                        tr('The "%s" lock, owned by the %s component, can not be released!'),
                        key, unicode(lock.getComponentName()))
            # Delete the lock
            self.destroyLock(key)
        finally:
            self.thread_lock.release()
Example #15
0
    def _edit_hostname(self):
        changeable = self.qhostnamecfg.hostnamecfg.changeable

        if not self._can_edit_hostname:
            QMessageBox.critical(
                self,
                _CANNOT_CHANGE_HOSTNAME_TITLE,
                _CANNOT_CHANGE_HOSTNAME,
                )
            return

        if changeable == CHANGE_DISCOURAGED:
            if not self._continue_edit(
                tr("About hostname change", "popup title"),
                _HOSTNAME_CHANGE_DISCLAIMER
                ):
                    return

        hostname, ok = self.__editFieldDialog(
            tr("Edit hostname"),
            tr("Enter new hostname"),
            self.qhostnamecfg.hostnamecfg.hostname
            )

        if ok:
            hostname = unicode(hostname).strip()
            if hostname == self.qhostnamecfg.hostnamecfg.hostname:
                return
            self.qhostnamecfg.pre_modify()
            self.qhostnamecfg.hostnamecfg.hostname = hostname
            self.qhostnamecfg.post_modify()
            self.setModified()
Example #16
0
 def check_proto_not_cleartext(self, options):
     if options['protocol'] == 'http':
         ret = QMessageBox.warning( self, tr("Insecure protocol"),
             tr("You are connecting using an insecure protocol. Everything will be transmitted in clear, including your login and password.\nDo you really want to do that ?"),
             QMessageBox.Ok | QMessageBox.Cancel)
         if ret != QMessageBox.Ok:
             raise RpcdError("UserError", tr("Aborted by user"))
Example #17
0
    def full_test(self):
        fields = {
            self.test_group.server_input: tr("test server field"),
            self.test_group.query_input: tr("test query field"),
        }

        default_test = True

        for item in fields:
            if not item.isEmpty():

                default_test = False

                if not item.isValid():
                    self.mainwindow.addToInfoArea(
                        tr("Wrong value in %s, can not test.") % fields[item]
                    )
                    return

        if default_test:
            self.default_test()
            return

        self.deactivate_tests()

        async = self.client.async()
        async.call('resolv', 'test',
            {
                'server': unicode(self.test_group.server_input.text()).strip(),
                'query': unicode(self.test_group.query_input.text()).strip()
            },
            callback=self.test_success,
            errback=self.test_error
            )
        self.mainwindow.addToInfoArea(tr("Testing DNS server with custom parameters..."))
Example #18
0
def _getTraceback(err, errtype, traceback):
    # Get server traceback (if any)
    if hasattr(err, "traceback") and err.traceback:
        server = list(err.traceback)
        server = _cleanupTraceback(server, tr("Server backtrace:"))
    else:
        server = u''

    # Get client (local) traceback
    info = None
    if traceback is None:
        try:
            info = sys.exc_info()
            sys.exc_clear()
        except Exception:
            info = None
    else:
        info = (errtype, err, traceback)
    if info:
        client = formatTraceback(info)
        client = _cleanupTraceback(client, tr("Client backtrace:"))
    else:
        client = u''

    return server + client
Example #19
0
 def createInformation(self):
     options = [
         (tr('Identifier'), self['id']),
         (tr('Duration'), self.getText()),
         (tr('References'), self.createReferencesHTML()),
     ]
     return tr('Duration'), options
Example #20
0
    def buildInterface(self):
        main_widget = QWidget()
        self.setWidget(main_widget)
        self.setWidgetResizable(True)
        self.form = QFormLayout(main_widget)

        title = u'<h1>%s</h1>' % \
            self.tr('Outgoing HTTP and HTTPS proxy configuration')

        self.form.addRow(QLabel(title))
        self.use_proxy = self.addField(tr("Use proxy"), QCheckBox)
        self.host = self.addField(tr("Host"), IpOrHostnameOrFqdnEdit)
        self.port = self.addField(tr("Port"), PortEdit)
        self.user = self.addField(tr("User"), QLineEdit)
        self.password = self.addField(tr("Password"), PasswordInput)

        self.connect(self.use_proxy, SIGNAL('stateChanged(int)'),
                     self.setUseProxy)
        for pair in (
            (self.host, self.setHost),
            (self.port, self.setPort),
            (self.user, self.setUser),
            (self.password, self.setPassword),
        ):
            self.connect(pair[0], SIGNAL('textEdited(QString)'), pair[1])
Example #21
0
    def build(self):

        #Texts for buttons
        sync_text = tr('Force synchronization')
        get_time_text = tr('Get the EdenWall appliance time')

        #we need to use the longest string to set correct and same
        #width of the buttons
        sync_len = len(sync_text)
        get_time_len = len(get_time_text)
        if sync_len > get_time_len:
            longest_text = sync_text
        else:
            longest_text = get_time_text

        #sync button
        synchronize = TestButton(text=sync_text)
        self.mainwindow.writeAccessNeeded(synchronize)
        self.connect(synchronize, SIGNAL('clicked()'), self.callSynchronize)

        #get time button
        server_time = TestButton(text=get_time_text)
        self.connect(server_time, SIGNAL('clicked()'), self.getServerTime)

        #add to layout and set the same width
        layout = self.layout()
        for button in (synchronize, server_time):
            layout.addWidget(button)
            button.fixWidth(longest_text)

        #the ntp servers tabular
        self.layout().addWidget(self.ntpServers)
Example #22
0
    def __init__(self, parent=None, accept_empty=True):
        LineEdit.__init__(self, netValidator, accept_empty, parent)

        help0 = tr('Enter a network address')
        help1 = "<ul><li>" + tr('either in the form IP/mask 192.168.1.0/255.255.255.0') + "</li>"
        help2 = "<li>" + tr("or in the form IP/prefix 192.168.1.0/24") + "</li></ul>"
        self.setWhatsThis(help0 + help1 + help2)
Example #23
0
    def __init__(self, client, mainwindow, parent=None):
        QFrame.__init__(self, parent)
        self.init_done = False
        self.modified = False
        self.client = client
        self.mainwindow = mainwindow
        self._parent = parent

        form_layout = QVBoxLayout(self)
        title = QLabel("<H1>%s</H1>" % tr('NTP Configuration'))
        form_layout.addWidget(title)

        self.ntpServers = ListEdit()
        self.ntpServers.headers = self.getColumnLabels()
        self.ntpServers.displayUpDown = True
        self.ntpServers.readOnly = mainwindow.readonly
        self.ntpServers.editInPopup = True
        self.ntpServers.setColDelegate(self.createDelegateForColumn)
        self.mainwindow.writeAccessNeeded(self.ntpServers)

        self.connect(self.ntpServers, SIGNAL('itemDeleted'), self.serverDeleted)
        self.connect(self.ntpServers, SIGNAL('itemAdded'), self.serverAdded)
        self.connect(self.ntpServers, SIGNAL('itemModified'), self.serverModified)
        self.connect(self.ntpServers, SIGNAL('itemSorted'), self.serverSorted)

        self.addToInfoArea = mainwindow.addToInfoArea

        if self.resetConf():
            self.addToInfoArea(tr("NTP interface enabled"))
        else:
            self.addToInfoArea(tr("NTP interface disabled: NTP backend not loaded"), category=COLOR_CRITICAL)
            raise NuConfModuleDisabled("NTP")

        self.build()
        self.init_done = True
Example #24
0
    def __init__(self, client, parent):
        ScrollArea.__init__(self)
        self.client = client
        self.mainwindow = parent
        self._modified = False
        self.error_message = ''
        self.config = None
        frame = QFrame(self)
        layout = QGridLayout(frame)

        title = QLabel(u'<H1>%s</H1>' % tr('Contact Configuration'))
        layout.addWidget(title, 0, 0)

        self.admin_mail = self.buildAdminMail(layout, 1, 0)
        self.sender_mail = self.buildSenderMail(layout, 2, 0)
        self.smarthost_group, self.use_smarthost, self.mail_relay = \
            self.buildOutgoing(layout, 3, 0)
        self.language = self.buildChooseLanguage(layout, 4, 0)
        self.buildTestMail(layout, 5, 0)
        layout.setRowStretch(6, 15)

        self.setWidget(frame)
        self.setWidgetResizable(True)

        self.resetConf()
        self.mainwindow.addToInfoArea(tr('Contact interface enabled'))
Example #25
0
 def _genTextFieldsData(self):
     return (
         ('dn_users', tr('LDAP DN for users'), self.setDnUsers),
         ('dn_groups', tr('LDAP DN for groups'), self.setDnGroups),
         ('user', tr('DN used to log in on the LDAP server'), self.setUser),
         ('password', tr('Password used to log in on the LDAP server'), self.setPassword, False)
     )
Example #26
0
def radtest(logger, user, password, server_and_port, shared_secret, timeout=3, nas_port=0):
    """
    server_and_port is expected as "192.168.0.1" or "192.168.0.1:1812"
    """
    if not user:
        return False, tr("This parameter cannot be empty: 'user'.")
    if not password:
        return False, tr("This parameter cannot be empty: 'password'.")
    if not shared_secret:
        return False, tr("This parameter cannot be empty: 'shared secret'.")
    if not isinstance(nas_port, int):
        return False, tr("This parameter should be an integer: 'nas port'")
    nas_port = unicode(nas_port)

    process = createProcess(
        logger,
        (RADTEST_EXE, user, password, server_and_port, nas_port, shared_secret),
        cmdstr="%s <user> <password> %s %s <shared_secret>" % (RADTEST_EXE, server_and_port, nas_port),
        stdout=PIPE,
        stderr=PIPE,
    )
    try:
        exit_status = waitProcess(logger, process, timeout)
    except ProcessError:
        return False, "Timeout reached, probably wrong secret"
    stdout = process.stdout.read()
    stderr = process.stderr.read()

    if exit_status != 0:
        return False, "stdout: %s\nstderr:%s" % (stdout, stderr)

    return _parse_radtest(stdout)
Example #27
0
    def upload_server_cert(self):
        dialog = UploadDialog(
            selector_label=tr("LDAP certificate"),
            filter=tr("Certificate file (*.crt *.pem *)")
            )
        accepted = dialog.exec_()

        if accepted != QDialog.Accepted:
            return

        filename = dialog.filename

        if not filename:
            return
        with open(filename, 'rb') as fd:
            content = fd.read()

        content = encodeFileContent(content)

        self.mainwindow.addToInfoArea(tr('Uploading of a certificate file for the ldap server'))
        async = self.mainwindow.client.async()
        async.call("nuauth", "upload_ldap_server_cert", content,
            callback = self.success_upload,
            errback = self.error_upload
            )
Example #28
0
    def __init__(self, window):
        Ui_Dialog.__init__(self)
        self.window = window
        self.dialog = QDialog(window)
        self.setupUi(self.dialog)
        self.rules = self.window.ruleset("getCustomRules")

        self.ipv_combo.clear()
        for ipv in IPTABLES_TABLES.keys():
            # Fill IPVersion the combo box:
            self.ipv_combo.addItem(ipv)

            # set default string if necessary:
            for table in IPTABLES_TABLES[ipv]:
                if self.rules[ipv][table + "-pre"] == "":
                    self.rules[ipv][table + "-pre"] = DEFAULT_STR % (ipv, table, tr("before"))
                if self.rules[ipv][table + "-post"] == "":
                    self.rules[ipv][table + "-post"] = DEFAULT_STR % (ipv, table, tr("after"))

        self.refreshTableCombo()
        self.refreshFrameText()

        self.previous_ipv, self.previous_table = self.currentIndex()

        self.ipv_combo.connect(self.ipv_combo, SIGNAL("currentIndexChanged (int)"), self.onIPVClick)
        self.table_combo.connect(self.table_combo, SIGNAL("currentIndexChanged (int)"), self.onTableClick)
        self.position_combo.connect(self.position_combo, SIGNAL("currentIndexChanged (int)"), self.onTableClick)

        if self.dialog.exec_():
            self.saveRules()
Example #29
0
    def _user_verify(self, error):
        # temporary implementation using a QMessageBox
        # XXX in the future, we should create a dedicated UI

        # Check wether we should ignore this error
        err_no = error.number
        fingerprint = error.getFingerprint()
        if (fingerprint in self.ignored_errors) \
        and (err_no in self.ignored_errors[fingerprint]):
            return 1
        if (fingerprint in self.temp_ignored_errors) \
        and (err_no in self.temp_ignored_errors[fingerprint]):
            return 1

        msgBox = QMessageBox()
        msgBox.setIcon(QMessageBox.Critical)
        msgBox.setTextFormat(Qt.RichText)
        message = u"<b>%s!</b>" %  error.getMessage()
        msgBox.setText( tr('The "%s" certificate is invalid: %s') % (error.getSubject(), message))
        msgBox.setInformativeText( tr("Do you want to accept the following certificate?") )
        msgBox.setDetailedText(error.getCertText())
        msgBox.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel)
        msgBox.addButton( tr("For this session only"), QMessageBox.AcceptRole )
        msgBox.setDefaultButton(QMessageBox.Cancel)

        ret = msgBox.exec_()
        if ret == QMessageBox.Ok:
            self.ignored_errors[fingerprint].add(err_no)
            self.saveOptions()
        elif ret == QMessageBox.AcceptRole:
            self.temp_ignored_errors[fingerprint].add(err_no)
        if ret in (QMessageBox.Ok, QMessageBox.AcceptRole):
            return 1
        else:
            return 0
Example #30
0
 def showErrors(self, intro = None):
     if not self.errors:
         return
     dialog = QDialog(self.main_window)
     dialog.setObjectName('errorDialog')
     dialog.setWindowTitle(tr('Error(s)'))
     layout = QVBoxLayout(dialog)
     dialog.setLayout(layout)
     if intro != '':
         if intro is None:
             intro = translate('MainWindow',
                 'Some errors were found in this form:')
         label = QLabel(intro)
         layout.addWidget(label)
     for subject, messages in self.errors.items():
         for msg in messages:
             if msg:
                 label = QLabel('- %s%s%s' % (subject,
                     unicode(tr(': ')),
                     unicode(msg)))
             else:
                 label = QLabel('- %s' % unicode(subject))
             layout.addWidget(label)
     button = createButton(translate('MainWindow',
         'Edit again'), dialog, dialog, SLOT('close()'))
     layout.addWidget(button)
     dialog.exec_()