Example #1
0
    def GET(self, cur_page=1):
        i = web.input()
        cur_page = int(cur_page)

        if cur_page == 0:
            cur_page == 1

        adminLib = adminlib.Admin()
        result = adminLib.listAccounts(cur_page=cur_page)
        if result[0] is True:
            (total, records) = (result[1], result[2])

            # Get list of global admins.
            allGlobalAdmins = []
            connutils = connUtils.Utils()
            qr = connutils.getAllGlobalAdmins()
            if qr[0] is True:
                allGlobalAdmins = qr[1]

            return web.render(
                'dbmail_mysql/admin/list.html',
                cur_page=cur_page,
                total=total,
                admins=records,
                allGlobalAdmins=allGlobalAdmins,
                msg=i.get('msg', None),
            )
        else:
            raise web.seeother('/domains?msg=%s' % web.urlquote(result[1]))
Example #2
0
    def add(self, data):
        self.domain = web.safestr(data.get('domainName', '')).strip().lower()

        # Get company/organization name.
        cn = data.get('cn', '')

        # Check domain name.
        if not iredutils.isDomain(self.domain):
            return (False, 'INVALID_DOMAIN_NAME')

        # Check whether domain name already exist (domainName, domainAliasName).
        connutils = connUtils.Utils()
        if connutils.isDomainExists(self.domain):
            return (False, 'ALREADY_EXISTS')

        # Add domain in database.
        try:
            self.conn.insert(
                'dbmail_domains',
                domain=self.domain,
                description=cn,
                transport=settings.DBMAIL_DEFAULT_DOMAIN_TRANSPORT,
            )
            web.logger(
                msg="Create domain: %s." % (self.domain),
                domain=self.domain,
                event='create',
            )
        except Exception, e:
            return (False, str(e))
Example #3
0
    def POST(self):
        i = web.input(accountType=[], accountStatus=[],)
        searchString = i.get('searchString', '')
        if len(searchString) == 0:
            raise web.seeother('/search?msg=EMPTY_STRING')

        accountType = i.get('accountType', [])
        accountStatus = i.get('accountStatus', [])

        try:
            connutils = connUtils.Utils()
            qr = connutils.search(searchString,
                                  accountType=accountType,
                                  accountStatus=accountStatus,
                                  )
            if qr[0] is False:
                return web.render(
                    'mysql/search.html',
                    msg=qr[1],
                    searchString=searchString,
                )
        except Exception, e:
            return web.render(
                'mysql/search.html',
                msg=str(e),
                searchString=searchString,
            )
Example #4
0
    def GET(
        self,
        domain=None,
    ):
        if domain is None:
            self.cur_domain = None
        else:
            self.cur_domain = str(domain)
            if not iredutils.isDomain(self.cur_domain):
                raise web.seeother('/domains?msg=INVALID_DOMAIN_NAME')

        i = web.input()

        # Get all managed domains.
        connutils = connUtils.Utils()
        qr = connutils.getManagedDomains(
            admin=session.get('username'),
            domainNameOnly=True,
        )

        if qr[0] is True:
            allDomains = qr[1]
        else:
            raise web.seeother('/domains?msg=' + web.urlquote(qr[1]))

        # Set first domain as current domain.
        if self.cur_domain is None:
            if len(allDomains) > 0:
                raise web.seeother('/create/alias/%s' % str(allDomains[0]))
            else:
                raise web.seeother('/domains?msg=NO_DOMAIN_AVAILABLE')

        # Get domain profile.
        domainLib = domainlib.Domain()
        resultOfProfile = domainLib.profile(domain=self.cur_domain)
        if resultOfProfile[0] is True:
            self.profile = resultOfProfile[1]
        else:
            raise web.seeother('/domains?msg=%s' %
                               web.urlquote(resultOfProfile[1]))

        # Cet total number and allocated quota size of existing users under domain.
        self.numberOfExistAccounts = 0

        resultOfCount = domainLib.getCountsOfExistAccountsUnderDomain(
            domain=self.cur_domain,
            accountType='alias',
        )
        if resultOfCount[0] is True:
            self.numberOfExistAccounts = resultOfCount[1]

        return web.render(
            'dbmail_mysql/alias/create.html',
            cur_domain=self.cur_domain,
            allDomains=allDomains,
            profile=self.profile,
            numberOfExistAccounts=self.numberOfExistAccounts,
            numberOfAccounts=2,
            msg=i.get('msg'),
        )
Example #5
0
    def GET(self, profile_type, mail):
        i = web.input()
        self.mail = web.safestr(mail)
        self.profile_type = web.safestr(profile_type)

        if not iredutils.isEmail(self.mail):
            raise web.seeother('/admins?msg=INVALID_MAIL')

        if session.get('domainGlobalAdmin'
                       ) is not True and session.get('username') != self.mail:
            # Don't allow to view/update other admins' profile.
            raise web.seeother(
                '/profile/admin/general/%s?msg=PERMISSION_DENIED' %
                session.get('username'))

        adminLib = adminlib.Admin()
        result = adminLib.profile(mail=self.mail)

        if result[0] is True:
            domainGlobalAdmin, profile = result[1], result[2]

            # Get all domains.
            self.allDomains = []

            domainLib = domainlib.Domain()
            resultOfAllDomains = domainLib.getAllDomains()
            if resultOfAllDomains[0] is True:
                self.allDomains = resultOfAllDomains[1]

            # Get managed domains.
            self.managedDomains = []

            connutils = connUtils.Utils()
            qr = connutils.getManagedDomains(
                admin=self.mail,
                domainNameOnly=True,
                listedOnly=True,
            )
            if qr[0] is True:
                self.managedDomains += qr[1]

            return web.render(
                'dbmail_mysql/admin/profile.html',
                mail=self.mail,
                profile_type=self.profile_type,
                domainGlobalAdmin=domainGlobalAdmin,
                profile=profile,
                languagemaps=languages.getLanguageMaps(),
                allDomains=self.allDomains,
                managedDomains=self.managedDomains,
                min_passwd_length=cfg.general.get('min_passwd_length', '0'),
                max_passwd_length=cfg.general.get('max_passwd_length', '0'),
                msg=i.get('msg'),
            )
        else:
            raise web.seeother('/admins?msg=' + web.urlquote(result[1]))
Example #6
0
    def add(self, data):
        self.cn = data.get('cn', '')
        self.mail = web.safestr(data.get('mail')).strip().lower()

        if not iredutils.isEmail(self.mail):
            return (False, 'INVALID_MAIL')

        # Check admin exist.
        connutils = connUtils.Utils()
        if connutils.isAdminExists(self.mail):
            return (False, 'ALREADY_EXISTS')

        # Get domainGlobalAdmin setting.
        self.domainGlobalAdmin = web.safestr(data.get('domainGlobalAdmin', 'no'))
        if self.domainGlobalAdmin not in ['yes', 'no', ]:
            self.domainGlobalAdmin = 'no'

        # Get language setting.
        preferredLanguage = web.safestr(data.get('preferredLanguage', 'en_US'))

        # Get new password.
        self.newpw = web.safestr(data.get('newpw'))
        self.confirmpw = web.safestr(data.get('confirmpw'))

        result = iredutils.verifyNewPasswords(self.newpw, self.confirmpw)

        if result[0] is True:
            self.passwd = result[1]
        else:
            return result

        try:
            self.conn.insert(
                'dbmail_admins',
                username=self.mail,
                name=self.cn,
                password=iredutils.getSQLPassword(self.passwd),
                language=preferredLanguage,
                created=iredutils.getGMTTime(),
                active='1',
            )

            if self.domainGlobalAdmin == 'yes':
                self.conn.insert(
                    'dbmail_domain_admins',
                    username=self.mail,
                    domain='ALL',
                    created=iredutils.getGMTTime(),
                    active='1',
                )

            web.logger(msg="Create admin: %s." % (self.mail), event='create',)
            return (True,)
        except Exception, e:
            return (False, str(e))
Example #7
0
    def add(self, domain, data):
        # Get domain name, username, cn.
        self.domain = web.safestr(data.get('domainName')).strip().lower()
        self.username = web.safestr(data.get('listname')).strip().lower()
        self.mail = self.username + '@' + self.domain

        if self.domain != domain:
            return (False, 'PERMISSION_DENIED')

        if not iredutils.isDomain(self.domain):
            return (False, 'INVALID_DOMAIN_NAME')

        if not iredutils.isEmail(self.mail):
            return (False, 'INVALID_MAIL')

        # Define columns and values used to insert.
        columns = {'domain': self.domain, 'alias': self.mail, }

        # Check account existing.
        connutils = connUtils.Utils()
        if connutils.isEmailExists(mail=self.mail):
            return (False, 'ALREADY_EXISTS')

        # Get domain profile.
        domainLib = domainlib.Domain()
        resultOfDomainProfile = domainLib.profile(domain=self.domain)

        if resultOfDomainProfile[0] is True:
            self.domainProfile = resultOfDomainProfile[1]
        else:
            return resultOfDomainProfile

        # Check account limit.
        adminLib = adminlib.Admin()
        numberOfExistAccounts = adminLib.getNumberOfManagedAccounts(accountType='alias', domains=[self.domain])

        if self.domainProfile.aliases == -1:
            return (False, 'NOT_ALLOWED')
        elif self.domainProfile.aliases > 0:
            if self.domainProfile.aliases <= numberOfExistAccounts:
                return (False, 'EXCEEDED_DOMAIN_ACCOUNT_LIMIT')

        # Get display name from <form>
        columns['name'] = data.get('cn', '')

        try:
            # Store new user in required SQL DBs.
            self.conn.insert(
                'dbmail_aliases_extra',
                **columns
            )
            web.logger(msg="Create mail alias: %s." % (self.mail), domain=self.domain, event='create',)
            return (True,)
        except Exception, e:
            return (False, str(e))
Example #8
0
    def POST(self, accountType):
        accountType = web.safestr(accountType)  # user, alias
        i = web.input(_unicode=False, mail=[])

        # Get action.
        action = i.get('action', None)
        if action not in ['enable', 'disable', 'delete', ]:
            raise web.seeother('/search?msg=INVALID_ACTION')

        # Get list of accounts which has valid format.
        accounts = [web.safestr(v).lower() for v in i.get('mail', []) if iredutils.isEmail(web.safestr(v))]

        # Raise earlier to avoid SQL query.
        if not accounts:
            raise web.seeother('/search?msg=INVALID_MAIL')

        domains = set([v.split('@', 1)[-1] for v in accounts])

        # Get managed accounts.
        if not session.get('domainGlobalAdmin'):
            # Get list of managed domains.
            connutils = connUtils.Utils()
            qr = connutils.getManagedDomains(
                admin=session.get('username'),
                domainNameOnly=True,
                listedOnly=True,
            )
            if qr[0] is True:
                domains = [d for d in domains if d in qr[1]]
                accounts = [v for v in accounts if v.split('@', 1)[-1] in domains]
            else:
                raise web.seeother('/search?msg=%s' % str(qr[1]))

        if not accounts:
            raise web.seeother('/search?msg=INVALID_MAIL')

        conn = core.MySQLWrap()
        if action in ['enable', ]:
            qr = conn.setAccountStatus(accounts=accounts, accountType=accountType, active=True)
        elif action in ['disable', ]:
            qr = conn.setAccountStatus(accounts=accounts, accountType=accountType, active=False)
        elif action in ['delete', ]:
            qr = conn.deleteAccounts(accounts=accounts, accountType=accountType)

        if qr[0] is True:
            raise web.seeother('/search?msg=SUCCESS')
        else:
            raise web.seeother('/search?msg=%s' % str(qr[1]))
Example #9
0
    def listAccounts(self, domain, cur_page=1):
        '''List all users.'''
        if not iredutils.isDomain(domain):
            return (False, 'INVALID_DOMAIN_NAME')

        domain = str(domain)
        connutils = connUtils.Utils()
        if not connutils.isDomainExists(domain):
            return (False, 'PERMISSION_DENIED')

        # Pre-defined.
        sql_vars = {
            'domain': domain,
        }
        total = 0

        try:
            resultOfTotal = self.conn.select(
                'dbmail_users',
                vars=sql_vars,
                what='COUNT(userid) AS total',
                where='domain=$domain',
            )
            if len(resultOfTotal) == 1:
                total = resultOfTotal[0].total or 0

            resultOfRecords = self.conn.select(
                'dbmail_users',
                vars=sql_vars,
                # Just query what we need to reduce memory use.
                what='userid,name,curmail_size,maxmail_size,last_login',
                where='domain=$domain',
                order='userid ASC',
                limit=settings.PAGE_SIZE_LIMIT,
                offset=(cur_page - 1) * settings.PAGE_SIZE_LIMIT,
            )

            return (True, total, list(resultOfRecords))
        except Exception, e:
            return (False, str(e))
Example #10
0
                except Exception, e:
                    return (False, str(e))
        elif self.profile_type == 'aliases':
            if session.get('domainGlobalAdmin') is True:
                # Delete old records first.
                try:
                    self.conn.delete(
                        'dbmail_alias_domains',
                        vars=sql_vars,
                        where='target_domain=$domain',
                    )
                except Exception, e:
                    return (False, str(e))

                # Get domain aliases from web form and store in LDAP.
                connutils = connUtils.Utils()
                aliasDomains = [
                    str(v).lower() for v in data.get('domainAliasName', [])
                    if not connutils.isDomainExists(v.lower())
                ]

                if len(aliasDomains) > 0:
                    v = []
                    for ad in aliasDomains:
                        v += [{
                            'alias_domain': ad,
                            'target_domain': self.domain,
                            'created': iredutils.getGMTTime(),
                            'active': 1,
                        }]
                    try:
Example #11
0
    def getNumberOfManagedAccounts(self, admin=None, accountType='domain', domains=[],):
        if admin is None:
            self.admin = session.get('username')
        else:
            self.admin = str(admin)

        if not iredutils.isEmail(self.admin):
            return 0

        self.domains = []
        if accountType in ['user', 'alias', ]:
            if len(domains) > 0:
                self.domains = [str(d).lower() for d in domains if iredutils.isDomain(d)]
            else:
                connutils = connUtils.Utils()
                qr = connutils.getManagedDomains(admin=self.admin, domainNameOnly=True)
                if qr[0] is True:
                    self.domains = qr[1]

        sql_vars = {'admin': self.admin, 'domains': self.domains, }
        if accountType == 'domain':
            try:
                if self.isGlobalAdmin(self.admin):
                    result = self.conn.select('dbmail_domains', what='COUNT(domain) AS total',)
                else:
                    result = self.conn.query(
                        """
                        SELECT COUNT(dbmail_domains.domain) AS total
                        FROM dbmail_domains
                        LEFT JOIN dbmail_domain_admins ON (dbmail_domains.domain=dbmail_domain_admins.domain)
                        WHERE dbmail_domain_admins.username=$admin
                        """,
                        vars=sql_vars,
                    )

                total = result[0].total or 0
                return total
            except:
                pass
        elif accountType == 'user':
            try:
                if self.isGlobalAdmin(self.admin):
                    if len(self.domains) >= 0:
                        result = self.conn.select(
                            'dbmail_users',
                            vars=sql_vars,
                            what='COUNT(user_idnr) AS total',
                            where='domain IN $domains AND user_idnr > 3',
                        )
                    else:
                        result = self.conn.select('dbmail_users', what='COUNT(user_idnr) AS total', where='user_idnr>3')
                else:
                    self.sql_append_where = ''
                    if len(self.domains) > 0:
                        self.sql_append_where = 'AND dbmail_users.domain IN %s' % web.sqlquote(self.domains)

                    result = self.conn.query(
                        """
                        SELECT COUNT(dbmail_users.user_idnr) AS total
                        FROM dbmail_users
                        LEFT JOIN dbmail_domain_admins ON (dbmail_users.domain = dbmail_domain_admins.domain)
                        WHERE dbmail_domain_admins.username=$admin %s
                        """ % (self.sql_append_where, ),
                        vars=sql_vars,
                    )

                total = result[0].total or 0
                return total
            except:
                pass
        elif accountType == 'alias':
            try:
                if self.isGlobalAdmin(self.admin):
                    if len(self.domains) == 0:
                        result = self.conn.select(
                            'dbmail_aliases',
                            what='COUNT(alias_idnr) AS total',
                        )
                    else:
                        result = self.conn.select(
                            'dbmail_aliases',
                            vars=sql_vars,
                            what='COUNT(alias_idnr) AS total',
                            where='domain IN $domains',
                        )
                else:
                    self.sql_append_where = ''
                    if len(self.domains) == 0:
                        self.sql_append_where = 'AND dbmail_aliases.domain IN %s' % web.sqlquote(self.domains)

                    result = self.conn.query(
                        """
                        SELECT COUNT(dbmail_aliases.alias_idnr) AS total
                        FROM dbmail_aliases
                        LEFT JOIN dbmail_domain_admins ON (dbmail_aliases.domain = dbmail_domain_admins.domain)
                        WHERE dbmail_domain_admins.username=$admin %s
                        """ % (self.sql_append_where, ),
                        vars=sql_vars,
                    )

                total = result[0].total or 0
                return total
            except:
                pass

        return 0
Example #12
0
class Dashboard:
    @decorators.require_login
    def GET(self, checknew=None):
        i = web.input(_unicode=False,)

        if checknew is not None:
            self.checknew = True
        else:
            self.checknew = False

        # Get network interface related infomation.
        netif_data = {}
        try:
            import netifaces
            ifaces = netifaces.interfaces()
            for iface in ifaces:
                addr = netifaces.ifaddresses(iface)
                if netifaces.AF_INET in addr.keys():
                    data = addr[netifaces.AF_INET][0]
                    try:
                        netif_data[iface] = {'addr': data['addr'], 'netmask': data['netmask'], }
                    except:
                        pass
        except:
            pass

        # Check new version.
        newVersionInfo = (None, )
        if session.get('domainGlobalAdmin') is True and self.checknew is True:
            try:
                curdate = time.strftime('%Y-%m-%d')
                vars = dict(date=curdate)

                r = web.admindb.select('updatelog', vars=vars, where='date >= $date',)
                if len(r) == 0:
                    urlInfo = {
                        'a': cfg.general.get('webmaster', session.get('username', '')),
                        'v': __version_dbmail_mysql__,
                        'o': __no__,
                        'f': __id__,
                        'host': getfqdn(),
                    }

                    url = __url_latest_dbmail_mysql__ + '?' + urlencode(urlInfo)
                    newVersionInfo = iredutils.getNewVersion(url)

                    # Always remove all old records, just keep the last one.
                    web.admindb.delete('updatelog', vars=vars, where='date < $date',)

                    # Insert updating date.
                    web.admindb.insert('updatelog', date=curdate,)
            except Exception, e:
                newVersionInfo = (False, str(e))

        # Get numbers of domains, users, aliases.
        numberOfDomains = 0
        numberOfUsers = 0
        numberOfAliases = 0

        try:
            adminLib = adminlib.Admin()

            numberOfDomains = adminLib.getNumberOfManagedAccounts(accountType='domain')
            numberOfUsers = adminLib.getNumberOfManagedAccounts(accountType='user')
            numberOfAliases = adminLib.getNumberOfManagedAccounts(accountType='alias')
        except:
            pass

        # Get numbers of existing messages and quota bytes.
        # Set None as default, so that it's easy to detect them in Jinja2 template.
        totalMessages = None
        totalBytes = None
        try:
            tmpConn = core.MySQLWrap()
            totalBytes = tmpConn.getUsedBytesMessages()
        except Exception:
            pass

        # Get records of quarantined mails.
        amavisdQuarantineCount = 0
        amavisdQuarantineRecords = []
        if session.get('enableAmavisdQuarantine') is True:
            quarantineLib = quarantine.Quarantine()

            # Show only 10 records in Dashboard.
            qr = quarantineLib.getRecordsOfQuarantinedMails(sizelimit=10, countOnly=True,)
            if qr[0] is True:
                (amavisdQuarantineCount, amavisdQuarantineRecords) = qr[1]

        # Get number of incoming/outgoing emails in latest 24 hours.
        numberOfIncomingMails = 0
        numberOfOutgoingMails = 0
        numberOfVirusMails = 0
        topSenders = []
        topRecipients = []

        if session.get('enableAmavisdLoggingIntoSQL') is True:
            allReversedDomainNames = []

            amavisdLogLib = amavisdlog.Log()

            # Get all managed domain names and reversed names.
            allDomains = []
            connutils = connUtils.Utils()
            result_all_domains = connutils.getManagedDomains(session.get('username'), domainNameOnly=True)
            if result_all_domains[0] is True:
                allDomains += result_all_domains[1]

            allReversedDomainNames = amavisdLogLib.reverseDomainNames(allDomains)
            numberOfIncomingMails = amavisdLogLib.getNumberOfIncomingMails(allReversedDomainNames, 86400)
            numberOfOutgoingMails = amavisdLogLib.getNumberOfOutgoingMails(allReversedDomainNames, 86400)
            numberOfVirusMails = amavisdLogLib.getNumberOfVirusMails(allReversedDomainNames, 86400)
            topSenders = amavisdLogLib.getTopUser(
                reversedDomainNames=allReversedDomainNames,
                logType='sent',
                timeLength=86400,
                number=10,
            )
            topRecipients = amavisdLogLib.getTopUser(
                reversedDomainNames=allReversedDomainNames,
                logType='received',
                timeLength=86400,
                number=10,
            )

        return web.render(
            'dashboard.html',
            version=__version_dbmail_mysql__,
            hostname=getfqdn(),
            uptime=iredutils.getServerUptime(),
            loadavg=os.getloadavg(),
            netif_data=netif_data,
            newVersionInfo=newVersionInfo,
            amavisdQuarantineCount=amavisdQuarantineCount,
            #amavisdQuarantineRecords=amavisdQuarantineRecords,
            numberOfDomains=numberOfDomains,
            numberOfUsers=numberOfUsers,
            numberOfAliases=numberOfAliases,
            totalMessages=totalMessages,
            totalBytes=totalBytes,
            numberOfIncomingMails=numberOfIncomingMails,
            numberOfOutgoingMails=numberOfOutgoingMails,
            numberOfVirusMails=numberOfVirusMails,
            topSenders=topSenders,
            topRecipients=topRecipients,
            removeQuarantinedInDays=settings.AMAVISD_REMOVE_QUARANTINED_IN_DAYS,
        )
Example #13
0
    def add(self, domain, data):
        # Get domain name, username, cn.
        self.domain = web.safestr(data.get('domainName')).strip().lower()
        self.username = web.safestr(data.get('username')).strip().lower()
        self.mail = self.username + '@' + self.domain
        sql_vars = {
            'mail': self.mail,
        }

        if not iredutils.isDomain(self.domain):
            return (False, 'INVALID_DOMAIN_NAME')

        if self.domain != domain:
            return (False, 'PERMISSION_DENIED')

        if not iredutils.isEmail(self.mail):
            return (False, 'INVALID_MAIL')

        # Check account existing.
        connutils = connUtils.Utils()
        if connutils.isEmailExists(self.mail):
            return (False, 'ALREADY_EXISTS')

        # Get domain profile.
        domainLib = domainlib.Domain()
        resultOfDomainProfile = domainLib.profile(domain=self.domain)

        if resultOfDomainProfile[0] is True:
            self.domainProfile = resultOfDomainProfile[1]
        else:
            return resultOfDomainProfile

        # Check account limit.
        adminLib = adminlib.Admin()
        numberOfExistAccounts = adminLib.getNumberOfManagedAccounts(
            accountType='user', domains=[self.domain])

        if self.domainProfile.mailboxes == -1:
            return (False, 'NOT_ALLOWED')
        elif self.domainProfile.mailboxes > 0:
            if self.domainProfile.mailboxes <= numberOfExistAccounts:
                return (False, 'EXCEEDED_DOMAIN_ACCOUNT_LIMIT')

        columns = {
            'userid': self.mail,
            'domain': self.domain,
        }

        # Check spare quota and number of spare account limit.
        # Get quota from form.
        self.mailQuota = str(data.get('mailQuota')).strip()
        self.defaultUserQuota = self.domainProfile.get('defaultuserquota', 0)

        if self.mailQuota.isdigit():
            self.mailQuota = int(self.mailQuota)
        else:
            self.mailQuota = self.defaultUserQuota

        # Re-calculate mail quota if this domain has max quota limit.
        if self.domainProfile.maxquota > 0:
            # Get used quota.
            qr = domainLib.getAllocatedQuotaSize(domain=self.domain)
            if qr[0] is True:
                self.allocatedQuota = qr[1]
            else:
                return qr

            spareQuota = self.domainProfile.maxquota - self.allocatedQuota / 1024 / 1024

            if spareQuota > 0:
                if spareQuota < self.mailQuota:
                    self.mailQuota = spareQuota
            else:
                # No enough quota.
                return (False, 'EXCEEDED_DOMAIN_QUOTA_SIZE')

        columns['maxmail_size'] = self.mailQuota * 1024 * 1024

        #
        # Get password from <form>.
        #
        newpw = web.safestr(data.get('newpw', ''))
        confirmpw = web.safestr(data.get('confirmpw', ''))

        # Get password length limit from domain profile or global setting.
        self.minPasswordLength = self.domainProfile.get(
            'minpasswordlength', cfg.general.get('min_passwd_length', '0'))
        self.maxPasswordLength = self.domainProfile.get(
            'maxpasswordlength', cfg.general.get('max_passwd_length', '0'))

        resultOfPW = iredutils.verifyNewPasswords(
            newpw,
            confirmpw,
            min_passwd_length=self.minPasswordLength,
            max_passwd_length=self.maxPasswordLength,
        )
        if resultOfPW[0] is True:
            if 'storePasswordInPlainText' in data:
                columns['passwd'] = iredutils.getSQLPassword(resultOfPW[1],
                                                             pwscheme='PLAIN')
                columns['encryption_type'] = ''
            else:
                columns['passwd'] = iredutils.getSQLPassword(resultOfPW[1])
                columns[
                    'encryption_type'] = settings.SQL_DEFAULT_PASSWD_SCHEME.lower(
                    )

        else:
            return resultOfPW

        # Get display name from <form>
        columns['name'] = data.get('cn', '')

        # Assign new user to default mail aliases.
        assignedAliases = [
            str(addr).lower()
            for addr in str(self.domainProfile.defaultuseraliases).split(',')
            if iredutils.isEmail(addr)
        ]

        try:
            # Store new user in SQL db.
            self.conn.insert('dbmail_users', **columns)

            # Get dbmail_users.user_idnr.
            qr = self.conn.select(
                'dbmail_users',
                vars=sql_vars,
                what='user_idnr,client_idnr',
                where='userid=$mail',
                limit=1,
            )
            p = qr[0]
            user_idnr, client_idnr = p.user_idnr, p.client_idnr

            self.conn.insert(
                'dbmail_aliases',
                alias=self.mail,
                deliver_to=user_idnr,
                client_idnr=client_idnr,
            )

            # Create and subscribe to default IMAP folders.
            if settings.DBMAIL_CREATE_DEFAULT_IMAP_FOLDERS:
                # Create default IMAP folders.
                imap_folders = [
                    '(%d, "%s")' % (user_idnr, fld)
                    for fld in settings.DBMAIL_DEFAULT_IMAP_FOLDERS
                ]
                self.conn.query(
                    '''INSERT INTO dbmail_mailboxes (owner_idnr, name) VALUES %s'''
                    % ','.join(imap_folders))

                # Subscribe to folders by default.
                self.conn.query(
                    '''INSERT INTO dbmail_subscription (user_id, mailbox_id)
                                SELECT owner_idnr, mailbox_idnr FROM dbmail_mailboxes WHERE owner_idnr = %d
                                ''' % user_idnr)

            # Assign new user to default mail aliases.
            if len(assignedAliases) > 0:
                for ali in assignedAliases:
                    try:
                        self.conn.update(
                            'dbmail_aliases',
                            vars={
                                'mail': self.mail,
                                'ali': ali,
                                'user_idnr': user_idnr,
                            },
                            where='alias = $ali AND deliver_to <> $user_idnr',
                            deliver_to=web.sqlliteral(
                                'CONCAT($mail, ",", deliver_to)'),
                        )
                    except:
                        pass

            vars_addition_sql = {
                'user_idnr': user_idnr,
                'mail': self.mail,
                'username': self.username,
                'domain': self.domain,
            }
            # Execute addition SQL commands after successfully created new users.
            if settings.DBMAIL_SQL_FOR_NEWLY_CREATED_USER:
                try:
                    for sql_cmd in settings.DBMAIL_SQL_FOR_NEWLY_CREATED_USER:
                        self.conn.query(sql_cmd, vars=vars_addition_sql)
                except Exception:
                    pass

            # Create Amavisd policy for newly created user.
            if settings.AMAVISD_EXECUTE_SQL_WITHOUT_ENABLED and settings.AMAVISD_SQL_FOR_NEWLY_CREATED_USER:
                try:
                    from libs.amavisd.core import AmavisdWrap
                    amwrap = AmavisdWrap()
                    for sql_cmd in settings.AMAVISD_SQL_FOR_NEWLY_CREATED_USER:
                        amwrap.db.query(sql_cmd, vars=vars_addition_sql)
                except:
                    pass

            web.logger(
                msg="Create user: %s." % (self.mail),
                domain=self.domain,
                event='create',
            )
            return (True, )
        except Exception, e:
            return (False, str(e))