"""
w2lreferral - Chase referrals
(c) by Michael Stroeder <michael@stroeder.com>

Distributed under GNU Public License (GPL)
web-based LDAP Client, see http://www.web2ldap.de for details
"""

import sys,string,ldap,ldapbase,w2lcore,w2lgui,web2ldapcnf

def w2l_ChaseReferral(outf,command,form,ls,e,reuse_binddn=0):


  if not reuse_binddn:
    ls.who = ''

  # Get the description of the LDAP exception
  referral_desc = e.args[0]['desc']
  # Pull out referral LDAP URL
  try:
    info, ldap_url_info = map(string.strip,string.split(e.args[0].get('info',''),'\n',1))
  except ValueError:
    ldap_url = ''
    info = ''
    referral_host = ''
    referral_dn = ''
    new_dn = ''
    matched_dn = ''
  else:
    ldap_url_list = string.split(ldap_url_info,'\n')
    ldap_url = ldap_url_list[0]
    # Parse the referral LDAP URL
    referral_host,referral_dn,search_attr,search_scope,search_filterstr,ext = ldapbase.parse_ldap_url(ldap_url)
    # DN which triggered the referral
    matched_dn = e.args[0].get('matched','')
    matched_dn_list = ldapbase.explode_dn(matched_dn)
    referral_dn_list = ldapbase.explode_dn(referral_dn)
    # determine new DN
    ls.dn_list=ldap.explode_dn(ls.dn)
    new_dn = string.join(
      ls.dn_list[0:len(ls.dn_list)-len(matched_dn_list)]+referral_dn_list,
      ','
    )

  w2lgui.PrintHeader(outf,referral_desc,form.accept_charset)
  w2lgui.MainMenuTable(outf,form,ls)
  outf.write("""<h1>Referral received</h1>
<p>%s: %s<br />
Referral DN %s matches %s =&gt; %s
</p>
"""  % (
      referral_desc,w2lgui.DataStr(form,ls,ldap_url),
      w2lgui.DisplayDN(form.accept_charset,referral_dn),
      w2lgui.DisplayDN(form.accept_charset,matched_dn),
      w2lgui.DisplayDN(form.accept_charset,new_dn),
    )
  )
  if command=='ldapurl':
    outf.write("""<h2><a href="%s/ldapurl?%s">Chase Referral</a></h2>
""" % (
        form.script_name,
        ldap_url
      )
    )
  else:
    outf.write("""<form
  id=CommandForm
  action="%s/%s"
  method="%s"
  enctype="application/x-www-form-urlencoded"
  accept-charset="%s"
>
  %s
  <input type="hidden" name="dn" value="%s">
  <input type="hidden" name="host" value="%s">
  <p>host:port %s (%s)</p>
  <input type="submit" value="Chase Referral">
"""  % (
        form.script_name,
        command,
        web2ldapcnf.script_method,
        form.accept_charset,
        w2lgui.BindInput % (''),
        w2lcore.utf2display(form.accept_charset,new_dn),
        referral_host,
        referral_host,
        w2lcore.iso2display(
          form.accept_charset,
          web2ldapcnf.hosts.ldap_def.get(referral_host,{}).get('description','')
        ),
      )
    )
    form.hiddeninputparams(outf,['host','dn','who','cred'])
    outf.write('</form>\n')

  w2lgui.PrintFooter(outf)
