"""
w2lapp.referral.py: chase LDAP referrals

web2ldap - a web-based LDAP Client,
see http://www.web2ldap.de for details

(c) by Michael Stroeder <michael@stroeder.com>

This module is distributed under the terms of the
GPL (GNU GENERAL PUBLIC LICENSE) Version 2
(see http://www.gnu.org/copyleft/gpl.html)

$Id: referral.py,v 1.16 2002/01/10 02:27:07 michael Exp $
"""

import ldaputil.base,w2lapp.core,w2lapp.gui,w2lapp.cnf

from ldapurl import LDAPUrl

ErrorMessageDiv = """<div id=ErrorMessageDiv>
<h1>Error</h1>
<p>
  %s
</p>
"""

def w2l_ChaseReferral(sid,outf,command,form,ls,dn,e):

  w2lapp.gui.TopSection(
    sid,outf,form,ls,dn,
    'Referral received',
    w2lapp.gui.MainMenu(sid,form,ls,dn),
    context_menu_list=[]
  )

  # Pull out referral LDAP URL
  try:
    ldap_url_info = [
      s.strip()
      for s in e.args[0].get('info','').split('\n')
    ]
  except ValueError:
    outf.write(
      ErrorMessageDiv % (
        'Error extracting referral LDAP URL from %s.' % (repr(e))
      )
    )
    return
  else:
    try:
      ldap_url_info = ldap_url_info[1]
    except IndexError,e:
      outf.write(
        ErrorMessageDiv % (
          'Error extracting referral LDAP URL from %s.' % (repr(ldap_url_info))
        )
      )
      return
    # Parse the referral LDAP URL
    try:
      referralUrl = LDAPUrl(ldap_url_info[ldap_url_info.find('ldap:'):])
    except ValueError,e:
      outf.write(ErrorMessageDiv % (
          'Error parsing referral URL %s: %s' % (
            repr(ldap_url_info),str(e)
          )
        )
      )
      return

    # DN which triggered the referral
    matched_dn = e.args[0].get('matched','')
    matched_dn_list = ldaputil.base.explode_dn(matched_dn)
    referral_dn_list = ldaputil.base.explode_dn(referralUrl.dn)
    # determine new DN
    dn_list=ldaputil.base.explode_dn(dn)
    new_dn = ','.join(
      dn_list[0:len(dn_list)-len(matched_dn_list)]+referral_dn_list
    )

  outf.write("""<div id=InputDiv>
<h1>Referral received</h1>
<p>
  Referral URL: %s
</p>
<p>
  Referral DN %s matches %s =&gt; %s
</p>
"""  % (
      referralUrl.unparse(charset=form.accept_charset),
      w2lapp.gui.DisplayDN(sid,form,ls,referralUrl.dn),
      w2lapp.gui.DisplayDN(sid,form,ls,matched_dn),
      w2lapp.gui.DisplayDN(sid,form,ls,new_dn),
    )
  )
  if command=='ldapurl':
    outf.write("""<h2><a href="%s/ldapurl?%s">Chase Referral</a></h2>
""" % (
        form.script_name,
        referralUrl.unparse(charset='utf-8',urlEncode=1)
      )
    )
  else:
    outf.write("""
<form
  id=CommandForm
  action="%s/%s/%s"
  method="POST"
  enctype="application/x-www-form-urlencoded"
  accept-charset="%s"
>
  <input type="hidden" name="host" value="%s">
  <input type="hidden" name="dn" value="%s">
  %s
"""  % (
        form.script_name,
        command,
        sid,
        form.accept_charset,
        referralUrl.hostport,
        w2lapp.core.utf2display(form.accept_charset,new_dn),
        w2lapp.gui.BindInput % (
          referralUrl.hostport,
          w2lapp.core.iso2display(
            form.accept_charset,
            w2lapp.cnf.hosts.ldap_def.get(
              ls.host,w2lapp.cnf.hosts.Web2LDAPConfig()
            ).get('description','')
          ),
          w2lapp.gui.SearchRootField(form,ls,dn,name='login_search_root').inputHTML(),
          '',
          'Chase Referral',
        ),
      )
    )
    form.hiddenInputFields(outf,['sid','host','dn','who','cred','login_search_root'])
    outf.write('</form></div>\n')

  w2lapp.gui.PrintFooter(outf,form)
