import cStringIO
import cPickle
import re
import os
import lasso
import glob
import zipfile

from quixote import get_publisher, get_request, get_response, redirect
from quixote.directory import Directory, AccessControlled

from menu import *

import larpe
from larpe.template import DEFAULT_TEMPLATE_EZT
from larpe import misc
from larpe.form import *
from larpe.hosts import Host
from larpe.admin.liberty_utils import *

class LibertyIDPDir(Directory):
    _q_exports = ['new', ('metadata.xml', 'metadata')]

    def _q_index [html] (self):
        misc.reload_cfg()
        html_top('settings', title = _('Identity Provider'))
        "<h2>%s</h2>" % _('Identity Provider')
        '<ul id="nav-idp-admin"> <li><a href="new">%s</a></li> </ul>' % _('New')

        '<ul class="biglist">'
        for kidp, idp in misc.cfg.get('idp', {}).items():
            p = lasso.Provider(lasso.PROVIDER_ROLE_IDP,
                    misc.get_abs_path(idp['metadata']),
                    misc.get_abs_path(idp['publickey']), None)
            try: # this handling since "if p is None: continue" doesn't work
                if p.providerId == '':
                    pass
            except TypeError:
                continue

            '<li>'
            '<strong class="label">%s</strong>' % misc.get_provider_label(p)
            '<p class="details">'
            '<span class="data">%s</span>' % p.providerId
            '</p>'
            '<p class="commands">'
            command_icon('%s/' % kidp, 'view')
            command_icon('%s/edit' % kidp, 'edit')
            command_icon('%s/delete' % kidp, 'remove')
            '</p></li>'
        '</ul>'

    def _q_lookup(self, component):
        misc.reload_cfg()
        return LibertyIDPUI(component)

    def new [html] (self):
        form = Form(enctype="multipart/form-data")
        form.add(FileWidget, "metadata", title = _("Metadata"), required=True)
        form.add(FileWidget, "publickey", title = _("Public Key"), required=True)
        form.add(FileWidget, "cacertchain", title = _("CA Certificate Chain"), required=False)
        form.add_submit("submit", _("Submit"))

        if not form.is_submitted() or form.has_errors():
            html_top('settings', title = _('New Identity Provider'))
            "<h2>%s</h2>" % _('New Identity Provider')
            form.render()
        else:
            self.submit_new(form)

    def submit_new(self, form, key_provider_id = None):
        metadata, publickey, cacertchain = None, None, None
        if form.get_widget('metadata').parse():
            metadata = form.get_widget('metadata').parse().fp.read()
        if form.get_widget('publickey').parse():
            publickey = form.get_widget('publickey').parse().fp.read()
        if form.get_widget('cacertchain').parse():
            cacertchain = form.get_widget('cacertchain').parse().fp.read()

        if not key_provider_id:
            try:
                provider_id = re.findall(r'(provider|entity)ID="(.*?)"', metadata)[0][1]
            except IndexError:
                return error_page(_('Bad metadata'))
            key_provider_id = provider_id.replace(str('://'), str('-')).replace(str('/'), str('-'))

        dir = os.path.join(get_publisher().app_dir, 'idp', key_provider_id)
        if not os.path.isdir(dir):
            os.makedirs(dir)
        metadata_fn = 'metadata.xml'
        publickey_fn = 'public_key.pem'
        cacertchain_fn = 'ca_cert_chain.pem'

        if metadata:
            file(os.path.join(dir, metadata_fn), 'w').write(metadata)
        if publickey:
            file(os.path.join(dir, publickey_fn), 'w').write(publickey)
        if cacertchain:
            file(os.path.join(dir, cacertchain_fn), 'w').write(cacertchain)

        idps_dir = misc.get_abs_path('idp')
        idp_name = key_provider_id
        idp_dir = os.path.join(idps_dir, idp_name)
        p = lasso.Provider(lasso.PROVIDER_ROLE_IDP,
                os.path.join(idp_dir, 'metadata.xml'),
                os.path.join(idp_dir, 'public_key.pem'),
                None)                    
        try:
            misc.get_provider_label(p)
            misc.cfg['idp'] = idp_name
            misc.write_cfg()
        except TypeError:
            if metadata:
                os.unlink(os.path.join(dir, metadata_fn))
            if publickey:
                os.unlink(os.path.join(dir, publickey_fn))
            if cacertchain:
                os.unlink(os.path.join(dir, cacertchain_fn))
            return error_page(_('Bad metadata'))

        redirect('..')

    def metadata(self):
        response = get_response()
        response.set_content_type('text/xml', 'utf-8')
        misc.reload_cfg()
        if misc.cfg['idp']:
            idp_metadata = os.path.join(misc.get_abs_path('idp'), misc.cfg['idp'], 'metadata.xml')
            return unicode(open(idp_metadata).read(), 'utf-8')
        return 'No IDP is configured'


class LibertyIDPUI(Directory):
    _q_exports = ["", "delete", "edit"]

    def __init__(self, component):
        self.idp = misc.cfg['idp'][component]
        self.idpk = component

    def _q_index [html] (self):
        html_top('settings', title = _('Identity Provider'))
        p = lasso.Provider(lasso.PROVIDER_ROLE_SP,
                misc.get_abs_path(self.idp['metadata']),
                misc.get_abs_path(self.idp['publickey']),
                misc.get_abs_path(self.idp.get('cacertchain', None)))
        '<h2>%s - %s</h2>' % (_('Identity Provider'), p.providerId)
        '<div class="form">'
        '<h3>%s</h3>' % _('Metadata')
        '<pre>'
        file(misc.get_abs_path(self.idp['metadata'])).read()
        '</pre>'
        '</div>'

    def edit [html] (self):
        form = Form(enctype="multipart/form-data")
        form.add(FileWidget, "metadata", title = _("Metadata"))
        form.add(FileWidget, "publickey", title = _("Public Key"))
        form.add(FileWidget, "cacertchain", title = _("CA Certificate Chain"))
        form.add(CheckboxWidget, 'hide', title = _('Hide this provider from user lists'),
                required = False, value = self.idp.get('hide'))
        form.add_submit("submit", _("Submit"))

        if not form.is_submitted() or form.has_errors():
            html_top('settings', title = _('Edit Identity Provider'))
            "<h2>%s</h2>" % _('Edit Identity Provider')
            form.render()
        else:
            t = LibertyIDPDir()
            t.submit_new(form, self.idpk) # XXX: not ok for metadata file path

    def delete [html] (self):
        p = lasso.Provider(lasso.PROVIDER_ROLE_SP,
                misc.get_abs_path(self.idp['metadata']),
                misc.get_abs_path(self.idp['publickey']), None)
        form = Form(enctype="multipart/form-data")
        form.widgets.append(HtmlWidget("<p>%s</p>" % _(
                        "You are about to irrevocably remove this identity provider.")))
        form.add_submit("submit", _("Submit"))
        form.add_submit("cancel", _("Cancel"))
        if form.get_widget('cancel').parse():
            return redirect('..')
        if not form.is_submitted() or form.has_errors():
            html_top('settings', title = _('Identity Provider'))
            '<h2>%s %s</h2>' % (_('Deleting'), p.providerId)
            form.render()
        else:
            self.delete_submitted()

    def delete_submitted(self):
        del misc.cfg['idp'][self.idpk]
        dir = get_publisher().app_dir
        metadata_fn = os.path.join(dir, 'idp-%s-metadata.xml' % self.idpk)
        publickey_fn = os.path.join(dir, 'idp-%s-publickey.pem' % self.idpk)
        cacertchain_fn = os.path.join(dir, 'idp-%s-cacertchain.pem' % self.idpk)
        for f in (metadata_fn, publickey_fn, cacertchain_fn):
            if os.path.exists(f):
                os.unlink(f)
        misc.write_cfg()
        return redirect('..')


class EmailsDirectory(Directory):
    emails = [ ('new_user', N_('Notification of creation to user')),
            ('new_receiver', N_('Notification of creation to receiver')),
            ('change_user', N_('Notification of change to user')),
            ('change_receiver', N_('Notification of change to receiver')),
            ('comment_user', N_('Notification of comment to user')),
            ('comment_receiver', N_('Notification of comment to receiver')),
            ]

    def __init__(self):
        self._q_exports = ['', 'options'] + [x[0] for x in self.emails]

    def options [html] (self):
        form = Form(enctype="multipart/form-data")
        emails = misc.cfg.get('emails', {})
        form.add(StringWidget, 'smtp_server', title = _('SMTP Server'),
                required = False, value = emails.get('smtp_server', ''))
        form.add(StringWidget, 'from', title = _('Email Sender'),
                required = True, value = emails.get('from', 'larpe@localhost'))
        form.add(StringWidget, 'reply_to', title = _('Reply-To Address'),
                required = False, value = emails.get('reply_to'))

        form.add_submit("submit", _("Submit"))
        form.add_submit("cancel", _("Cancel"))
        if form.get_widget('cancel').parse():
            return redirect('.')

        if not form.is_submitted() or form.has_errors():
            html_top('settings', title = _('Emails'))
            "<h2>%s</h2>" % _('General Options')
            form.render()
        else:
            self.options_submit(form)
            redirect('.')

    def options_submit(self, form):
        misc.reload_cfg()
        if not misc.cfg.has_key('emails'):
            misc.cfg['emails'] = {}
        for k in ('smtp_server', 'from', 'reply_to'):
            misc.cfg['emails'][k] = form.get_widget(k).parse()
        misc.write_cfg()

    def new_user(self):
        return self.email('new_user', _('Notification of creation to user'),
                _('Available variables: url, details'), enabled = False)

    def new_receiver(self):
        return self.email('new_receiver', _('Notification of creation to receiver'),
                _('Available variables: url, details'))

    def change_user(self):
        return self.email('change_user', _('Notification of change to user'),
                _('Available variables: url, before, after, evolution'))

    def change_receiver(self):
        return self.email('change_receiver', _('Notification of change to receiver'),
                _('Available variables: url, before, after, evolution'))

    def comment_user(self):
        return self.email('comment_user', _('Notification of comment to user'),
                _('Available variables: url, evolution'))

    def comment_receiver(self):
        return self.email('comment_receiver', _('Notification of comment to receiver'),
                _('Available variables: url, evolution'))

    def _q_index [html] (self):
        html_top('settings', title = _('Emails'))
        '<h2>%s</h2>' % _('Emails')

        '<ul>'
        '<li><a href="options">%s</a></li>' % _('General Options')
        for email_key, email_label in self.emails:
            '<li><a href="%s">%s %s</a></li>' % (email_key,
                    _('Custom Email:'), _(email_label))
        '</ul>'

        '<p>'
        '<a href="..">%s</a>' % _('Back')
        '</p>'


    def email [html] (self, email_key, email_label, hint = None, check_template = None,
                enabled = True):
        emails_cfg = misc.cfg.get('emails', {})
        cfg_key = 'email-%s' % email_key

        form = Form(enctype='multipart/form-data')
        form.add(CheckboxWidget, cfg_key + '_enabled', title = _('Enabled Email'),
                value = emails_cfg.get(cfg_key + '_enabled', True), default = enabled)
        form.add(StringWidget, cfg_key + '_subject', title = _('Subject'),
                value = emails_cfg.get(cfg_key + '_subject', ''))
        form.add(TextWidget, cfg_key, title = email_label, value = emails_cfg.get(cfg_key),
                cols = 80, rows = 10, hint = hint)
        form.add_submit('submit', _('Submit'))
        form.add_submit('restore-default', _('Restore default email'))
        form.add_submit('cancel', _('Cancel'))

        if form.get_submit() == 'cancel':
            return redirect('.')

        if form.get_submit() == 'restore-default':
            self.email_submit(None, cfg_key)
            return redirect('.')

        if form.is_submitted() and not form.has_errors():
            if self.email_submit(form, cfg_key, check_template):
                return redirect('.')
            form.set_error(cfg_key, _('Invalid template'))

        html_top('settings', title = _('Emails'))
        '<h2>%s - %s</h2>' % (_('Email'), email_label)
        form.render()

    def email_submit(self, form, cfg_key, check_template = None):
        misc.reload_cfg()
        if not misc.cfg.has_key('emails'):
            misc.cfg['emails'] = {}
        if form:
            template = form.get_widget(cfg_key).parse()
            if check_template and not check_template(template):
                return False
            misc.cfg['emails'][str(cfg_key)] = template
            misc.cfg['emails'][str(cfg_key + '_enabled')] = form.get_widget(
                    cfg_key + '_enabled').parse()
            misc.cfg['emails'][str(cfg_key + '_subject')] = form.get_widget(
                    cfg_key + '_subject').parse()
        else:
            misc.cfg['emails'][str(cfg_key)] = None
        misc.write_cfg()
        return True




class SettingsDirectory(AccessControlled, Directory):
    _q_exports = ['', 'liberty_sp', 'liberty_idp', 'metadata', ('public_key.pem', 'public_key'),
                  'apache2_configuration_generation' ]

    liberty_idp = LibertyIDPDir()
#    emails = EmailsDirectory()

    def _q_access(self):
        get_response().breadcrumb.append( ('settings/', _('Settings')) )

    def _q_index [html] (self):
        misc.reload_cfg()
        html_top('settings', title = _('Settings'))

        if lasso.SAML2_SUPPORT:
            '<h2>Liberty Alliance & SAML 2.0 Service Provider</h2>'
            '<dl> <dt><a href="liberty_sp">%s</a></dt> <dd>%s</dd>' % (
                    _('Service Provider'), _('Configure Liberty / SAML 2.0 parameters'))
        else:
            '<h2>Liberty Alliance Service Provider</h2>'
            '<dl> <dt><a href="liberty_sp">%s</a></dt> <dd>%s</dd>' % (
                    _('Service Provider'), _('Configure Liberty parameters'))

        hosts = Host.select(lambda x: x.name == 'larpe')
        if hosts:
            self.host = hosts[0]

            if self.host.metadata is not None:
                metadata_url = '%s/metadata.xml' % self.host.base_url
                '<dt><a href="%s">%s</a></dt> <dd>%s</dd>' % (
                        metadata_url,
                        _('Service Provider Metadata'),
                        _('Download Service Provider ID-FF 1.2 Metadata file'))

            if lasso.SAML2_SUPPORT:
                metadata_url = '%s/metadata.xml' % self.host.saml2_base_url
                '<dt><a href="%s">%s</a></dt> <dd>%s</dd>' % (
                        metadata_url,
                        _('Service Provider Metadata'),
                        _('Download Service Provider SAML 2.0 Metadata file'))

            if self.host.public_key is not None:
                '<dt><a href="public_key.pem">%s</a></dt> <dd>%s</dd>' % (
                        _('Public key'),
                        _('Download Service Provider SSL Public Key file'))

        if lasso.SAML2_SUPPORT:
            '<h2>Liberty Alliance & SAML 2.0 Identity Provider</h2>'
        else:
            '<h2>Liberty Alliance Identity Provider</h2>'

        '<dl>'        

        '<dt><a href="liberty_idp/new">%s</a></dt> <dd>%s</dd>' % (
               _('Identity Provider'), _('Configure an identity provider'))

        if misc.cfg.has_key('idp'):
            '<dt><a href="liberty_idp/metadata.xml">%s</a></dt> <dd>%s</dd>' % (
                    _('Identity Provider configuration'), _('See current identity provider metadatas'))

        '</dl>'

        '<h2>%s</h2>' % _('Customisation')

        '<dl>'
        '<dt><a href="apache2_configuration_generation">%s</a></dt> <dd>%s</dd>' % (
                _('Apache 2 configuration generation'), _('Customise Apache 2 configuration generation'))
#        '<dt><a href="language">%s</a></dt> <dd>%s</dd>' % (
#                _('Language'), _('Configure site language'))
#        '<dt><a href="themes">%s</a></dt> <dd>%s</dd>' % (
#                _('Theme'), _('Configure theme'))
#        '<dt><a href="template">%s</a></dt> <dd>%s</dd>' % (
#                _('Template'), _('Configure template'))
#        '<dt><a href="home">%s</a></dt> <dd>%s</dd>' % (
#                _('Home'), _('Configure home page'))
#        '<dt><a href="emails">%s</a></dt> <dd>%s</dd>' % (
#                _('Emails'), _('Configure email settings'))
        '</dl>'

#        '<h2>%s</h2>' % _('Misc')
#        '<dl>'
#        '<dt><a href="misc">%s</a></dt> <dd>%s</dd>' % (
#                _('Misc'), _('Configure misc options'))
#        '<dt><a href="debug_options">%s</a></dt> <dd>%s</dd>' % (
#                _('Debug Options'), _('Configure options useful for debugging'))
#        '</dl>'

#     def language [html] (self):
#         form = Form(enctype='multipart/form-data')
#         language_cfg = misc.cfg.get('language', {})
#         form.add(SingleSelectWidget, 'language', title = _('Language'),
#                 value = language_cfg.get('language'),
#                 options = [ (None, _('System Default')),
#                             (str('HTTP'), _('From HTTP Accept-Language header')),
#                             (str('en'), _('English')),
#                             (str('es'), _('Spanish')),
#                             (str('fr'), _('French')) ] )
#         
#         form.add_submit('submit', _('Submit'))
#         form.add_submit('cancel', _('Cancel'))
#         if form.get_widget('cancel').parse():
#             return redirect('.')

#         if not form.is_submitted() or form.has_errors():
#             html_top('settings', title = _('Language'))
#             '<h2>%s</h2>' % _('Language')
#             form.render()
#         else:
#             self.language_submit(form)
#             redirect('.')

#     def language_submit(self, form):
#         misc.reload_cfg()
#         if not misc.cfg.has_key('language'):
#             misc.cfg['language'] = {}
#         for k in ('language', ):
#             misc.cfg['language'][k] = form.get_widget(k).parse()
#         misc.write_cfg()

    def liberty_sp [html] (self):
        misc.reload_cfg()
        req = get_request()
        if not misc.cfg.has_key('proxy_hostname'):
            misc.cfg[str('proxy_hostname')] = req.get_server().split(str(':'))[0]
            
        # Get the hosts object for the reverse proxy
        hosts = Host.select(lambda x: x.name == 'larpe')
        if hosts:
            self.host = hosts[0]
        else:
            self.host = Host()
            self.host.reversed_hostname = misc.cfg[str('proxy_hostname')]

        form = Form(enctype='multipart/form-data')
        form.add(StringWidget, 'proxy_hostname', title=_('Domain name of the reverse proxy'), size=50,
                required = True, value = self.host.reversed_hostname)
        form.add(StringWidget, 'organization_name', title=_('Organisation Name'), size=50,
                required = True, value = self.host.organization_name)
        form.add_submit('submit', _('Submit'))
        form.add_submit('cancel', _('Cancel'))
        if form.get_widget('cancel').parse():
            return redirect('.')
        if not form.is_submitted() or form.has_errors():
            html_top('settings', title = _('Service Provider Configuration'))
            '<h2>%s</h2>' % _('Service Provider Configuration')
            form.render()
        else:
            self.liberty_sp_save(form)
            redirect('.')

    def liberty_sp_save(self, form):
        misc.reload_cfg()
        metadata_cfg = {}

        for f in ( 'organization_name', 'proxy_hostname' ):
            if form.get_widget(f):
                setattr(self.host, f, form.get_widget(f).parse())

        metadata_cfg['organization_name'] = self.host.organization_name

        self.host.name = 'larpe'
        
        # Liberty Alliance / SAML parameters
        base_url = '%s/liberty/%s/liberty' % (misc.get_root_url(), self.host.name)
        metadata_cfg['base_url'] = base_url
        self.host.base_url = base_url

        if lasso.SAML2_SUPPORT:
            saml2_base_url = '%s/saml/%s/saml' % (misc.get_root_url(), self.host.name)
            metadata_cfg['saml2_base_url'] = saml2_base_url
            self.host.saml2_base_url = saml2_base_url

        provider_id = '%s/metadata' % base_url
        metadata_cfg['provider_id'] = provider_id
        self.host.provider_id = provider_id

        if lasso.SAML2_SUPPORT:
            saml2_provider_id = '%s/metadata' % saml2_base_url
            metadata_cfg['saml2_provider_id'] = saml2_provider_id
            self.host.saml2_provider_id = saml2_provider_id

        # Storage directories
        site_dir = os.path.join(get_publisher().app_dir, 'sp',
                    self.host.reversed_hostname, self.host.name)
        user_dir = os.path.join(site_dir, 'users')
        token_dir = os.path.join(site_dir, 'tokens')
        for dir in (site_dir, user_dir, token_dir):
            if not os.path.isdir(dir):
                os.makedirs(dir)
        metadata_cfg['site_dir'] = site_dir
        self.host.site_dir = site_dir

        # Generate SSL keys
        private_key_path = os.path.join(site_dir, 'private_key.pem')
        public_key_path = os.path.join(site_dir, 'public_key.pem')
        if not os.path.isfile(private_key_path) or not os.path.isfile(public_key_path):
            set_provider_keys(private_key_path, public_key_path)
#            metadata_cfg['privatekey'] = private_key_path
            self.host.private_key = private_key_path
#            metadata_cfg['publickey'] = public_key_path
            self.host.public_key = public_key_path
        
        # Write metadatas
        metadata_path = os.path.join(site_dir, 'metadata.xml')
        file(metadata_path, 'w').write(get_metadata(metadata_cfg))
#        metadata_cfg['metadata'] = metadata_path
        self.host.metadata = metadata_path

        if hasattr(self.host, 'saml2_provider_id'):
            saml2_metadata_path = os.path.join(site_dir, 'saml2_metadata.xml')
            file(saml2_metadata_path, 'w').write(get_saml2_metadata(metadata_cfg))
#            metadata_cfg['saml2_metadata'] = saml2_metadata_path
            self.host.saml2_metadata = saml2_metadata_path

        # Use default idps
#         idp_dir = os.path.join(get_publisher().app_dir, 'idp')
#         self.host.idps = os.listdir(idp_dir)

        self.host.root_url = '%s/' % misc.get_root_url()
        self.host.return_url = '%s/admin/' % misc.get_root_url()

        self.host.store()

    def metadata(self):
        hosts = Host.select(lambda x: x.name == 'larpe')
        if hosts:
            host = hosts[0]
        else:
            return redirect('%s/admin/' % misc.get_root_url())
        response = get_response()
        response.set_content_type('text/xml', 'utf-8')
        metadata = unicode(open(host.metadata).read(), 'utf-8')
        return metadata

    def public_key(self):
        hosts = Host.select(lambda x: x.name == 'larpe')
        if hosts:
            host = hosts[0]
        else:
            # FIXME : error page ?
            return redirect('.')
        response = get_response()
        response.set_content_type('text/plain')
        public_key = open(host.public_key).read()
        return public_key

    def apache2_configuration_generation [html] (self):
        misc.reload_cfg()

        form = Form(enctype='multipart/form-data')
        form.add(CheckboxWidget, 'allow_config_generation',
                title=_('Automatically generate Apache 2 configuration for new hosts and reload Apache 2 after changes'),
                value = misc.cfg.get(str('allow_config_generation'), True))
        form.add_submit('submit', _('Submit'))
        form.add_submit('cancel', _('Cancel'))
        if form.get_widget('cancel').parse():
            return redirect('.')
        if not form.is_submitted() or form.has_errors():
            html_top('settings', title = _('Apache 2 configuration generation'))
            '<h2>%s</h2>' % _('Apache 2 configuration generation')
            form.render()
        else:
            self.apache2_configuration_generation_save(form)
            redirect('.')
            
    def apache2_configuration_generation_save(self, form):
        misc.reload_cfg()

        f = 'allow_config_generation'
        misc.cfg[f] = form.get_widget(f).parse()

        misc.write_cfg()

#     def themes [html] (self):
#         import xml.dom.minidom

#         def getText(nodelist):
#             rc = ""
#             for node in nodelist:
#                 if node.nodeType == node.TEXT_NODE:
#                     rc = rc + node.data
#             return rc.encode('iso-8859-1')

#         request = get_request()

#         if not request.form.has_key('theme'):
#             current_theme = misc.cfg.get('branding', {}).get('theme', 'default')

#             html_top('settings', title = _('Themes'))
#             "<h2>%s</h2>" % _('Themes')
#             '<form action="themes" enctype="multipart/form-data" method="post">'
#             theme_files = glob.glob(os.path.join(larpe.DATA_DIR, str('themes/*/desc.xml')))
#             theme_files.sort()
#             '<ul class="biglist">'
#             for t in theme_files:
#                 dom = xml.dom.minidom.parseString(open(t).read())
#                 theme = dom.getElementsByTagName('theme')[0].attributes['name'].value.encode(
#                         str('iso-8859-1'))
#                 if current_theme == theme:
#                     checked = ' checked="checked"'
#                 else:
#                     checked = ''
#                 '<li>'
#                 '<strong class="label">'
#                 '  <input name="theme" value="%s" type="radio"%s>%s</input></strong>' % (
#                         theme, checked, getText(dom.getElementsByTagName('label')[0].childNodes))
#                 icon_file = t.replace(str('desc.xml'), str('icon.png'))
#                 if os.path.exists(icon_file):
#                     '<img src="/themes/%s/icon.png" alt="" class="theme-icon" />' % theme
#                 '<p class="details">%s<br/>by %s</p>' % (
#                         getText(dom.getElementsByTagName('desc')[0].childNodes),
#                         getText(dom.getElementsByTagName('author')[0].childNodes))
#                 '</li>'
#             '</ul>'
#             '<div class="buttons">'
#             '<input type="submit" name="submit" value="%s" />' % _('Submit')
#             '</div>'
#             '</form>'
#         else:
#             if not misc.cfg.has_key('branding'):
#                 misc.cfg[str('branding')] = {}
#             misc.cfg[str('branding')][str('theme')] = str(request.form['theme'])
#             misc.write_cfg()
#             return redirect('.')


#     def template [html] (self):
#         branding_cfg = misc.cfg.get('branding', {})
#         template = branding_cfg.get('template', DEFAULT_TEMPLATE_EZT)
#         form = Form(enctype="multipart/form-data")
#         form.add(TextWidget, 'template', title = _('Site Template'), value = template,
#                 cols = 80, rows = 25)
#         form.add_submit("submit", _("Submit"))
#         form.add_submit("cancel", _("Cancel"))
#         if form.get_widget('cancel').parse():
#             return redirect('.')

#         if not form.is_submitted() or form.has_errors():
#             html_top('settings', title = _('Template'))
#             '<h2>%s</h2>' % _('Template')
#             form.render()
#         else:
#             self.template_submit(form)
#             redirect('.')


#     def template_submit(self, form):
#         misc.reload_cfg()
#         branding_cfg = misc.cfg.get('branding', {})
#         template = form.get_widget('template').parse()
#         if template == DEFAULT_TEMPLATE_EZT or not template:
#             if branding_cfg.has_key('template'):
#                 del branding_cfg['template']
#         else:
#             branding_cfg['template'] = template
#         misc.cfg['branding'] = branding_cfg
#         misc.write_cfg()


#     def home [html] (self):
#         home_cfg = misc.cfg.get('home', {})

#         form = Form(enctype="multipart/form-data")
#         form.add(TextWidget, 'text-unlogged', title = _('Text for unlogged users'),
#                 value = home_cfg.get('text-unlogged'), cols = 80, rows = 8)
#         form.add(TextWidget, 'text-logged', title = _('Text for logged users'),
#                 value = home_cfg.get('text-logged'), cols = 80, rows = 8)
#         form.add_submit("submit", _("Submit"))
#         form.add_submit("cancel", _("Cancel"))

#         if form.get_submit() == 'cancel':
#             return redirect('.')

#         if not form.is_submitted() or form.has_errors():
#             html_top('settings', title = _('Home page'))
#             '<h2>%s</h2>' % _('Home page')
#             form.render()
#         else:
#             self.home_submit(form)
#             redirect('.')

#     def home_submit(self, form):
#         misc.reload_cfg()
#         home_cfg = misc.cfg.get('home', {})
#         for k in ('text-unlogged', 'text-logged'):
#             home_cfg[k] = form.get_widget(k).parse()
#         misc.cfg['home'] = home_cfg
#         misc.write_cfg()


#     def misc [html] (self):
#         misc_cfg = misc.cfg.get('misc', {})
#         form = Form(enctype="multipart/form-data")
#         form.add(CheckboxWidget, 'grab-user-with-wsf',
#                 title = _('Grab user details with ID-WSF on first logon'),
#                 value = misc_cfg.get('grab-user-with-wsf', False))
#         if not lasso.WSF_SUPPORT:
#             widget = form.get_widget('grab-user-with-wsf')
#             widget.hint = _('Lasso version is too old for this support.')
#             widget.attrs[str('disabled')] = str('disabled')
#         form.add(CheckboxWidget, 'do-not-token',
#                 title = _('Do not show anything about identification tokens'),
#                 value = misc_cfg.get('do-not-token', False))
#         form.add(RadiobuttonsWidget, 'features', title = _('Features'),
#                 value = misc_cfg.get('features', 'both'),
#                 options = [ (str('forms'), _('Forms')),
#                     (str('consultations'), _('Consultations')),
#                     (str('both'), _('Both'))])
#         form.add(CheckboxWidget, 'include-user-details',
#                 title = _('Show user details on public pages'),
#                 value = misc_cfg.get('include-user-details', False))
#         form.add_submit("submit", _("Submit"))
#         form.add_submit("cancel", _("Cancel"))
#         if form.get_widget('cancel').parse():
#             return redirect('.')

#         if not form.is_submitted() or form.has_errors():
#             html_top('settings', title = _('Misc'))
#             '<h2>%s</h2>' % _('Misc')
#             form.render()
#         else:
#             self.misc_submit(form)
#             redirect('.')

#     def misc_submit(self, form):
#         misc.reload_cfg()
#         misc_cfg = misc.cfg.get('misc', {})
#         for k in ('features', 'grab-user-with-wsf', 'do-not-token', 'include-user-details'):
#             misc_cfg[k] = form.get_widget(k).parse()
#         misc.cfg['misc'] = misc_cfg
#         misc.write_cfg()

#     def export [html] (self):
#         form = Form(enctype="multipart/form-data")
#         form.add(CheckboxWidget, 'formdefs', title = _('Forms'), value = True)
#         form.add(CheckboxWidget, 'workflows', title = _('Workflows'), value = True)
#         form.add(CheckboxWidget, 'roles', title = _('Roles'), value = True)
#         form.add(CheckboxWidget, 'categories', title = _('Categories'), value = True)
#         form.add(CheckboxWidget, 'settings', title = _('Settings'), value = False)
#         form.add_submit('submit', _('Submit'))
#         form.add_submit('cancel', _('Cancel'))
#         if form.get_submit() == 'cancel':
#             return redirect('.')

#         if not form.is_submitted():
#             html_top('settings', title = _('Export'))
#             "<h2>%s</h2>" % _('Export')
#             form.render()
#         else:
#             return self.export_submit(form)

#     def export_submit [plain] (self, form):
#         dirs = []
#         for w in ('formdefs', 'workflows', 'roles', 'categories'):
#             if form.get_widget(w) and form.get_widget(w).parse():
#                 dirs.append(w)
#         if not dirs:
#             return redirect('.')

#         c = cStringIO.StringIO()
#         z = zipfile.ZipFile(c, 'w')
#         app_dir = get_publisher().app_dir
#         for d in dirs:
#             path = os.path.join(app_dir, d)
#             if not os.path.exists(path):
#                 continue
#             for f in os.listdir(path):
#                 z.write(os.path.join(path, f), os.path.join(d, f))
#         if form.get_widget('settings').parse():
#             z.write(os.path.join(app_dir, 'config.pck'), 'config.pck')
#             for f in os.listdir(app_dir):
#                 if f.startswith('idp-') and os.path.splitext(f)[-1] in ('.pem', '.xml'):
#                     z.write(os.path.join(app_dir, f), f)
#         z.close()

#         response = get_response()
#         response.set_content_type('application/x-larpe')
#         response.set_header('content-disposition', 'attachment; filename=export.larpe')
#         return c.getvalue()

#     def p_import [html] (self):
#         form = Form(enctype="multipart/form-data")
#         form.add(FileWidget, "file", title = _('File'), required = True)
#         form.add_submit('submit', _('Submit'))
#         form.add_submit('cancel', _('Cancel'))
#         if form.get_submit() == 'cancel':
#             return redirect('.')

#         if not form.is_submitted() or form.has_errors():
#             html_top('settings', title = _('Import'))
#             "<h2>%s</h2>" % _('Import')
#             form.render()
#         else:
#             try:
#                 results = self.import_submit(form)
#             except zipfile.BadZipfile:
#                 results = None
#             html_top('settings', title = _('Import'))
#             "<h2>%s</h2>" % _('Import')
#             if results:
#                 '<p>%s</p>' % _('Imported successfully:')
#                 '<ul>'
#                 if results['formdefs']:
#                     '<li>%d %s</li>' % (results['formdefs'], _('forms'))
#                 if results['workflows']:
#                     '<li>%d %s</li>' % (results['workflows'], _('workflows'))
#                 if results['roles']:
#                     '<li>%d %s</li>' % (results['roles'], _('roles'))
#                 if results['categories']:
#                     '<li>%d %s</li>' % (results['categories'], _('categories'))
#                 if results['settings']:
#                     '<li>%s</li>' % _('Settings')
#                 '</ul>'
#             else:
#                 '<p>%s</p>' % _('Error: Not a valid export file')
#             '<a href=".">%s</a>' % _('Back')

#     def import_submit(self, form):
#         z = zipfile.ZipFile(form.get_widget('file').parse().fp, 'r')
#         app_dir = get_publisher().app_dir
#         results = {'formdefs': 0, 'workflows': 0, 'categories': 0, 'roles': 0, 'settings': 0}
#         for f in z.namelist():
#             path = os.path.join(app_dir, f)
#             data = z.read(f)
#             if not os.path.exists(os.path.dirname(path)):
#                 os.mkdir(os.path.dirname(path))
#             if f == 'config.pck':
#                 results['settings'] = 1
#                 d = cPickle.loads(data)
#                 if misc.cfg.has_key('sp'):
#                     current_sp = misc.cfg['sp']
#                 else:
#                     current_sp = None
#                 misc.cfg = d
#                 if current_sp:
#                     misc.cfg['sp'] = current_sp
#                 else:
#                     del misc.cfg['sp']
#                 misc.write_cfg()
#                 continue
#             open(path, 'w').write(data)
#             if results.has_key(os.path.split(f)[0]):
#                 results[os.path.split(f)[0]] += 1
#         z.close()
#         return results
#  
#     def debug_options [html] (self):
#         form = Form(enctype="multipart/form-data")
#         debug_cfg = misc.cfg.get('debug', {})
#         form.add(StringWidget, 'error_email', title = _('Email for Tracebacks'),
#                 value = debug_cfg.get('error_email', ''))
#         form.add(SingleSelectWidget, 'display_exceptions', title = _('Display Exceptions'),
#                 value = debug_cfg.get('display_exceptions', ''),
#                 options = [ (str(''), _('No display')),
#                             (str('text'), _('Display as Text')),
#                             (str('text-in-html'), _('Display as Text in HTML an error page')),
#                             (str('html'), _('Display as HTML')) ])
#         form.add(CheckboxWidget, 'logger', title = _('Logger'),
#                 value = debug_cfg.get('logger', False))
#         form.add_submit("submit", _("Submit"))
#         form.add_submit("cancel", _("Cancel"))

#         if form.get_widget('cancel').parse():
#             return redirect('.')

#         if not form.is_submitted() or form.has_errors():
#             html_top('settings', title = _('Debug Options'))
#             '<h2>%s</h2>' % _('Debug Options')
#             form.render()
#         else:
#             self.debug_options_submit(form)
#             redirect('.')

#     def debug_options_submit(self, form):
#         misc.reload_cfg()
#         if not misc.cfg.has_key('debug'):
#             misc.cfg['debug'] = {}
#         for k in ('error_email', 'display_exceptions', 'logger'):
#             misc.cfg['debug'][k] = form.get_widget(k).parse()
#         misc.write_cfg()
#         get_publisher().set_config()



def error_page [html] (error_message):
    html_top(_('Error'))
    '<h1>%s</h1>' % _('Error')
    '<div class="error-page">'
    '<p>%s</p>' % error_message
    '</div>'
