Fix for python 2.6: add position indexes to format strings
[mutt-ldap.git] / mutt-ldap.py
index f7159378762e0f55ed009e8923cb0d3a143a6258..7029b60ec2a134a8115e5ae16c6de92d02af008d 100755 (executable)
@@ -54,13 +54,15 @@ CONFIG.add_section('auth')
 CONFIG.set('auth', 'user', '')
 CONFIG.set('auth', 'password', '')
 CONFIG.set('auth', 'gssapi', 'no')
+CONFIG.add_section('query')
+CONFIG.set('query', 'filter', '') # only match entries according to this filter
 CONFIG.read(os.path.expanduser('~/.mutt-ldap.rc'))
 
 def connect():
     protocol = 'ldap'
     if CONFIG.getboolean('connection', 'ssl'):
         protocol = 'ldaps'
-    url = '{}://{}:{}'.format(
+    url = '{0}://{1}:{2}'.format(
         protocol,
         CONFIG.get('connection', 'server'),
         CONFIG.get('connection', 'port'))
@@ -86,9 +88,12 @@ def search(query, connection=None):
         post = ''
         if query:
             post = '*'
-        filterstr = u'(|{})'.format(
-            u' '.join([u'({}=*{}{})'.format(field, query, post)
+        filterstr = u'(|{0})'.format(
+            u' '.join([u'({0}=*{1}{2})'.format(field, query, post)
                        for field in ['cn', 'displayName', 'uid', 'mail']]))
+        query_filter = CONFIG.get('query', 'filter')
+        if query_filter:
+            filterstr = u'(&({0}){1})'.format(query_filter, filterstr)
         r = connection.search_s(
             CONFIG.get('connection', 'basedn'),
             ldap.SCOPE_SUBTREE,
@@ -103,7 +108,9 @@ def format_entry(entry):
     if 'mail' in data:
         name = data.get('displayName', data['cn'])[-1]
         for m in data['mail']:
-            yield email.utils.formataddr((name, m))
+            # http://www.mutt.org/doc/manual/manual-4.html#ss4.5
+            # Describes the format mutt expects: address\tname
+            yield "\t".join([m, name])
 
 
 if __name__ == '__main__':
@@ -113,5 +120,5 @@ if __name__ == '__main__':
     entries = search(query)
     addresses = list(itertools.chain(
             *[format_entry(e) for e in sorted(entries)]))
-    print('{} addresses found:'.format(len(addresses)))
+    print('{0} addresses found:'.format(len(addresses)))
     print('\n'.join(addresses))