Commits

Zhang Huangbin  committed 552ea86

Convert config file from ini format (settings.ini) to python source file (settings.py).

  • Participants
  • Parent commits cd62e9f

Comments (0)

Files changed (46)

File controllers/ldap/admin.py

 # Author: Zhang Huangbin <zhb@iredmail.org>
 
 import web
-from libs import languages, settings
+import settings
+from libs import languages
 from libs.ldaplib import decorators, admin, domain as domainlib, connUtils
 
-cfg = web.iredconfig
 session = web.config.get('_session')
 
 #
     def GET(self):
         i = web.input()
         return web.render('ldap/admin/create.html',
-                          languagemaps=languages.getLanguageMaps(),
-                          default_language=cfg.general.get('lang', 'en_US'),
-                          min_passwd_length=cfg.general.get('min_passwd_length'),
-                          max_passwd_length=cfg.general.get('max_passwd_length'),
+                          languagemaps=languages.get_language_maps(),
+                          default_language=settings.default_language,
+                          min_passwd_length=settings.min_passwd_length,
+                          max_passwd_length=settings.max_passwd_length,
                           msg=i.get('msg'),
                          )
 
                     mail=self.mail,
                     profile_type=self.profile_type,
                     profile=self.admin_profile,
-                    languagemaps=languages.getLanguageMaps(),
+                    languagemaps=languages.get_language_maps(),
                     allDomains=self.allDomains,
                     msg=i.get('msg', None),
                 )
                               mail=self.mail,
                               profile_type=self.profile_type,
                               profile=self.admin_profile,
-                              min_passwd_length=cfg.general.get('min_passwd_length'),
-                              max_passwd_length=cfg.general.get('max_passwd_length'),
+                              min_passwd_length=settings.min_passwd_length,
+                              max_passwd_length=settings.max_passwd_length,
                               msg=i.get('msg', None),
                              )
 

File controllers/ldap/basic.py

 import web
 from socket import getfqdn
 from urllib import urlencode
+import settings
 from libs import __url_latest_ose__, __version_ose__, __no__, __id__
 from libs import iredutils, languages
 from libs.ldaplib import auth, decorators, admin as adminlib, ldaputils
 
 
-cfg = web.iredconfig
 session = web.config.get('_session')
 
 
 
             # Show login page.
             return web.render('login.html',
-                              languagemaps=languages.getLanguageMaps(),
+                              languagemaps=languages.get_language_maps(),
                               webmaster=session.get('webmaster'),
                               msg=i.get('msg'),
                              )
             raise web.seeother('/login?msg=EMPTY_PASSWORD')
 
         # Get LDAP URI.
-        uri = cfg.ldap.get('uri')
+        uri = settings.ldap_uri
 
         # Verify bind_dn & bind_pw.
         try:
                 conn.set_option(ldap.OPT_X_TLS, ldap.OPT_X_TLS_DEMAND)
 
             # synchronous bind.
-            conn.bind_s(cfg.ldap.get('bind_dn'), cfg.ldap.get('bind_pw'))
+            conn.bind_s(settings.ldap_bind_dn, settings.ldap_bind_password)
             conn.unbind_s()
         except (ldap.INVALID_CREDENTIALS):
             raise web.seeother('/login?msg=vmailadmin_INVALID_CREDENTIALS')
                 adminProfile = adminLib.profile(username, attributes=['preferredLanguage'])
                 if adminProfile[0] is True:
                     dn, entry = adminProfile[1][0]
-                    lang = entry.get('preferredLanguage', [cfg.general.get('lang', 'en_US')])[0]
+                    lang = entry.get('preferredLanguage', [settings.default_language])[0]
                     session['lang'] = lang
 
             if qr_user_auth is True:
             web.logger(msg="Login success", event='login',)
             raise web.seeother('/dashboard/checknew')
         else:
-            session['failedTimes'] += 1
+            session['failed_times'] += 1
             web.logger(msg="Login failed.", admin=username, event='login', loglevel='error',)
             raise web.seeother('/login?msg=%s' % qr_admin_auth)
 
                         'v': __version_ose__,
                         'o': __no__,
                         'f': __id__,
-                        'lang': cfg.general.get('lang', ''),
+                        'lang': settings.default_language,
                         'host': getfqdn(),
-                        'backend': cfg.general.get('backend', ''),
+                        'backend': settings.backend,
                     }
 
                     url = __url_latest_ose__ + '?' + urlencode(urlInfo)
             'dashboard.html',
             version=__version_ose__,
             hostname=getfqdn(),
-            uptime=iredutils.getServerUptime(),
+            uptime=iredutils.get_server_uptime(),
             loadavg=os.getloadavg(),
             netif_data=netif_data,
             newVersionInfo=newVersionInfo,

File controllers/ldap/domain.py

 # Author: Zhang Huangbin <zhb@iredmail.org>
 
 import web
-from libs import iredutils, settings
-from libs.ldaplib import decorators, admin, domain as domainlib, connUtils, ldaputils
+import settings
+from libs import iredutils
+from libs.ldaplib import decorators, domain as domainlib, connUtils, ldaputils
 
-cfg = web.iredconfig
 session = web.config.get('_session')
 
 

File controllers/ldap/user.py

 # Author: Zhang Huangbin <zhb@iredmail.org>
 
 import web
-from libs import iredutils, settings
-from libs.languages import getLanguageMaps
+import settings
+from libs import iredutils
+from libs.languages import get_language_maps
 from libs.ldaplib import decorators, domain as domainlib, user, ldaputils, connUtils
 
-cfg = web.iredconfig
 session = web.config.get('_session')
 
 
             if cur_page > sl.get('totalPages'):
                 cur_page = sl.get('totalPages')
 
-            # Show login date.
-            if cfg.general.get('show_login_date', 'False').lower() in ['true', ]:
-                showLoginDate = True
-            else:
-                showLoginDate = False
-
             return web.render(
                 'ldap/user/list.html',
                 cur_page=cur_page,
                 users=accountList,
                 cur_domain=domain,
                 allDomains=allDomains,
-                showLoginDate=showLoginDate,
                 accountUsedQuota={},
                 msg=i.get('msg'),
             )
             profile_type=self.profile_type,
             mail=self.mail,
             user_profile=result[1],
-            defaultStorageBaseDirectory=cfg.general.get('storage_base_directory'),
+            defaultStorageBaseDirectory=settings.storage_base_directory,
             minPasswordLength=minPasswordLength,
             maxPasswordLength=maxPasswordLength,
             domainAccountSetting=domainAccountSetting,
-            languagemaps=getLanguageMaps(),
+            languagemaps=get_language_maps(),
             msg=i.get('msg', None),
         )
 

File controllers/mysql/admin.py

 # Author: Zhang Huangbin <zhb@iredmail.org>
 
 import web
+import settings
 from libs import languages, iredutils
 from libs.mysql import decorators, admin as adminlib, domain as domainlib
 
-cfg = web.iredconfig
 session = web.config.get('_session')
 
 
                 profile_type=self.profile_type,
                 domainGlobalAdmin=domainGlobalAdmin,
                 profile=profile,
-                languagemaps=languages.getLanguageMaps(),
+                languagemaps=languages.get_language_maps(),
                 allDomains=self.allDomains,
-                min_passwd_length=cfg.general.get('min_passwd_length', '0'),
-                max_passwd_length=cfg.general.get('max_passwd_length', '0'),
+                min_passwd_length=settings.min_passwd_length,
+                max_passwd_length=settings.max_passwd_length,
                 msg=i.get('msg'),
             )
         else:
         i = web.input()
         return web.render(
             'mysql/admin/create.html',
-            languagemaps=languages.getLanguageMaps(),
-            default_language=cfg.general.get('lang', 'en_US'),
-            min_passwd_length=cfg.general.get('min_passwd_length'),
-            max_passwd_length=cfg.general.get('max_passwd_length'),
+            languagemaps=languages.get_language_maps(),
+            default_language=settings.default_language,
+            min_passwd_length=settings.min_passwd_length,
+            max_passwd_length=settings.max_passwd_length,
             msg=i.get('msg'),
         )
 

File controllers/mysql/basic.py

 from socket import getfqdn
 from urllib import urlencode
 import web
+import settings
 from libs import __url_latest_ose__, __version_ose__, __no__, __id__
 from libs import iredutils, languages
 from libs.mysql import core, decorators
 
 
-cfg = web.iredconfig
 session = web.config.get('_session')
 
 
             # Show login page.
             return web.render(
                 'login.html',
-                languagemaps=languages.getLanguageMaps(),
+                languagemaps=languages.get_language_maps(),
                 msg=i.get('msg'),
             )
         else:
             web.logger(msg="Login success", event='login',)
             raise web.seeother('/dashboard/checknew')
         else:
-            session['failedTimes'] += 1
+            session['failed_times'] += 1
             web.logger(msg="Login failed.", admin=username, event='login', loglevel='error',)
             raise web.seeother('/login?msg=%s' % web.urlquote(auth_result[1]))
 
                         'v': __version_ose__,
                         'o': __no__,
                         'f': __id__,
-                        'lang': cfg.general.get('lang', ''),
+                        'lang': settings.default_language,
                         'host': getfqdn(),
-                        'backend': cfg.general.get('backend', ''),
+                        'backend': settings.backend,
                     }
 
                     url = __url_latest_ose__ + '?' + urlencode(urlInfo)
             'dashboard.html',
             version=__version_ose__,
             hostname=getfqdn(),
-            uptime=iredutils.getServerUptime(),
+            uptime=iredutils.get_server_uptime(),
             loadavg=os.getloadavg(),
             netif_data=netif_data,
             newVersionInfo=newVersionInfo,

File controllers/mysql/domain.py

 
 import web
 from libs import iredutils
-from libs.mysql import decorators, domain as domainlib, admin as adminlib
+from libs.mysql import decorators, domain as domainlib
 
-cfg = web.iredconfig
 session = web.config.get('_session')
 
 

File controllers/mysql/user.py

 
 import web
 from libs import iredutils
-from libs.languages import getLanguageMaps
+from libs.languages import get_language_maps
 from libs.mysql import decorators, user as userlib, domain as domainlib, connUtils
 
-cfg = web.iredconfig
 session = web.config.get('_session')
 
 
             mail=self.mail,
             profile_type=self.profile_type,
             profile=self.profile,
-            languagemaps=getLanguageMaps(),
+            languagemaps=get_language_maps(),
             msg=i.get('msg'),
         )
 

File controllers/panel/log.py

 from controllers import decorators
 from libs.panel import LOG_EVENTS, log as loglib
 
-cfg = web.iredconfig
 session = web.config.get('_session')
 
-if cfg.general.backend == 'ldap':
-    from libs.ldaplib import admin as adminlib, connUtils
-elif cfg.general.backend == 'mysql':
-    from libs.mysql import admin as adminlib, connUtils
-elif cfg.general.backend == 'pgsql':
-    from libs.pgsql import admin as adminlib, connUtils
-elif cfg.general.backend == 'dbmail_mysql':
-    from libs.dbmail_mysql import admin as adminlib, connUtils
-
 
 class Log:
     @decorators.require_login

File controllers/pgsql/admin.py

 # Author: Zhang Huangbin <zhb@iredmail.org>
 
 import web
+import settings
 from libs import languages, iredutils
 from libs.pgsql import decorators, admin as adminlib, domain as domainlib
 
-cfg = web.iredconfig
 session = web.config.get('_session')
 
 
                 profile_type=self.profile_type,
                 domainGlobalAdmin=domainGlobalAdmin,
                 profile=profile,
-                languagemaps=languages.getLanguageMaps(),
+                languagemaps=languages.get_language_maps(),
                 allDomains=self.allDomains,
-                min_passwd_length=cfg.general.get('min_passwd_length', '0'),
-                max_passwd_length=cfg.general.get('max_passwd_length', '0'),
+                min_passwd_length=settings.min_passwd_length,
+                max_passwd_length=settings.max_passwd_length,
                 msg=i.get('msg'),
             )
         else:
         i = web.input()
         return web.render(
             'pgsql/admin/create.html',
-            languagemaps=languages.getLanguageMaps(),
-            default_language=cfg.general.get('lang', 'en_US'),
-            min_passwd_length=cfg.general.get('min_passwd_length'),
-            max_passwd_length=cfg.general.get('max_passwd_length'),
+            languagemaps=languages.get_language_maps(),
+            default_language=settings.default_language,
+            min_passwd_length=settings.min_passwd_length,
+            max_passwd_length=settings.max_passwd_length,
             msg=i.get('msg'),
         )
 

File controllers/pgsql/basic.py

 from socket import getfqdn
 from urllib import urlencode
 import web
+import settings
 from libs import __url_latest_ose__, __version_ose__, __no__, __id__
 from libs import iredutils, languages
 from libs.pgsql import core, decorators
 
 
-cfg = web.iredconfig
 session = web.config.get('_session')
 
 
             # Show login page.
             return web.render(
                 'login.html',
-                languagemaps=languages.getLanguageMaps(),
+                languagemaps=languages.get_language_maps(),
                 msg=i.get('msg'),
             )
         else:
             web.logger(msg="Login success", event='login',)
             raise web.seeother('/dashboard/checknew')
         else:
-            session['failedTimes'] += 1
+            session['failed_times'] += 1
             web.logger(msg="Login failed.", admin=username, event='login', loglevel='error',)
             raise web.seeother('/login?msg=%s' % web.urlquote(auth_result[1]))
 
                         'v': __version_ose__,
                         'o': __no__,
                         'f': __id__,
-                        'lang': cfg.general.get('lang', ''),
+                        'lang': settings.default_language,
                         'host': getfqdn(),
-                        'backend': cfg.general.get('backend', ''),
+                        'backend': settings.backend,
                     }
 
                     url = __url_latest_ose__ + '?' + urlencode(urlInfo)
             'dashboard.html',
             version=__version_ose__,
             hostname=getfqdn(),
-            uptime=iredutils.getServerUptime(),
+            uptime=iredutils.get_server_uptime(),
             loadavg=os.getloadavg(),
             netif_data=netif_data,
             newVersionInfo=newVersionInfo,

File controllers/pgsql/domain.py

 
 import web
 from libs import iredutils
-from libs.pgsql import decorators, domain as domainlib, admin as adminlib
+from libs.pgsql import decorators, domain as domainlib
 
-cfg = web.iredconfig
 session = web.config.get('_session')
 
 

File controllers/pgsql/user.py

 
 import web
 from libs import iredutils
-from libs.languages import getLanguageMaps
+from libs.languages import get_language_maps
 from libs.pgsql import decorators, user as userlib, domain as domainlib, connUtils
 
-cfg = web.iredconfig
 session = web.config.get('_session')
 
 
             mail=self.mail,
             profile_type=self.profile_type,
             profile=self.profile,
-            languagemaps=getLanguageMaps(),
+            languagemaps=get_language_maps(),
             msg=i.get('msg'),
         )
 

File libs/iredbase.py

 
 import os
 import sys
-from ConfigParser import SafeConfigParser
+import gettext
 
 import web
 from jinja2 import Environment, FileSystemLoader
 os.environ['PYTHON_EGG_CACHE'] = '/tmp/.iredadmin-eggs'
 os.environ['LC_ALL'] = 'C'
 
-# init settings.ini to a web.storage
-rootdir = os.path.abspath(os.path.dirname(__file__)) + '/../'
-iniSettings = SafeConfigParser()
-cfgfile = os.path.join(rootdir, 'settings.ini')
-if os.path.exists(cfgfile):
-    iniSettings.read(cfgfile)
-else:
-    sys.exit('Error: No config file found: %s.' % cfgfile)
-
-iniSections = web.storage(iniSettings._sections)
-cfg = web.iredconfig = web.storage()
-for k in iniSections:
-    web.iredconfig[k] = web.storage(iniSections[k])
-
-web.iredconfig['rootdir'] = rootdir
-
-webmaster = cfg.general.get('webmaster', 'root')
-backend = cfg.general.get('backend', 'ldap')
-
-# Set debug mode.
-if cfg.general.get('debug', 'False').lower() in ['true', ]:
-    web.config.debug = True
-else:
-    web.config.debug = False
-
-# Initialize object which used to stored all translations.
-cfg.allTranslations = web.storage()
-
-# Get global language setting.
-lang = cfg.general.get('lang', 'en_US')
-
 import iredutils
 import settings
 from ireddate import convert_utc_to_timezone
 
+# Set debug mode.
+web.config.debug = settings.DEBUG
+
+# Check Policyd/Cluebringer
+enable_policyd = settings.policyd_enabled
+enable_cluebringer = settings.policyd_enabled
+if settings.policyd_db_name in ['cluebringer']:
+    enable_policyd = False
+
 # Set session parameters.
 web.config.session_parameters['cookie_name'] = 'iRedAdmin'
 web.config.session_parameters['cookie_domain'] = None
 
 # Initialize session object.
 session_dbn = 'mysql'
-if backend in ['pgsql', ]:
+if settings.backend in ['pgsql', ]:
     session_dbn = 'postgres'
 
 db_iredadmin = web.database(
-    host=cfg.iredadmin.get('host', 'localhost'),
-    port=int(cfg.iredadmin.get('port', '3306')),
+    host=settings.iredadmin_db_host,
+    port=int(settings.iredadmin_db_port),
     dbn=session_dbn,
-    db=cfg.iredadmin.get('db', 'iredadmin'),
-    user=cfg.iredadmin.get('user', 'iredadmin'),
-    pw=cfg.iredadmin.get('passwd'),
+    db=settings.iredadmin_db_name,
+    user=settings.iredadmin_db_user,
+    pw=settings.iredadmin_db_password,
 )
+db_iredadmin.supports_multiple_insert = True
 
 # Store session data in 'iredadmin.sessions'.
 sessionStore = web.session.DBStore(db_iredadmin, 'sessions')
 
 # URL handlers.
 # Import backend related urls.
-if backend == 'ldap':
+if settings.backend == 'ldap':
     from controllers.ldap.urls import urls as backendUrls
-elif backend == 'mysql':
+elif settings.backend == 'mysql':
     from controllers.mysql.urls import urls as backendUrls
-elif backend == 'pgsql':
+elif settings.backend == 'pgsql':
     from controllers.pgsql.urls import urls as backendUrls
-elif backend == 'dbmail_mysql':
-    from controllers.dbmail_mysql.urls import urls as backendUrls
 else:
     backendUrls = []
 
 urls = backendUrls
 
+# Import Policyd/Cluebringer related urls.
+if enable_policyd:
+    from controllers.policyd.urls import urls as policydUrls
+    urls += policydUrls
+
+if enable_cluebringer:
+    from controllers.cluebringer.urls import urls as policydUrls
+    urls += policydUrls
+
+# Import amavisd related urls.
+if settings.amavisd_enable_quarantine or settings.amavisd_enable_logging:
+    from controllers.amavisd.urls import urls as amavisdUrls
+    urls += amavisdUrls
+
 from controllers.panel.urls import urls as panelUrls
 urls += panelUrls
 
     app,
     sessionStore,
     initializer={
-        'webmaster': webmaster,
+        'webmaster': settings.webmaster,
         'username': None,
         'logged': False,
-        'failedTimes': 0,   # Integer.
-        'lang': lang,
+        'failed_times': 0,   # Integer.
+        'lang': settings.default_language,
+        'is_global_admin': False,
+        'default_mta_transport': settings.default_mta_transport,
 
         # Store password in plain text.
-        'storePasswordInPlain': settings.STORE_PASSWORD_IN_PLAIN,
+        'store_password_in_plain_text': settings.STORE_PASSWORD_IN_PLAIN_TEXT,
 
-        # Show used quota.
-        'enableShowUsedQuota': False,
-
-        # Enable Policyd & Amavisd integration.
-        'enablePolicyd': False,
+        # Policyd/Cluebringer integration.
+        'enable_policyd': enable_policyd,
+        'enable_cluebringer': enable_cluebringer,
 
         # Amavisd related features.
-        'enableAmavisdQuarantine': False,
-        'enableAmavisdLoggingIntoSQL': False,
+        'amavisd_enable_quarantine': settings.amavisd_enable_quarantine,
     }
 )
 
 # Generate CSRF token and store it in session.
 def csrf_token():
     if not 'csrf_token' in session.keys():
-        session['csrf_token'] = iredutils.getRandomPassword(32)
+        session['csrf_token'] = iredutils.generate_random_strings(32)
 
     return session['csrf_token']
 
 
-# Hooks.
-def hook_lang():
-    web.ctx.lang = web.input(lang=None, _method="GET").lang or session.get('lang', 'en_US')
+# Initialize object which used to stored all translations.
+all_translations = {'en_US': gettext.NullTranslations()}
+
+# Translations
+def ired_gettext(string):
+    """Translate a given string to the language of the application."""
+    lang = session.lang
+
+    if lang in all_translations:
+        translation = all_translations[lang]
+    else:
+        try:
+            # Store new translation
+            translation = gettext.translation(
+                'iredadmin',
+                os.path.abspath(os.path.dirname(__file__)) + '/../i18n',
+                languages=[lang])
+            all_translations[lang] = translation
+        except:
+            translation = all_translations['en_US']
+
+    return translation.ugettext(string)
 
 
 # Define template render.
 def render_template(template_name, **context):
     jinja_env = Environment(
-        loader=FileSystemLoader(os.path.join(os.path.dirname(__file__), '../templates/default', )),
+        loader=FileSystemLoader(os.path.join(os.path.dirname(__file__),
+                                             '../templates/default', )),
         extensions=[],
     )
     jinja_env.globals.update({
-        '_': iredutils.iredGettext,    # Override _() which provided by Jinja2.
-        'ctx': web.ctx,                 # Used to get 'homepath'.
-        'skin': 'default',              # Used for static files.
+        '_': ired_gettext,  # Override _() which provided by Jinja2.
+        'ctx': web.ctx,     # Used to get 'homepath'.
+        'skin': 'default',  # Used for static files.
         'session': web.config._session,
-        'backend': backend,
+        'backend': settings.backend,
         'csrf_token': csrf_token,
         'pageSizeLimit': settings.PAGE_SIZE_LIMIT,
         'policyPriorityOfUser': settings.POLICY_PRIORITY_OF_USER,
 
     jinja_env.filters.update({
         'filesizeformat': iredutils.filesizeformat,
-        'setDatetimeFormat': iredutils.setDatetimeFormat,
-        'getRandomPassword': iredutils.getRandomPassword,
-        'getPercentage': iredutils.getPercentage,
-        'cutString': iredutils.cutString,
+        'set_datetime_format': iredutils.set_datetime_format,
+        'generate_random_strings': iredutils.generate_random_strings,
+        'convert_to_percentage': iredutils.convert_to_percentage,
+        'cut_string': iredutils.cut_string,
         'convert_utc_to_timezone': convert_utc_to_timezone,
     })
 
 
 
 # Logger. Logging into SQL database.
-def log_into_sql(msg, admin='', domain='', username='', event='', loglevel='info',):
+def log_into_sql(msg,
+                 admin='',
+                 domain='',
+                 username='',
+                 event='',
+                 loglevel='info'):
     try:
-        if admin == '':
-            admin = session.get('username', '')
+        if not admin:
+            admin = session.get('username')
 
         db_iredadmin.insert(
             'log',
             event=str(event),
             msg=str(msg),
             ip=str(session.ip),
-            timestamp=iredutils.getGMTTime(),
+            timestamp=iredutils.get_gmttime(),
         )
     except Exception:
         pass
 
+    return None
+
 
 # Log error message. default log to sys.stderr.
 def log_error(*args):
         except Exception, e:
             print >> sys.stderr, e
 
-app.add_processor(web.loadhook(hook_lang))
 
 # Mail 500 error to webmaster.
-if cfg.general.get('mail_error_to_webmaster', 'False').lower() == 'true':
-    app.internalerror = web.emailerrors(webmaster, web.webapi._InternalError,)
+if settings.MAIL_ERROR_TO_WEBMASTER:
+    app.internalerror = web.emailerrors(settings.webmaster, web.webapi._InternalError)
 
 # Store objects in 'web' module.
 web.app = app

File libs/iredutils.py

 # Author: Zhang Huangbin <zhb@iredmail.org>
 
 from os import urandom
-import gettext
 import re
-import datetime
 import time
 import urllib2
 import socket
 from xml.dom.minidom import parseString as parseXMLString
 import random
 import web
-from libs import md5crypt, settings
-
-cfg = web.iredconfig
+import settings
+from libs import md5crypt
 
 ######################
 # Regular expressions.
     return ret
 
 
-def setDatetimeFormat(t, hour=True,):
+def set_datetime_format(t, hour=True,):
     """Format LDAP timestamp and Amavisd msgs.time_iso to YYYY-MM-DD HH:MM:SS.
 
-    >>> setDatetimeFormat('20100925T113256Z')
+    >>> set_datetime_format('20100925T113256Z')
     '2010-09-25 11:32:56'
 
-    >>> setDatetimeFormat('20100925T113256Z', hour=False)
+    >>> set_datetime_format('20100925T113256Z', hour=False)
     '2010-09-25'
 
-    >>> setDatetimeFormat('INVALID_TIME_STAMP')      # Return original string
+    >>> set_datetime_format('INVALID_TIME_STAMP')      # Return original string
     'INVALID_TIME_STAMP'
     """
     if t is None:
     return t
 
 
-def cutString(s, length=40):
+def cut_string(s, length=40):
     try:
         if len(s) != len(s.encode('utf-8', 'replace')):
             length = length / 2
 # End Jinja2 filters.
 ########################
 
-
-def getTranslations(lang='en_US'):
-    # Init translation.
-    if lang in cfg.allTranslations.keys():
-        translation = cfg.allTranslations[lang]
-    elif lang is None:
-        translation = gettext.NullTranslations()
-    else:
-        try:
-            translation = gettext.translation(
-                    'iredadmin',
-                    cfg['rootdir'] + 'i18n',
-                    languages=[lang],
-                    )
-        except IOError:
-            translation = gettext.NullTranslations()
-    return translation
-
-
-def loadTranslations(lang):
-    """Return the translations for the locale."""
-    lang = str(lang)
-    translation = cfg.allTranslations.get(lang)
-    if translation is None:
-        translation = getTranslations(lang)
-        cfg.allTranslations[lang] = translation
-
-        # Delete other translations.
-        for lk in cfg.allTranslations.keys():
-            if lk != lang:
-                del cfg.allTranslations[lk]
-    return translation
-
-
-def iredGettext(string):
-    """Translate a given string to the language of the application."""
-    lang = web.ctx.lang
-    translation = loadTranslations(lang)
-    if translation is None:
-        return unicode(string)
-    return translation.ugettext(string)
-
-
-def getServerUptime():
+def get_server_uptime():
     try:
         # Works on Linux.
         f = open("/proc/uptime")
     return (days, hours, minutes)
 
 
-def getGMTTime():
+def get_gmttime():
     # Convert local time to UTC
     return time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime())
 
     return rcds
 
 
-def verifyNewPasswords(newpw, confirmpw, \
-                   min_passwd_length=cfg.general.get('min_passwd_length', 0), \
-                   max_passwd_length=cfg.general.get('max_passwd_length', 0), \
-                  ):
+def verify_new_password(newpw, confirmpw,
+                       min_passwd_length=settings.min_passwd_length,
+                       max_passwd_length=settings.max_passwd_length):
     # Get new passwords from user input.
     newpw = str(newpw).strip()
     confirmpw = str(confirmpw).strip()
     return (True, passwd)
 
 
-def getRandomPassword(length=10):
+def generate_random_strings(length=10):
     """Create a random password of specified length"""
     try:
         length = int(length) or 10
 
 def generate_md5_password(p):
     p = str(p).strip()
-    return md5crypt.unix_md5_crypt(p, getRandomPassword(length=8))
+    return md5crypt.unix_md5_crypt(p, generate_random_strings(length=8))
 
 
 def verify_md5_password(challenge_password, plain_password):
     elif pwscheme == 'PLAIN-MD5':
         pw = generate_plain_md5_password(p)
     elif pwscheme == 'PLAIN':
-        backend = cfg.general.get('backend', 'mysql')
-        if backend in ['mysql', 'pgsql']:
-            if settings.SQL_PASSWD_PREFIX_SCHEME is True:
-                pw = '{PLAIN}' + p
-            else:
-                pw = p
-        elif backend == 'dbmail_mysql':
+        if settings.SQL_PASSWD_PREFIX_SCHEME is True:
+            pw = '{PLAIN}' + p
+        else:
             pw = p
     elif pwscheme == 'SSHA':
         pw = generate_ssha_password(p)
     return pw
 
 
-def setMailMessageStore(mail,
+def generate_maildir_path(mail,
                         hashedMaildir=settings.MAILDIR_HASHED,
                         prependDomainName=settings.MAILDIR_PREPEND_DOMAIN,
                         appendTimestamp=settings.MAILDIR_APPEND_TIMESTAMP,
     return mailMessageStore.lower()
 
 
-# Return value of percentage.
-def getPercentage(current, total):
-    try:
-        current = int(current)
-        total = int(total)
-    except:
-        return 0
-
-    if current == 0 or total == 0:
-        return 0
-    else:
-        percent = (current * 100) // total
-        if percent < 0:
-            return 0
-        elif percent > 100:
-            return 100
-        else:
-            return percent
-
-
 def getNewVersion(urlOfXML):
     '''Checking new version via parsing XML string to extract version number.
 
     except Exception, e:
         return (False, str(e))
 
-
-def convShadowLastChangeToDate(day):
-    if not isinstance(day, int):
-        return '0'
-
-    return (datetime.date(1970, 1, 1) + datetime.timedelta(day)).isoformat()

File libs/languages.py

 import glob
 import web
 
-cfg = web.iredconfig
-
 langmaps = {
     'en_US': u'English (US)',
     'sq_AL': u'Albanian',
 
 
 # Get available languages.
-def getLanguageMaps():
+def get_language_maps():
     # Get available languages.
-    available_langs = [web.safestr(os.path.basename(v))
-                       for v in glob.glob(cfg.get('rootdir') + 'i18n/[a-z][a-z]_[A-Z][A-Z]')
-                       if os.path.basename(v) in langmaps
-                      ]
-    available_langs += [web.safestr(os.path.basename(v))
-                        for v in glob.glob(cfg.get('rootdir') + 'i18n/[a-z][a-z]')
-                        if os.path.basename(v) in langmaps
-                       ]
+    rootdir = os.path.abspath(os.path.dirname(__file__)) + '/../'
+
+    available_langs = [
+        web.safestr(os.path.basename(v))
+        for v in glob.glob(rootdir + 'i18n/[a-z][a-z]_[A-Z][A-Z]')
+        if os.path.basename(v) in langmaps]
+
+    available_langs += [
+        web.safestr(os.path.basename(v))
+        for v in glob.glob(rootdir + 'i18n/[a-z][a-z]')
+        if os.path.basename(v) in langmaps]
+
     available_langs.sort()
 
     # Get language maps.
     languagemaps = {}
-    [languagemaps.update({i: langmaps[i]})
-     for i in available_langs
-     if i in langmaps
-    ]
+    for i in available_langs:
+        if i in langmaps:
+            languagemaps.update({i: langmaps[i]})
+
     return languagemaps

File libs/ldaplib/admin.py

 from libs import iredutils
 from libs.ldaplib import core, attrs, ldaputils, iredldif, deltree, connUtils, decorators
 
-cfg = web.iredconfig
 session = web.config.get('_session')
 
 
         self.newpw = web.safestr(data.get('newpw'))
         self.confirmpw = web.safestr(data.get('confirmpw'))
 
-        result = iredutils.verifyNewPasswords(self.newpw, self.confirmpw)
+        result = iredutils.verify_new_password(self.newpw, self.confirmpw)
         if result[0] is True:
             self.passwd = ldaputils.generateLDAPPasswd(result[1])
         else:
             self.newpw = web.safestr(data.get('newpw'))
             self.confirmpw = web.safestr(data.get('confirmpw'))
 
-            result = iredutils.verifyNewPasswords(self.newpw, self.confirmpw)
+            result = iredutils.verify_new_password(self.newpw, self.confirmpw)
             if result[0] is True:
                 self.passwd = result[1]
             else:

File libs/ldaplib/connUtils.py

 import web
 import ldap
 from ldap.filter import escape_filter_chars
+import settings
 from libs import iredutils
 from libs.ldaplib import core, ldaputils, decorators, attrs, deltree
 
-cfg = web.iredconfig
 session = web.config.get('_session')
 
 try:
         # Check domainName and domainAliasName.
         try:
             result = self.conn.search_s(
-                cfg.ldap.get('basedn'),
+                settings.ldap_basedn,
                 ldap.SCOPE_ONELEVEL,
                 '(|(domainName=%s)(domainAliasName=%s))' % (self.domain, self.domain),
                 ['domainName', 'domainAliasName', ],

File libs/ldaplib/core.py

 
 import web
 import ldap
-from libs import settings
+import settings
 from libs.ldaplib import attrs
 
-cfg = web.iredconfig
 session = web.config.get('_session')
 
 
 class LDAPWrap:
     def __init__(self, app=web.app, session=session,):
         # Get LDAP settings.
-        self.basedn = cfg.ldap.get('basedn')
-        self.domainadmin_dn = cfg.ldap.get('domainadmin_dn')
+        self.basedn = settings.ldap_basedn
+        self.domainadmin_dn = settings.ldap_domainadmin_dn
 
         # Initialize LDAP connection.
         try:
             # Get LDAP URI.
-            uri = cfg.ldap.get('uri', 'ldap://127.0.0.1')
+            uri = settings.ldap_uri
 
             # Detect STARTTLS support.
             if uri.startswith('ldaps://'):
             return False
 
         # synchronous bind.
-        self.conn.bind_s(cfg.ldap.get('bind_dn'), cfg.ldap.get('bind_pw'))
+        self.conn.bind_s(settings.ldap_bind_dn, settings.ldap_bind_password)
 
     def __del__(self):
         try:

File libs/ldaplib/domain.py

 from libs import iredutils
 from libs.ldaplib import core, attrs, iredldif, ldaputils, deltree, connUtils, decorators
 
-cfg = web.iredconfig
 session = web.config.get('_session')
 
 

File libs/ldaplib/iredldif.py

 # Author: Zhang Huangbin <zhb@iredmail.org>
 
 import web
+import settings
 from libs import iredutils
 from libs.ldaplib import ldaputils
 
-cfg = web.iredconfig
-
 
 # Define and return LDIF structure of domain.
 def ldif_maildomain(domain, cn=None,
-        mtaTransport=cfg.general.get('mtaTransport', 'dovecot'),
+        mtaTransport=settings.default_mta_transport,
         enabledService=['mail'], ):
     domain = web.safestr(domain).lower()
 
-    minPasswordLength = cfg.general.get('min_passwd_length', '8')
+    minPasswordLength = settings.min_passwd_length
 
     ldif = [
             ('objectClass', ['mailDomain']),
     mail = username + '@' + domain
 
     if storageBaseDirectory is None:
-        tmpStorageBaseDirectory = cfg.general.get('storage_base_directory').lower()
+        tmpStorageBaseDirectory = settings.storage_base_directory.lower()
     else:
         tmpStorageBaseDirectory = storageBaseDirectory
 
     storageNode = splitedSBD.pop()
     storageBaseDirectory = '/'.join(splitedSBD)
 
-    mailMessageStore = storageNode + '/' + iredutils.setMailMessageStore(mail)
+    mailMessageStore = storageNode + '/' + iredutils.generate_maildir_path(mail)
     homeDirectory = storageBaseDirectory + '/' + mailMessageStore
 
     # Generate basic LDIF.

File libs/ldaplib/ldaputils.py

 import web
 import ldap
 from ldap.dn import escape_dn_chars
-from libs import iredutils, settings
+import settings
+from libs import iredutils
 from libs.ldaplib import attrs
 
-cfg = web.iredconfig
 session = web.config.get('_session')
 
-basedn = cfg.ldap['basedn']
-domainadmin_dn = cfg.ldap['domainadmin_dn']
-
 
 def convKeywordToDN(keyword, accountType='user'):
     '''Convert keyword and account type to DN.'''
             attrs.RDN_USER, keyword,
             attrs.DN_BETWEEN_USER_AND_DOMAIN,
             attrs.RDN_DOMAIN, domain,
-            basedn,
+            settings.ldap_basedn,
         )
     elif accountType == 'maillist':
         dn = '%s=%s,%s%s=%s,%s' % (
             attrs.RDN_MAILLIST, keyword,
             attrs.DN_BETWEEN_MAILLIST_AND_DOMAIN,
             attrs.RDN_DOMAIN, domain,
-            basedn,
+            settings.ldap_basedn,
         )
     elif accountType == 'maillistExternal':
         dn = '%s=%s,%s%s=%s,%s' % (
             attrs.RDN_MAILLIST_EXTERNAL, keyword,
             attrs.DN_BETWEEN_MAILLIST_EXTERNAL_AND_DOMAIN,
             attrs.RDN_DOMAIN, domain,
-            basedn,
+            settings.ldap_basedn,
         )
     elif accountType == 'alias':
         dn = '%s=%s,%s%s=%s,%s' % (
             attrs.RDN_ALIAS, keyword,
             attrs.DN_BETWEEN_ALIAS_AND_DOMAIN,
             attrs.RDN_DOMAIN, domain,
-            basedn,
+            settings.ldap_basedn,
         )
     elif accountType == 'admin':
         dn = '%s=%s,%s' % (
             attrs.RDN_ADMIN, keyword,
-            domainadmin_dn,
+            settings.ldap_domainadmin_dn,
         )
     elif accountType == 'catchall':
         dn = '%s=@%s,%s%s=%s,%s' % (
             attrs.RDN_CATCHALL, domain,
             attrs.DN_BETWEEN_CATCHALL_AND_DOMAIN,
             attrs.RDN_DOMAIN, domain,
-            basedn,
+            settings.ldap_basedn,
         )
     elif accountType == 'domain':
         dn = '%s=%s,%s' % (
             attrs.RDN_DOMAIN, keyword,
-            basedn,
+            settings.ldap_basedn,
         )
 
     return dn

File libs/ldaplib/user.py

 import ldap
 import ldap.filter
 import web
-from libs import iredutils, settings
+import settings
+from libs import iredutils
 from libs.ldaplib import core, domain as domainlib, attrs, ldaputils, iredldif, connUtils, decorators, deltree
 
-cfg = web.iredconfig
 session = web.config.get('_session')
 
 
         self.newpw = web.safestr(data.get('newpw'))
         self.confirmpw = web.safestr(data.get('confirmpw'))
 
-        result = iredutils.verifyNewPasswords(self.newpw, self.confirmpw,
+        result = iredutils.verify_new_password(self.newpw, self.confirmpw,
                                           min_passwd_length=domainAccountSetting.get('minPasswordLength', '0'),
                                           max_passwd_length=domainAccountSetting.get('maxPasswordLength', '0'),
                                          )
 
         elif self.profile_type == 'password':
             # Get password length from @domainAccountSetting.
-            minPasswordLength = domainAccountSetting.get('minPasswordLength', cfg.general.get('min_passwd_length', '0'))
-            maxPasswordLength = domainAccountSetting.get('maxPasswordLength', cfg.general.get('max_passwd_length', '0'))
+            minPasswordLength = domainAccountSetting.get('minPasswordLength', settings.min_passwd_length)
+            maxPasswordLength = domainAccountSetting.get('maxPasswordLength', settings.max_passwd_length)
 
             # Get new passwords from user input.
             self.newpw = str(data.get('newpw', None))
             self.confirmpw = str(data.get('confirmpw', None))
 
-            result = iredutils.verifyNewPasswords(
+            result = iredutils.verify_new_password(
                 newpw=self.newpw,
                 confirmpw=self.confirmpw,
                 min_passwd_length=minPasswordLength,

File libs/mysql/admin.py

 # Author: Zhang Huangbin <zhb@iredmail.org>
 
 import web
-from libs import iredutils, settings
+import settings
+from libs import iredutils
 from libs.mysql import core, decorators, connUtils
 
-cfg = web.iredconfig
 session = web.config.get('_session')
 
 
         sql_vars = {'admin': self.admin, 'domains': self.domains, }
         if accountType == 'domain':
             try:
-                if self.isGlobalAdmin(self.admin):
+                if self.is_global_admin(self.admin):
                     result = self.conn.select('domain', what='COUNT(domain) AS total',)
                 else:
                     result = self.conn.query(
                 pass
         elif accountType == 'user':
             try:
-                if self.isGlobalAdmin(self.admin):
+                if self.is_global_admin(self.admin):
                     if len(self.domains) >= 0:
                         result = self.conn.select(
                             'mailbox',
                 pass
         elif accountType == 'alias':
             try:
-                if self.isGlobalAdmin(self.admin):
+                if self.is_global_admin(self.admin):
                     if len(self.domains) == 0:
                         result = self.conn.select(
                             'alias',
                 limit=1,
             )
             if len(result) == 1:
-                if self.isGlobalAdmin(admin=self.mail):
+                if self.is_global_admin(admin=self.mail):
                     self.domainGlobalAdmin = True
 
                 return (True, self.domainGlobalAdmin, list(result)[0])
         self.newpw = web.safestr(data.get('newpw'))
         self.confirmpw = web.safestr(data.get('confirmpw'))
 
-        result = iredutils.verifyNewPasswords(self.newpw, self.confirmpw)
+        result = iredutils.verify_new_password(self.newpw, self.confirmpw)
 
         if result[0] is True:
             self.passwd = result[1]
                 name=self.cn,
                 password=iredutils.generate_password_for_sql_mail_account(self.passwd),
                 language=self.preferredLanguage,
-                created=iredutils.getGMTTime(),
+                created=iredutils.get_gmttime(),
                 active='1',
             )
 
                     'domain_admins',
                     username=self.mail,
                     domain='ALL',
-                    created=iredutils.getGMTTime(),
+                    created=iredutils.get_gmttime(),
                     active='1',
                 )
 
             self.confirmpw = web.safestr(data.get('confirmpw', ''))
 
             # Verify new passwords.
-            qr = iredutils.verifyNewPasswords(self.newpw, self.confirmpw)
+            qr = iredutils.verify_new_password(self.newpw, self.confirmpw)
             if qr[0] is True:
                 self.passwd = iredutils.generate_password_for_sql_mail_account(qr[1])
             else:
                     vars=sql_vars,
                     where='username=$username',
                     password=self.passwd,
-                    passwordlastchange=iredutils.getGMTTime(),
+                    passwordlastchange=iredutils.get_gmttime(),
                 )
             except Exception, e:
                 raise web.seeother('/profile/admin/password/%s?msg=%s' % (self.mail, web.urlquote(e)))

File libs/mysql/core.py

 # Author: Zhang Huangbin <zhb@iredmail.org>
 
 import web
-from libs import iredutils, md5crypt
+import settings
+from libs import iredutils
 
-cfg = web.iredconfig
 session = web.config.get('_session')
 
 
 class MySQLWrap:
-    def __init__(self, app=web.app, session=session, **settings):
+    def __init__(self):
         # Initial DB connection and cursor.
         try:
             self.conn = web.database(
                 dbn='mysql',
-                host=cfg.vmaildb.get('host', '127.0.0.1'),
-                port=int(cfg.vmaildb.get('port', 3306)),
-                db=cfg.vmaildb.get('db', 'vmail'),
-                user=cfg.vmaildb.get('user', 'vmailadmin'),
-                pw=cfg.vmaildb.get('passwd', ''),
+                host=settings.vmail_db_host,
+                port=int(settings.vmail_db_port),
+                db=settings.vmail_db_name,
+                user=settings.vmail_db_user,
+                pw=settings.vmail_db_password,
                 charset='utf8',
             )
             self.conn.supports_multiple_insert = True
             return False
 
     # Validators.
-    def isGlobalAdmin(self, admin=None,):
+    def is_global_admin(self, admin=None,):
         if admin is None:
             return False
         elif admin == session.get('username'):
                             vars={'address': als.address, },
                             where='address = $address',
                             goto=','.join([str(v) for v in exist_members if v not in accounts]),
-                            modified=iredutils.getGMTTime(),
+                            modified=iredutils.get_gmttime(),
                         )
                 except Exception, e:
                     pass

File libs/mysql/domain.py

 # Author: Zhang Huangbin <zhb@iredmail.org>
 
 import web
-from libs import iredutils, settings
+import settings
+from libs import iredutils
 from libs.mysql import core, decorators, connUtils
 
-cfg = web.iredconfig
 session = web.config.get('_session')
 
 
             OFFSET %d
         """ % (sql_where, settings.PAGE_SIZE_LIMIT, (page - 1) * settings.PAGE_SIZE_LIMIT,)
 
-        if self.isGlobalAdmin(admin):
+        if self.is_global_admin(admin):
             try:
                 resultOfTotal = self.conn.select(
                     'domain',
                 'domain',
                 domain=domain,
                 description=cn,
-                transport=cfg.general.get('transport', 'dovecot'),
-                created=iredutils.getGMTTime(),
+                transport=settings.default_mta_transport,
+                created=iredutils.get_gmttime(),
                 active='1',
             )
             web.logger(msg="Create domain: %s." % (domain), domain=domain, event='create',)
         domain = str(domain)
 
         # Pre-defined update key:value.
-        updates = {'modified': iredutils.getGMTTime(), }
+        updates = {'modified': iredutils.get_gmttime(), }
 
         sql_vars = {'domain': domain, }
 

File libs/mysql/user.py

 # Author: Zhang Huangbin <zhb@iredmail.org>
 
 import web
-from libs import iredutils, settings
+import settings
+from libs import iredutils
 from libs.mysql import core, decorators, connUtils, domain as domainlib, admin as adminlib
 
-cfg = web.iredconfig
 session = web.config.get('_session', {})
 
 ENABLED_SERVICES = [
         confirmpw = web.safestr(data.get('confirmpw', ''))
 
         # Get password length limit from domain profile or global setting.
-        minPasswordLength = domainProfile.get('minpasswordlength', cfg.general.get('min_passwd_length', '0'))
-        maxPasswordLength = domainProfile.get('maxpasswordlength', cfg.general.get('max_passwd_length', '0'))
+        minPasswordLength = domainProfile.get('minpasswordlength', settings.min_passwd_length)
+        maxPasswordLength = domainProfile.get('maxpasswordlength', settings.max_passwd_length)
 
-        resultOfPW = iredutils.verifyNewPasswords(
+        resultOfPW = iredutils.verify_new_password(
             newpw,
             confirmpw,
             min_passwd_length=minPasswordLength,
         cn = data.get('cn', '')
 
         # Get storage base directory.
-        tmpStorageBaseDirectory = cfg.general.get('storage_base_directory').lower()
+        tmpStorageBaseDirectory = settings.storage_base_directory.lower()
         splitedSBD = tmpStorageBaseDirectory.rstrip('/').split('/')
         storageNode = splitedSBD.pop()
         storageBaseDirectory = '/'.join(splitedSBD)
                 username=self.mail,
                 password=passwd,
                 name=cn,
-                maildir=iredutils.setMailMessageStore(self.mail),
+                maildir=iredutils.generate_maildir_path(self.mail),
                 quota=mailQuota,
                 storagebasedirectory=storageBaseDirectory,
                 storagenode=storageNode,
-                created=iredutils.getGMTTime(),
+                created=iredutils.get_gmttime(),
                 active='1',
                 local_part=mail_local_part,
             )
                 address=self.mail,
                 goto=self.mail,
                 domain=self.domain,
-                created=iredutils.getGMTTime(),
+                created=iredutils.get_gmttime(),
                 active='1',
             )
 
         self.domain = self.mail.split('@', 1)[-1]
 
         # Pre-defined update key:value.
-        updates = {'modified': iredutils.getGMTTime()}
+        updates = {'modified': iredutils.get_gmttime()}
 
         if self.profile_type == 'general':
             # Get settings of domain admin and global admin
                     self.conn.insert('domain_admins',
                                      username=self.mail,
                                      domain=managed_domain,
-                                     created=iredutils.getGMTTime(),
+                                     created=iredutils.get_gmttime(),
                                      active=1,
                                     )
                 except:
             confirmpw = str(data.get('confirmpw', ''))
 
             # Verify new passwords.
-            qr = iredutils.verifyNewPasswords(newpw, confirmpw)
+            qr = iredutils.verify_new_password(newpw, confirmpw)
             if qr[0] is True:
                 pwscheme = None
                 if 'storePasswordInPlainText' in data and settings.STORE_PASSWORD_IN_PLAIN:
                     'mailbox',
                     vars={'username': self.mail, },
                     where='username=$username',
-                    passwordlastchange=iredutils.getGMTTime(),
+                    passwordlastchange=iredutils.get_gmttime(),
                 )
             except:
                 pass

File libs/pgsql/admin.py

 # Author: Zhang Huangbin <zhb@iredmail.org>
 
 import web
-from libs import iredutils, settings
+import settings
+from libs import iredutils
 from libs.pgsql import core, decorators, connUtils
 
-cfg = web.iredconfig
 session = web.config.get('_session')
 
 
         sql_vars = {'admin': self.admin, 'domains': self.domains, }
         if accountType == 'domain':
             try:
-                if self.isGlobalAdmin(self.admin):
+                if self.is_global_admin(self.admin):
                     result = self.conn.select('domain', what='COUNT(domain) AS total',)
                 else:
                     result = self.conn.query(
                 pass
         elif accountType == 'user':
             try:
-                if self.isGlobalAdmin(self.admin):
+                if self.is_global_admin(self.admin):
                     if len(self.domains) >= 0:
                         result = self.conn.select(
                             'mailbox',
                 pass
         elif accountType == 'alias':
             try:
-                if self.isGlobalAdmin(self.admin):
+                if self.is_global_admin(self.admin):
                     if len(self.domains) == 0:
                         result = self.conn.select(
                             'alias',
                 limit=1,
             )
             if len(result) == 1:
-                if self.isGlobalAdmin(admin=self.mail):
+                if self.is_global_admin(admin=self.mail):
                     self.domainGlobalAdmin = True
 
                 return (True, self.domainGlobalAdmin, list(result)[0])
         self.newpw = web.safestr(data.get('newpw'))
         self.confirmpw = web.safestr(data.get('confirmpw'))
 
-        result = iredutils.verifyNewPasswords(self.newpw, self.confirmpw)
+        result = iredutils.verify_new_password(self.newpw, self.confirmpw)
 
         if result[0] is True:
             self.passwd = result[1]
                 name=self.cn,
                 password=iredutils.generate_password_for_sql_mail_account(self.passwd),
                 language=self.preferredLanguage,
-                created=iredutils.getGMTTime(),
+                created=iredutils.get_gmttime(),
                 active='1',
             )
 
                     'domain_admins',
                     username=self.mail,
                     domain='ALL',
-                    created=iredutils.getGMTTime(),
+                    created=iredutils.get_gmttime(),
                     active='1',
                 )
 
             self.confirmpw = web.safestr(data.get('confirmpw', ''))
 
             # Verify new passwords.
-            qr = iredutils.verifyNewPasswords(self.newpw, self.confirmpw)
+            qr = iredutils.verify_new_password(self.newpw, self.confirmpw)
             if qr[0] is True:
                 self.passwd = iredutils.generate_password_for_sql_mail_account(qr[1])
             else:
                     vars=sql_vars,
                     where='username=$username',
                     password=self.passwd,
-                    passwordlastchange=iredutils.getGMTTime(),
+                    passwordlastchange=iredutils.get_gmttime(),
                 )
             except Exception, e:
                 raise web.seeother('/profile/admin/password/%s?msg=%s' % (self.mail, web.urlquote(e)))

File libs/pgsql/core.py

 # Author: Zhang Huangbin <zhb@iredmail.org>
 
 import web
-from libs import iredutils, md5crypt
+import settings
+from libs import iredutils
 
-cfg = web.iredconfig
 session = web.config.get('_session')
 
 
 class PGSQLWrap:
-    def __init__(self, app=web.app, session=session, **settings):
+    def __init__(self):
         # Initial DB connection and cursor.
         try:
             self.conn = web.database(
                 dbn='postgres',
-                host=cfg.vmaildb.get('host', '127.0.0.1'),
-                port=int(cfg.vmaildb.get('port', 5432)),
-                db=cfg.vmaildb.get('db', 'vmail'),
-                user=cfg.vmaildb.get('user', 'vmailadmin'),
-                pw=cfg.vmaildb.get('passwd', ''),
+                host=settings.vmail_db_host,
+                port=int(settings.vmail_db_port),
+                db=settings.vmail_db_name,
+                user=settings.vmail_db_user,
+                pw=settings.vmail_db_password,
             )
             self.conn.supports_multiple_insert = True
         except:
             return False
 
     # Validators.
-    def isGlobalAdmin(self, admin=None,):
+    def is_global_admin(self, admin=None,):
         if admin is None:
             return False
         elif admin == session.get('username'):
                             vars={'address': als.address, },
                             where='address = $address',
                             goto=','.join([str(v) for v in exist_members if v not in accounts]),
-                            modified=iredutils.getGMTTime(),
+                            modified=iredutils.get_gmttime(),
                         )
                 except Exception, e:
                     pass

File libs/pgsql/domain.py

 # Author: Zhang Huangbin <zhb@iredmail.org>
 
 import web
-from libs import iredutils, settings
+import settings
+from libs import iredutils
 from libs.pgsql import core, decorators, connUtils
 
-cfg = web.iredconfig
 session = web.config.get('_session')
 
 
             OFFSET %d
         """ % (sql_where, settings.PAGE_SIZE_LIMIT, (page - 1) * settings.PAGE_SIZE_LIMIT,)
 
-        if self.isGlobalAdmin(admin):
+        if self.is_global_admin(admin):
             try:
                 resultOfTotal = self.conn.select(
                     'domain',
                 'domain',
                 domain=domain,
                 description=cn,
-                transport=cfg.general.get('transport', 'dovecot'),
-                created=iredutils.getGMTTime(),
+                transport=settings.default_mta_transport,
+                created=iredutils.get_gmttime(),
                 active='1',
             )
             web.logger(msg="Create domain: %s." % (domain), domain=domain, event='create',)
         domain = str(domain)
 
         # Pre-defined update key:value.
-        updates = {'modified': iredutils.getGMTTime(), }
+        updates = {'modified': iredutils.get_gmttime(), }
 
         sql_vars = {'domain': domain, }
 

File libs/pgsql/user.py

 # Author: Zhang Huangbin <zhb@iredmail.org>
 
 import web
-from libs import iredutils, settings
+import settings
+from libs import iredutils
 from libs.pgsql import core, decorators, connUtils, domain as domainlib, admin as adminlib
 
-cfg = web.iredconfig
 session = web.config.get('_session', {})
 
 ENABLED_SERVICES = [
         confirmpw = web.safestr(data.get('confirmpw', ''))
 
         # Get password length limit from domain profile or global setting.
-        minPasswordLength = domainProfile.get('minpasswordlength', cfg.general.get('min_passwd_length', '0'))
-        maxPasswordLength = domainProfile.get('maxpasswordlength', cfg.general.get('max_passwd_length', '0'))
+        minPasswordLength = domainProfile.get('minpasswordlength', settings.min_passwd_length)
+        maxPasswordLength = domainProfile.get('maxpasswordlength', settings.max_passwd_length)
 
-        resultOfPW = iredutils.verifyNewPasswords(
+        resultOfPW = iredutils.verify_new_password(
             newpw,
             confirmpw,
             min_passwd_length=minPasswordLength,
         cn = data.get('cn', '')
 
         # Get storage base directory.
-        tmpStorageBaseDirectory = cfg.general.get('storage_base_directory').lower()
+        tmpStorageBaseDirectory = settings.storage_base_directory.lower()
         splitedSBD = tmpStorageBaseDirectory.rstrip('/').split('/')
         storageNode = splitedSBD.pop()
         storageBaseDirectory = '/'.join(splitedSBD)
                 username=self.mail,
                 password=passwd,
                 name=cn,
-                maildir=iredutils.setMailMessageStore(self.mail),
+                maildir=iredutils.generate_maildir_path(self.mail),
                 quota=mailQuota,
                 storagebasedirectory=storageBaseDirectory,
                 storagenode=storageNode,
-                created=iredutils.getGMTTime(),
+                created=iredutils.get_gmttime(),
                 active='1',
                 local_part=mail_local_part,
             )
                 address=self.mail,
                 goto=self.mail,
                 domain=self.domain,
-                created=iredutils.getGMTTime(),
+                created=iredutils.get_gmttime(),
                 active='1',
             )
 
         self.domain = self.mail.split('@', 1)[-1]
 
         # Pre-defined update key:value.
-        updates = {'modified': iredutils.getGMTTime()}
+        updates = {'modified': iredutils.get_gmttime()}
 
         if self.profile_type == 'general':
             # Get settings of domain admin and global admin
                     self.conn.insert('domain_admins',
                                      username=self.mail,
                                      domain=managed_domain,
-                                     created=iredutils.getGMTTime(),
+                                     created=iredutils.get_gmttime(),
                                      active=1,
                                     )
                 except:
             confirmpw = str(data.get('confirmpw', ''))
 
             # Verify new passwords.
-            qr = iredutils.verifyNewPasswords(newpw, confirmpw)
+            qr = iredutils.verify_new_password(newpw, confirmpw)
             if qr[0] is True:
                 pwscheme = None
                 if 'storePasswordInPlainText' in data and settings.STORE_PASSWORD_IN_PLAIN:
                     'mailbox',
                     vars={'username': self.mail, },
                     where='username=$username',
-                    passwordlastchange=iredutils.getGMTTime(),
+                    passwordlastchange=iredutils.get_gmttime(),
                 )
             except:
                 pass

File settings.py.ldap.sample

+############################################################
+# DO NOT TOUCH BELOW LINE.
+#
+# Import default settings.
+# You can always override default settings by placing custom settings in this
+# file.
+from libs.default_settings import *
+
+############################################################
+# General settings.
+#
+# Site webmaster's mail address.
+webmaster = 'zhb@iredmail.org'
+
+# Default language.
+default_language = 'en_US'
+
+# Database backend: ldap.
+backend = 'ldap'
+
+# Base directory used to store all mail data.
+# iRedMail uses '/var/vmail/vmail1' as default storage directory.
+# Tip: You can set a per-domain storage directory in domain profile page.
+storage_base_directory = '/var/vmail/vmail1'
+
+# Default mta transport.
+# iRedMail uses 'dovecot' as defualt transport.
+# Tip: You can set a per-domain or per-user transport in domain or user
+#      profile page.
+default_mta_transport = 'dovecot'
+
+# Min/Max admin password length.
+#   - min_passwd_length: 0 means unlimited, but at least 1 character
+#                        is required.
+#   - max_passwd_length: 0 means unlimited.
+# User password length is controlled in domain profile.
+min_passwd_length = 8
+max_passwd_length = 0
+
+#####################################################################
+# Database used to store iRedAdmin data. e.g. sessions, log.
+#
+iredadmin_db_host = '127.0.0.1'
+iredadmin_db_port = 3306
+iredadmin_db_name = 'iredadmin'
+iredadmin_db_user = 'iredadmin'
+iredadmin_db_password = 'password'
+
+############################################################################
+# Settings used for OpenLDAP backend.
+#
+# LDAP server uri. Examples:
+# - ldap://127.0.0.1    normal LDAP connection (port 389)
+# - ldaps://127.0.0.1   secure connection through STARTTLS (port 389)
+ldap_uri = 'ldap://127.0.0.1'
+
+# LDAP suffix.
+# basedn: dn which contains virtual domains.
+# domainadmin_dn: dn which contains virtual domain admins.
+ldap_basedn = 'o=domains,dc=iredmail,dc=org'
+ldap_domainadmin_dn = 'o=domainAdmins,dc=iredmail,dc=org'
+
+# Bind dn and password.
+#   - bind dn should have write privilege in LDAP.
+#   - bind pw is plain text, not encryped/hashed.
+ldap_bind_dn = 'cn=vmailadmin,dc=iredmail,dc=org'
+ldap_bind_password = 'password'
+
+############################################################################
+# Settings used for Policyd (1.8.x) integration. Provides global
+# white-/blacklist, sender/recipient throttling, etc.
+#
+# Enable policyd integration: True, False.
+policyd_enabled = True
+
+# SQL Database used to store policyd data, eg. whitelist, blacklist.
+# You can find related information in policyd config files:
+#   - On RHEL/CentOS:   /etc/policyd.conf
+#   - On Debian/Ubuntu: /etc/postfix-policyd.conf
+#   - On FreeBSD:       /usr/local/etc/policyd.conf
+# Related parameters:
+#   host    -> MYSQLHOST
+#   port    -> 3306 (Default)
+#   db      -> MYSQLDBASE
+#   user    -> MYSQLUSER
+#   passwd  -> MYSQLPASS
+policyd_db_host = '127.0.0.1'
+policyd_db_port = 3306
+policyd_db_name = 'policyd'
+policyd_db_user = 'policyd'
+policyd_db_password = 'password'
+
+##############################################################################
+# Settings used for Amavisd-new integration. Provides spam/virus quaranting,
+# releasing, etc.
+#
+# Log basic info of in/out emails into SQL (@storage_sql_dsn): True, False.
+# It's @storage_sql_dsn setting in amavisd. You can find this setting
+# in amavisd-new config files:
+#   - On RHEL/CentOS:   /etc/amavisd.conf or /etc/amavisd/amavisd.conf
+#   - On Debian/Ubuntu: /etc/amavis/conf.d/50-user.conf
+#   - On FreeBSD:       /usr/local/etc/amavisd.conf
+# Reference:
+# http://www.iredmail.org/wiki/index.php?title=IRedMail/FAQ/Integrate.MySQL.in.Amavisd
+amavisd_enable_logging = True
+
+amavisd_db_host = '127.0.0.1'
+amavisd_db_port = 3306
+amavisd_db_name = 'amavisd'
+amavisd_db_user = 'amavisd'
+amavisd_db_password = 'password'
+
+# #### Quarantining ####
+# Release quarantined SPAM/Virus mails: True, False.
+# iRedAdmin-Pro will connect to @quarantine_server to release quarantined mails.
+# How to enable quarantining in Amavisd-new:
+# http://www.iredmail.org/wiki/index.php?title=IRedMail/FAQ/Quarantining.SPAM
+amavisd_enable_quarantine = True
+
+# Port of Amavisd protocol 'AM.PDP-INET'. Default is 9998.
+amavisd_quarantine_port = 9998
+
+##############################################################################
+# Place your custom settings below, you can override all settings in this file
+# and libs/default_settings.py here.
+#

File settings.py.mysql.sample

+############################################################
+# DO NOT TOUCH BELOW LINE.
+#
+from libs.default_settings import *
+
+############################################################
+# General settings.
+#
+# Site webmaster's mail address.
+webmaster = 'zhb@iredmail.org'
+
+# Default language.
+default_language = 'en_US'
+
+# Database backend: mysql.
+backend = 'mysql'
+
+# Base directory used to store all mail data.
+# iRedMail uses '/var/vmail/vmail1' as default storage directory.
+# Tip: You can set a per-domain storage directory in domain profile page.
+storage_base_directory = '/var/vmail/vmail1'
+
+# Default mta transport.
+# iRedMail uses 'dovecot' as defualt transport.
+# Tip: You can set a per-domain or per-user transport in domain or user
+#      profile page.