########################################################################
# web2ldap
# (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,cgiforms,ldap,ldapbase,w2lcore,web2ldapcnf, w2lgui

########################################################################
# Modify RDN
########################################################################

def w2l_ModRDN(outf,command,form,ls):

  if 'modrdn_newrdn' in form.inputkeys:

    modrdn_newrdn = form.field['modrdn_newrdn'][0].content
    if 'modrdn_delold' in form.inputkeys:
      modrdn_delold = form.field['modrdn_delold'][0].content=='yes'
    else:
      modrdn_delold = 0
    ls.l.modrdn_s(
      ls.dn.encode('utf-8'),
      modrdn_newrdn.encode('utf-8'),
      modrdn_delold
    )
    # delete all cache entries referencing to old DN
    ls.l.uncache_entry(ls.dn.encode('utf-8'))

    new_dn = '%s,%s' % (modrdn_newrdn,w2lcore.ParentDN(ls.dn))
    w2lgui.PrintHeader(outf,'Modified DN of entry.',form.accept_charset)
    w2lgui.MainMenuTable(outf,form,ls,new_dn)
    outf.write('<DIV ID=MessageDiv><P>Modified DN of entry <STRONG>%s</STRONG> to <STRONG>%s</STRONG>.</P></DIV>' % (w2lcore.utf2display(form.accept_charset,ls.dn),w2lcore.utf2display(form.accept_charset,new_dn)))
    w2lgui.PrintFooter(outf)

  else:
    form.field['modrdn_newrdn'][0].setdefault(w2lcore.utf2display(form.accept_charset,ldapbase.SplitRDN(ls.dn)[0]))
    # Leeres Eingabeformular für neuen RDN ausgeben
    w2lgui.PrintHeader(outf,'Modify RDN',form.accept_charset)
    w2lgui.MainMenuTable(outf,form,ls)
    outf.write("""
<div id=InputDiv>
<h1>Modify RDN</h1>
<form action="%s/modrdn"
      method="%s"
      enctype="application/x-www-form-urlencoded"
      accept-charset="%s"
>
  <input type=hidden name="dn" value="%s">
  <input type=hidden name="host" value="%s">
  <input type=hidden name="who" value="%s">
  <input type=hidden name="cred" value="%s">
  <table>
    <tr><td>%s</td><td>%s</td></tr>
    <tr><td>%s</td><td>%s</td></tr>
  </table>
  <input type="submit" value="Change RDN">
  <input type="reset" value="Reset">
</form>
</div>
""" % (
      form.script_name,
      web2ldapcnf.script_method,
      form.accept_charset,
      ls.dn.encode(form.accept_charset),
      ls.host.encode('ascii'),
      w2lcore.utf2display(form.accept_charset,ls.who),
      w2lcore.utf2display(form.accept_charset,ls.cred),
      form.field['modrdn_newrdn'][0].text.encode(form.accept_charset),
      form.field['modrdn_newrdn'][0].inputfield(),
      form.field['modrdn_delold'][0].text.encode(form.accept_charset),
      form.field['modrdn_delold'][0].inputfield()
    ))
    w2lgui.PrintFooter(outf)


