fix collect_sub_objects
[matthijs/upstream/django-ldapdb.git] / ldapdb / models / base.py
1 # -*- coding: utf-8 -*-
2
3 # django-ldapdb
4 # Copyright (c) 2009-2010, BollorĂ© telecom
5 # All rights reserved.
6
7 # See AUTHORS file for a full list of contributors.
8
9 # Redistribution and use in source and binary forms, with or without modification,
10 # are permitted provided that the following conditions are met:
11
12 #     1. Redistributions of source code must retain the above copyright notice, 
13 #        this list of conditions and the following disclaimer.
14 #     
15 #     2. Redistributions in binary form must reproduce the above copyright 
16 #        notice, this list of conditions and the following disclaimer in the
17 #        documentation and/or other materials provided with the distribution.
18
19 #     3. Neither the name of BollorĂ© telecom nor the names of its contributors
20 #        may be used to endorse or promote products derived from this software
21 #        without specific prior written permission.
22
23 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
24 # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
25 # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
26 # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
27 # ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
28 # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
29 # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
30 # ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
31 # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
32 # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
33 #
34
35 import ldap
36 import logging
37
38 import django.db.models
39 from django.db.models import signals
40
41 import ldapdb
42 from ldapdb.models.query import QuerySet
43
44 class ModelBase(django.db.models.base.ModelBase):
45     """
46     Metaclass for all LDAP models.
47     """
48     def __new__(cls, name, bases, attrs):
49         super_new = super(ModelBase, cls).__new__
50         new_class = super_new(cls, name, bases, attrs)
51
52         # patch manager to use our own QuerySet class
53         if not new_class._meta.abstract:
54             def get_query_set():
55                 return QuerySet(new_class)
56             new_class.objects.get_query_set = get_query_set
57             new_class._default_manager.get_query_set = get_query_set
58
59         return new_class
60
61 class Model(django.db.models.base.Model):
62     """
63     Base class for all LDAP models.
64     """
65     __metaclass__ = ModelBase
66
67     dn = django.db.models.fields.CharField(max_length=200)
68
69     # meta-data
70     base_dn = None
71     search_scope = ldap.SCOPE_SUBTREE
72     object_classes = ['top']
73
74     def __init__(self, *args, **kwargs):
75         super(Model, self).__init__(*args, **kwargs)
76         self.saved_pk = self.pk
77
78     def _collect_sub_objects(self, seen_objs, parent=None, nullable=False):
79         """
80         This private API seems to be called by the admin interface in django 1.2
81         """
82         pk_val = self._get_pk_val()
83         seen_objs.add(self.__class__, pk_val, self,
84                       type(parent), parent, nullable)
85
86     def build_rdn(self):
87         """
88         Build the Relative Distinguished Name for this entry.
89         """
90         bits = []
91         for field in self._meta.fields:
92             if field.db_column and field.primary_key:
93                 bits.append("%s=%s" % (field.db_column, getattr(self, field.name)))
94         if not len(bits):
95             raise Exception("Could not build Distinguished Name")
96         return '+'.join(bits)
97
98     def build_dn(self):
99         """
100         Build the Distinguished Name for this entry.
101         """
102         return "%s,%s" % (self.build_rdn(), self.base_dn)
103         raise Exception("Could not build Distinguished Name")
104
105     def delete(self):
106         """
107         Delete this entry.
108         """
109         logging.debug("Deleting LDAP entry %s" % self.dn)
110         ldapdb.connection.delete_s(self.dn)
111         signals.post_delete.send(sender=self.__class__, instance=self)
112         
113     def save(self):
114         if not self.dn:
115             # create a new entry
116             record_exists = False 
117             entry = [('objectClass', self.object_classes)]
118             new_dn = self.build_dn()
119
120             for field in self._meta.fields:
121                 if not field.db_column:
122                     continue
123                 value = getattr(self, field.name)
124                 if value:
125                     entry.append((field.db_column, field.get_db_prep_save(value, connection=ldapdb.connection)))
126
127             logging.debug("Creating new LDAP entry %s" % new_dn)
128             ldapdb.connection.add_s(new_dn, entry)
129
130             # update object
131             self.dn = new_dn
132
133         else:
134             # update an existing entry
135             record_exists = True
136             modlist = []
137             orig = self.__class__.objects.get(pk=self.saved_pk)
138             for field in self._meta.fields:
139                 if not field.db_column:
140                     continue
141                 old_value = getattr(orig, field.name, None)
142                 new_value = getattr(self, field.name, None)
143                 if old_value != new_value:
144                     if new_value:
145                         modlist.append((ldap.MOD_REPLACE, field.db_column, field.get_db_prep_save(new_value, connection=ldapdb.connection)))
146                     elif old_value:
147                         modlist.append((ldap.MOD_DELETE, field.db_column, None))
148
149             if len(modlist):
150                 # handle renaming
151                 new_dn = self.build_dn()
152                 if new_dn != self.dn:
153                     logging.debug("Renaming LDAP entry %s to %s" % (self.dn, new_dn))
154                     ldapdb.connection.rename_s(self.dn, self.build_rdn())
155                     self.dn = new_dn
156             
157                 logging.debug("Modifying existing LDAP entry %s" % self.dn)
158                 ldapdb.connection.modify_s(self.dn, modlist)
159             else:
160                 logging.debug("No changes to be saved to LDAP entry %s" % self.dn)
161
162         # done
163         self.saved_pk = self.pk
164         signals.post_save.send(sender=self.__class__, instance=self, created=(not record_exists))
165
166     @classmethod
167     def scoped(base_class, base_dn):
168         """
169         Returns a copy of the current class with a different base_dn.
170         """
171         import new
172         import re
173         suffix = re.sub('[=,]', '_', base_dn)
174         name = "%s_%s" % (base_class.__name__, str(suffix))
175         new_class = new.classobj(name, (base_class,), {'base_dn': base_dn, '__module__': base_class.__module__})
176         return new_class
177