##############################################################################
# -*- coding: utf-8 -*-
# Project:      EnciendeEquipos
# Module:    	LdapConnection.py
# Purpose:     	Anonymous Connection with ldap server
# Language:    	Python 2.5
# Date:        	23-Feb-2011.
# Ver:         	23-Feb-2011.
# Author:    	Francisco Mendez Palma
# Copyright:    2011 - Francisco Mendez Palma <fmendezpalma @no-spam@ gmail.com>
#
# EnciendeEquipos is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# EnciendeEquipos is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
##############################################################################

import ldap

class LdapConnection(object):

    def __init__(self,host):
		self.host = host

    def connect(self):
		## first you must open a connection to the server
		
		try:
			self.connect=ldap.open(self.host)
			## searching doesn't require a bind in LDAP V3.  If you're using LDAP v2, set the next line appropriately
			## and do a bind as shown in the above example.
			# you can also set this to ldap.VERSION2 if you're using a v2 directory
			# you should  set the next option to ldap.VERSION2 if you're using a v2 directory
			self.protocol_version = ldap.VERSION3
		except ldap.LDAPError, e:
			return False
			# handle error however you like
			
		return True

    def search(self,baseDN,filter,retrieveAttributes):
		
		try:
			ldap_result_id = self.connect.search(baseDN+",dc=instituto,dc=extremadura,dc=es", ldap.SCOPE_SUBTREE, filter, retrieveAttributes)
			result_set = []
			while 1:
				result_type, result_data = self.connect.result(ldap_result_id, 0)
				if (result_data == []):
					break
				else:
					if result_type == ldap.RES_SEARCH_ENTRY:
						result_set.append(result_data)
			return result_set
		except ldap.LDAPError, e:
			print e
