# coding: latin-1

import ldif,os,re
import mod_python.apache

_stylesdir='../styles'
_scripturi='http://www.tphys.physik.uni-tuebingen.de/tplist/phonelist.py'

_strings_de={
      "room" : "Raum",
      "phone" : "Telefon",
      "group" : "Gruppe",
      "name" : "Name",
      "OP" : "Professoren",
      "EM" : "Emeriti",
      'AP' : "Wissenschaftliche Mitarbeiter",
      'PD' : "Wissenschaftliche Mitarbeiter",
      'AR' : "Wissenschaftliche Mitarbeiter",
      'AD' : "Wissenschaftliche Mitarbeiter",
      "WA" : "Wissenschaftliche Mitarbeiter",
      "WH" : "Wissenschaftliche Mitarbeiter",
      "DO" : "Doktoranden",
      "DI" : "Diplomanden",
      "SE" : "Sekretariat",
      "BI" : "Bibliothek",
      "mainuri" : "http://www.tphys.physik.uni-tuebingen.de/DE/mitarbeiter.shtml",
      "mainuridesc" : "Mitarbeiterverzeichnis"
    }
_strings_en={
      "room" : "Room",
      "phone" : "Telephone",
      "group" : "Group",
      "name" : "Name",
      "OP" : "Professors",
      "EM" : "Emeriti",
      'AP' : "Scientific Staff",
      'PD' : "Scientific Staff",
      'AR' : "Scientific Staff",
      'AD' : "Scientific Staff",
      "WA" : "Scientific Staff",
      "WH" : "Scientific Staff",
      "DO" : "PhD Students",
      "DI" : "Diploma Students",
      "SE" : "Secretary",
      "BI" : "Library",
      "mainuri" : "http://www.tphys.physik.uni-tuebingen.de/EN/mitarbeiter.shtml",
      "mainuridesc" : "Staff Index"
    }
_categories={
    'OP': 1,
    'EM': 2,
    'AP': 3,
    'PD': 3,
    'AR': 3,
    'AD': 3,
    'WA': 3,
    'WH': 3,
    'DO': 4,
    'DI': 5,
    'SE': 6,
    'BI': 7,
    'XX': 1000}

class _MyLDIFParser(ldif.LDIFParser):
    def __init__(
        self,
        input_file,
        ignored_attr_types=None,max_entries=0,process_url_schemes=None
    ):
        """
        See LDIFParser.__init__()

        Additional Parameters:
        all_records
            List instance for storing parsed records
        """
        ldif.LDIFParser.__init__(self,input_file,ignored_attr_types,max_entries,process_url_schemes)
        self.all_records=[]

    def handle(self,dn,entry):
        """
        Append single record to dictionary of all records.
        """
        if entry.get('webShow',['FALSE'])[0]=='TRUE':
            self.all_records.append((dn,entry))

# The publisher will call this function as default
#def index(req, lang="de"):
#    return greeting(req, lang)

#def greeting(req, lang="de"):
#    if lang=="de": message="Hallo."
#    elif lang=="en": message="Hello."
#    else: message="Diese Sprache kann ich nicht."
#    return "<html><body><h1>%s</h1></body></html>" % message

def index(req, lang='de', mode=None, uid=None):
    global strings
    if lang=='en': strings=_strings_en
    else:
        lang='de'
        strings=_strings_de
    if mode==None:
        if uid!=None:
            _printVCard(req, lang, uid)
        else:
            _printUsersTable(req, lang)
    elif mode=='bild':
        _bild(req, uid)
    elif mode=='key':
        _key(req, uid)
    elif mode=='text':
        _text(req)
    # the following is neccessary for OK return status; see
    # http://www.modpython.org/pipermail/mod_python/2002-August/012852.html
    raise mod_python.apache.SERVER_RETURN, mod_python.apache.OK
    # alternatively:
    #return " "

def _bild(req, uid=None):
    req.content_type="image/jpg"
    if uid==None: return
    all_records=_readLDAPDirectory(uid)
    if len(all_records)<1: return
    entry=all_records[0][1]
    if not entry.has_key('jpegPhoto'): return
    req.write(entry['jpegPhoto'][0])

def _key(req, uid=None):
    req.content_type="text/plain"
    if uid==None: return
    all_records=_readLDAPDirectory(uid)
    if len(all_records)<1: return
    entry=all_records[0][1]
    if not entry.has_key('pgpPublicKey'): return
    req.write(entry['pgpPublicKey'][0])

def _text(req):
    all_records=_readLDAPDirectory('*')
    req.content_type="text/plain; charset=iso-8859-1"
    #Nachname:Vorname:Titel:Stelle:EMail:TelNr:Adresse:RaumNr:\
    #Arbeitsgruppe:Institut:Karteikarte:Bemerkungen:Homepage
    pattern=re.compile(':')
    for p in all_records:
        dn, entry=p
        if not entry.has_key('employeeType'): continue
        # these are the official types
        # we use also "DI" for diplomand etc
        et=entry['employeeType'][0]
        if et != "OP" \
          and et != "EM" \
          and et != "AP" \
          and et != "PD" \
          and et != "AR" \
          and et != "AD" \
          and et != "WA" \
          and et != "WH" \
          and et != "AS" \
          and et != "DO":
            continue
        if entry.has_key('mail'):
            email=entry['mail'][0]
        else:
            email="%s@tphys.physik.uni-tuebingen.de" % entry['uid'][0]
        vcard="%s?uid=%s" % (pattern.sub('\\:',_scripturi),entry['uid'][0])
        uri=entry.get('labeledURI', [''])[0]
        uri=pattern.sub('\\:', uri)
        req.write('%s:%s:%s:%s:%s:%s:Auf der Morgenstelle 14:'\
          '%s:%s:Institut für Theoretische Physik:%s:%s:%s\n'\
          %(entry.get('sn', [''])[0],                   \
            entry.get('givenName', [''])[0],            \
            entry.get('title', [''])[0],                \
            entry.get('employeeType', [''])[0],         \
            email,                                      \
            entry.get('telephoneNumber', [''])[0],      \
            entry.get('roomNumber', [''])[0],           \
            'Theory',                                   \
            vcard,entry.get('desc', [''])[0],           \
            uri))

def _printVCard(req, lang, uid):
    _printHTMLHeader(req)
    all_records=_readLDAPDirectory(uid)
    size=len(all_records)
    if size!=1:
        req.write('    <h3>The user you requested does not exist.</h3>\n')
        req.write('    <a href="javascript:back()">back</a>\n')
        _printHTMLFooter(req)
        return
    p=all_records[0][1]

    req.write("""\
    <center>
      <table cellpadding="10" cellspacing="2" border="0">
        <tr>
          <td valign=top>
            <center>
""")
    if p.has_key('jpegPhoto'):
        req.write("""\
              <img src="?mode=bild&uid=%s" alt="%s">
""" % (uid,p['cn'][0]))
#    else:
#        req.write("No Photo!\n")

    if p.has_key('mail'):
        email=p['mail'][0]
    else:
        email="%s@tphys.physik.uni-tuebingen.de" % p['uid'][0]
    req.write("""\
            </center>
          </td>
          <td VALIGN=MIDDLE>
            <h2>%s</h2>
            <h3>%s %s</h3>
            <table border=0 cellpadding=3>
              <TR><TH align="left">%s</TH><TH align="left">%s</TH></TR>
              <TR><TD align="left">%s</TD><TD align="left">+49 7071 29 %s</TD></TR>
            </table>
            <p>Email:</p>
              <UL>
                <LI><a href="mailto:%s">%s</a>
              </UL>
""" % (p['cn'][0],strings['group'],'Theory',strings['room'],strings['phone'],\
        p['roomNumber'][0],p['telephoneNumber'][0],\
        email,email))
    if p.has_key('labeledURI'):
      req.write("""\
            <p>WWW:</p>
              <UL>
                <LI><A HREF="%s" TARGET="_blank">Homepage</A>
              </UL>
""" % p['labeledURI'][0])
    if p.has_key('pgpPublicKey'):
      req.write("""\
            <p>PGP Public Key:</p>
              <UL>
                <LI><A HREF="?mode=key&uid=%s" TARGET="_blank">available</A>
              </UL>
""" % uid)
    req.write("""\
          </td>
        </tr>
      </table>
    </center>
    <a href="%s" target="_blank">%s</a>
""" % (strings["mainuri"],strings["mainuridesc"]))
    _printHTMLFooter(req)


def _printUsersTable(req, lang):
    _printHTMLHeader(req)
    all_records=_readLDAPDirectory('*')
    req.write('    <table width="90%" border="0" cellspacing="1"'\
        ' cellpadding="3" bgcolor="#cccccc">\n')
    oldcat=''
    for rec in all_records:
        entry=rec[1];
        try: et=entry['employeeType'][0]
        except KeyError: continue
        try:
            if oldcat!=strings[et]:
                oldcat=strings[et]
                _printHeaderLine(req,et)
        except KeyError: continue
        try: name='%s, %s' % (entry['sn'][0], entry.get('givenName',[''])[0])
        except KeyError: continue
        nl='<a href="%s?uid=%s&lang=%s" '\
            'onclick="window.open(this.href, \'popupwindow\','\
            ' \'width=640,height=400,scrollbars=0,resizable\');'\
            ' return false;">%s'\
        % (_scripturi,entry['uid'][0],lang,name)
        if entry.has_key('title'):
            nl+=', %s' % entry.get('title',[''])[0]
        nl+='</a>'
        phone=entry.get('telephoneNumber',[''])[0]
        room=entry.get('roomNumber',[''])[0]
        _printDataLine(req,nl,phone,room)
    req.write('    </table>\n')
    _printHTMLFooter(req)

def _readLDAPDirectory(uid):
    ldap_base='ou=People,dc=tphys,dc=physik,dc=uni-tuebingen,dc=de'
    ldap_filter='(uid=%s)' % uid
    ldif_in, ldif_out, ldif_err=os.popen3("ldapsearch -x  -b %s -LLL '%s'" % (ldap_base, ldap_filter))
    records=_MyLDIFParser(ldif_out)
    records.parse()
    records.all_records.sort(_pplSorter)
    return records.all_records

def _printHeaderLine(req,et):
    req.write("""\
      <tr>
        <th align="left" class="phonelist">%s</th>
        <th align="left" class="phonelist">%s</th>
        <th align="left" class="phonelist">%s</th>
        <th align="left" class="phonelist">%s</th>
      </tr>
""" % (strings[et], strings['name'],strings['phone'],strings['room']))

def _printDataLine(req,nl,phone,room):
    req.write("""\
      <tr>
        <td align="left" class="phonelist"></th>
        <td align="left" class="phonelist">%s</th>
        <td align="left" class="phonelist">%s</th>
        <td align="left" class="phonelist">%s</th>
      </tr>
""" % (nl,phone,room))

def _printHTMLHeader(req):
    req.content_type="text/html; charset=iso-8859-1"
    req.send_http_header()
    req.write("""\
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
  <head>
    <meta name="GENERATOR" content="Epple, Ahlig, Schaefke">
    <title>Adressbuch</title>
    <link REL="stylesheet" HREF="%s/TPstyle.css" TYPE="text/css">
  </head>
  <body class="phonelist">
""" % _stylesdir)

def _printHTMLFooter(req):
    req.write("""\
  </body>
</html>""")

def _pplSorter(a,b):
    cat_a=_categories.get(a[1].get('employeeType',['XX'])[0],1000)
    cat_b=_categories.get(b[1].get('employeeType',['XX'])[0],1000)
    if cat_a!=cat_b: return cmp(cat_a,cat_b)
    elif a[1]['sn'][0]!=b[1]['sn'][0]: return cmp(a[1]['sn'][0],b[1]['sn'][0])
    elif a[1]['givenName'][0]!=b[1]['givenName'][0]: return cmp(a[1]['givenName'][0],b[1]['givenName'][0])
    else: return 0
