########################################################################
# 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 string,cgiforms,w2lcore,msbase,web2ldapcnf,w2lgui,w2lcnf,ldapbase

########################################################################
# Output a pretty search form
########################################################################

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

  if 'search_scope' in form.inputkeys:
    form.field['search_scope'][0].setdefault(form.field['search_scope'][0].content)

  if 'searchform_mode' in form.inputkeys:
    searchform_mode = form.field['searchform_mode'][0].content
  else:
    searchform_mode = 'base'

  search_root_field = w2lgui.SearchRootField(form,ls)

  w2lgui.PrintHeader(outf,'',form.accept_charset)
  w2lgui.MainMenuTable(outf,form,ls)

  if searchform_mode == 'base':

    # base search form with fixed input fields

    searchform_template_filename = w2lgui.GetVariantFilename(
      w2lcnf.GetParam(ls,'searchform_template',''),
      map(string.strip,string.split(form.env.get('HTTP_ACCEPT_LANGUAGE',''),','))
    )

    if searchform_template_filename:
      try:
  	template_str = open(searchform_template_filename,'r').read()
	outf.write('<div id=InputDiv><h1>Base Search Form</h1>')
	outf.write(
	  '<form action="%s/search" method="%s" enctype="application/x-www-form-urlencoded" accept-charset="%s">\n%s\n' % (
            form.script_name,
	    web2ldapcnf.script_method,
	    form.accept_charset,
            template_str
	  )
	)

      except IOError:
	outf.write('<div id=MessageDiv><p>I/O error during reading template file.</p></div>')
    else:
      outf.write('<div id=MessageDiv><p>Template file not found.</p></div>')


  elif searchform_mode == 'exp':

    # expert search form for using LDAP filters
    outf.write('<div id=InputDiv><h1>Expert Search Form</h1>')
    search_filterstr = form.field.get('search_filterstr',[])
    search_filterstr = search_filterstr[0].content
    outf.write("""<form action="%s/search" method="%s" enctype="application/x-www-form-urlencoded" accept-charset="%s">
             LDAP filter string<BR>
	     <input name="search_filterstr" maxlength="120" size="60" value="%s">
	     """ % (form.script_name,web2ldapcnf.script_method,form.accept_charset,search_filterstr))

  elif searchform_mode == 'adv':

    # advanced search form with select lists
    outf.write('<div id=InputDiv><h1>Advanced Search Form</h1>')

    if ('search_params' in form.inputkeys) and \
       form.field['search_params'][0].content:
      # Gewuenschte Anzahl der Suchparameter wurde angegeben
      rows = string.atoi(form.field['search_params'][0].content)
      if rows<1:                rows=1
      if rows>web2ldapcnf.max_searchparams: rows=web2ldapcnf.max_searchparams
    else:
      rows = 1

    # More und Fewer-Buttons ausgeben
    outf.write('<table><tr>')
    if rows<web2ldapcnf.max_searchparams:
      outf.write(
        '<td>%s</td>' % w2lgui.CommandButton(
	  form,'searchform','More',
	  ls.who,
	  ls.cred,
	  ls.host,
          ls.dn,
	  extrastr='<input type=hidden name="searchform_mode" value="adv"><input type=hidden name="search_params" value="%d">' % (rows+1)
        )
      )
    if rows>1:
      outf.write('<td>%s</td>' % w2lgui.CommandButton(
          form,'searchform','Fewer',
	  ls.who,
	  ls.cred,
	  ls.host,
          ls.dn,
	  extrastr='<input type=hidden name="searchform_mode" value="adv"><input type=hidden name="search_params" value="%d">' % (rows-1)
        )
      )

    outf.write('<td>search parameters</td></tr></table>')

    search_mode_select = cgiforms.formSelectClass('search_mode',u'Search mode',[(ur'(&amp;%s)',u'all'),(ur'(|%s)',u'any')])
    search_mode_select.setcharset(form.accept_charset)
    search_attrs = w2lcnf.GetParam(ls,'search_attrs',['cn','mail'])

    # Eigentliches Suchformular ausgeben
    outf.write("""<form action="%s/search" method="%s" enctype="application/x-www-form-urlencoded" accept-charset="%s">
Match %s of the following.<br>
""" % (form.script_name,web2ldapcnf.script_method,form.accept_charset,search_mode_select.inputfield()))

    search_attr_list = []
    for attr in search_attrs:
      search_attr_list.append((attr,w2lcore.ldap_knownattr.get(attr,attr)))
    search_attr_select = cgiforms.formSelectClass('search_attr',u'Search attribute type',search_attr_list,multiple=web2ldapcnf.max_searchparams)
    search_attr_select.setcharset(form.accept_charset)
    search_option_select = cgiforms.formSelectClass('search_option','Search option',w2lcore.search_options,multiple=web2ldapcnf.max_searchparams)
    search_option_select.setcharset(form.accept_charset)
    # Output a row of the search form
    for i in range(rows):
      search_attr_select.setdefault(search_attrs[i % len(search_attrs)])
      outf.write('%s\n%s\n' % (search_attr_select.inputfield(),search_option_select.inputfield()))
      # Output of search string input field
      outf.write('<input name="search_string" maxlength="60" size="30" value=""><br>\n')

  # Output of form part for all kind of search forms
  outf.write("""
<p>
 Search root
 %s
 Scope %s
 Results per page %s
</p>
 <input type=hidden name="who"     value="%s">
 <input type=hidden name="cred" value="%s">
 <input type=hidden name="host"       value="%s">
 <input type="submit" value="Search">
 <input type="reset" value="Reset">
 </form>
</div>
""" % (
    search_root_field.inputfield(),
    form.field['search_scope'][0].inputfield(),
    form.field['search_resnumber'][0].inputfield(),
    w2lcore.utf2display(form.accept_charset,ls.who),
    w2lcore.utf2display(form.accept_charset,ls.cred),
    ls.host.encode('ascii'),
  ))

  w2lgui.PrintFooter(outf)

