root / pykota / trunk / pykota / storages / ldapstorage.py @ 1179

Revision 1179, 38.7 kB (checked in by jalet, 21 years ago)

Bug fix wrt no user/group name command line argument to edpykota

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
Line 
1# PyKota
2# -*- coding: ISO-8859-15 -*-
3#
4# PyKota : Print Quotas for CUPS and LPRng
5#
6# (c) 2003 Jerome Alet <alet@librelogiciel.com>
7# This program is free software; you can redistribute it and/or modify
8# it under the terms of the GNU General Public License as published by
9# the Free Software Foundation; either version 2 of the License, or
10# (at your option) any later version.
11#
12# This program is distributed in the hope that it will be useful,
13# but WITHOUT ANY WARRANTY; without even the implied warranty of
14# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15# GNU General Public License for more details.
16#
17# You should have received a copy of the GNU General Public License
18# along with this program; if not, write to the Free Software
19# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
20#
21# $Id$
22#
23# $Log$
24# Revision 1.35  2003/11/12 13:06:37  jalet
25# Bug fix wrt no user/group name command line argument to edpykota
26#
27# Revision 1.34  2003/10/24 08:37:55  jalet
28# More complete messages in case of LDAP failure.
29# LDAP database connection is now unbound on exit too.
30#
31# Revision 1.33  2003/10/08 07:01:20  jalet
32# Job history can be disabled.
33# Some typos in README.
34# More messages in setup script.
35#
36# Revision 1.32  2003/10/07 14:23:25  jalet
37# More work on cache
38#
39# Revision 1.31  2003/10/07 09:07:30  jalet
40# Character encoding added to please latest version of Python
41#
42# Revision 1.30  2003/10/06 14:42:36  jalet
43# LDAP group access will be slower when cache is disabled, but at least code
44# is consistent with the rest of the caching mechanis, but at least code
45# is consistent with the rest of the caching mechanism
46#
47# Revision 1.29  2003/10/06 13:12:28  jalet
48# More work on caching
49#
50# Revision 1.28  2003/10/03 12:27:02  jalet
51# Several optimizations, especially with LDAP backend
52#
53# Revision 1.27  2003/10/03 08:57:55  jalet
54# Caching mechanism now caches all that's cacheable.
55#
56# Revision 1.26  2003/10/02 20:23:18  jalet
57# Storage caching mechanism added.
58#
59# Revision 1.25  2003/08/20 15:56:24  jalet
60# Better user and group deletion
61#
62# Revision 1.24  2003/07/29 20:55:17  jalet
63# 1.14 is out !
64#
65# Revision 1.23  2003/07/29 19:52:32  jalet
66# Forgot to read the email field from LDAP
67#
68# Revision 1.22  2003/07/29 09:54:03  jalet
69# Added configurable LDAP mail attribute support
70#
71# Revision 1.21  2003/07/28 09:11:12  jalet
72# PyKota now tries to add its attributes intelligently in existing LDAP
73# directories.
74#
75# Revision 1.20  2003/07/25 10:41:30  jalet
76# Better documentation.
77# pykotme now displays the current user's account balance.
78# Some test changed in ldap module.
79#
80# Revision 1.19  2003/07/14 14:18:16  jalet
81# Wrong documentation strings
82#
83# Revision 1.18  2003/07/11 14:23:13  jalet
84# When adding an user only adds one object containing both the user and
85# its account balance instead of two objects.
86#
87# Revision 1.17  2003/07/07 12:51:07  jalet
88# Small fix
89#
90# Revision 1.16  2003/07/07 12:11:13  jalet
91# Small fix
92#
93# Revision 1.15  2003/07/07 11:49:24  jalet
94# Lots of small fixes with the help of PyChecker
95#
96# Revision 1.14  2003/07/07 08:33:18  jalet
97# Bug fix due to a typo in LDAP code
98#
99# Revision 1.13  2003/07/05 07:46:50  jalet
100# The previous bug fix was incomplete.
101#
102# Revision 1.12  2003/06/30 13:54:21  jalet
103# Sorts by user / group name
104#
105# Revision 1.11  2003/06/25 14:10:01  jalet
106# Hey, it may work (edpykota --reset excepted) !
107#
108# Revision 1.10  2003/06/16 21:55:15  jalet
109# More work on LDAP, again. Problem detected.
110#
111# Revision 1.9  2003/06/16 11:59:09  jalet
112# More work on LDAP
113#
114# Revision 1.8  2003/06/15 22:26:52  jalet
115# More work on LDAP
116#
117# Revision 1.7  2003/06/14 22:44:21  jalet
118# More work on LDAP storage backend.
119#
120# Revision 1.6  2003/06/13 19:07:57  jalet
121# Two big bugs fixed, time to release something ;-)
122#
123# Revision 1.5  2003/06/10 16:37:54  jalet
124# Deletion of the second user which is not needed anymore.
125# Added a debug configuration field in /etc/pykota.conf
126# All queries can now be sent to the logger in debug mode, this will
127# greatly help improve performance when time for this will come.
128#
129# Revision 1.4  2003/06/10 10:45:32  jalet
130# Not implemented methods now raise an exception when called.
131#
132# Revision 1.3  2003/06/06 20:49:15  jalet
133# Very latest schema. UNTESTED.
134#
135# Revision 1.2  2003/06/06 14:21:08  jalet
136# New LDAP schema.
137# Small bug fixes.
138#
139# Revision 1.1  2003/06/05 11:19:13  jalet
140# More good work on LDAP storage.
141#
142#
143#
144
145#
146# My IANA assigned number, for
147# "Conseil Internet & Logiciels Libres, J�me Alet"
148# is 16868. Use this as a base to create the LDAP schema.
149#
150
151import time
152import md5
153
154from pykota.storage import PyKotaStorageError,BaseStorage,StorageObject,StorageUser,StorageGroup,StoragePrinter,StorageLastJob,StorageUserPQuota,StorageGroupPQuota
155
156try :
157    import ldap
158    from ldap import modlist
159except ImportError :   
160    import sys
161    # TODO : to translate or not to translate ?
162    raise PyKotaStorageError, "This python version (%s) doesn't seem to have the python-ldap module installed correctly." % sys.version.split()[0]
163   
164class Storage(BaseStorage) :
165    def __init__(self, pykotatool, host, dbname, user, passwd) :
166        """Opens the LDAP connection."""
167        # raise PyKotaStorageError, "Sorry, the LDAP backend for PyKota is not yet implemented !"
168        BaseStorage.__init__(self, pykotatool)
169        self.info = pykotatool.config.getLDAPInfo()
170        try :
171            self.database = ldap.initialize(host) 
172            self.database.simple_bind_s(user, passwd)
173            self.basedn = dbname
174        except ldap.SERVER_DOWN :   
175            raise PyKotaStorageError, "LDAP backend for PyKota seems to be down !" # TODO : translate
176        except ldap.LDAPError :   
177            raise PyKotaStorageError, "Unable to connect to LDAP server %s as %s." % (host, user) # TODO : translate
178        else :   
179            self.closed = 0
180            self.tool.logdebug("Database opened (host=%s, dbname=%s, user=%s)" % (host, dbname, user))
181           
182    def close(self) :   
183        """Closes the database connection."""
184        if not self.closed :
185            self.database.unbind_s()
186            self.closed = 1
187            self.tool.logdebug("Database closed.")
188       
189    def genUUID(self) :   
190        """Generates an unique identifier.
191       
192           TODO : this one is not unique accross several print servers, but should be sufficient for testing.
193        """
194        return md5.md5("%s" % time.time()).hexdigest()
195       
196    def beginTransaction(self) :   
197        """Starts a transaction."""
198        self.tool.logdebug("Transaction begins... WARNING : No transactions in LDAP !")
199       
200    def commitTransaction(self) :   
201        """Commits a transaction."""
202        self.tool.logdebug("Transaction committed. WARNING : No transactions in LDAP !")
203       
204    def rollbackTransaction(self) :     
205        """Rollbacks a transaction."""
206        self.tool.logdebug("Transaction aborted. WARNING : No transaction in LDAP !")
207       
208    def doSearch(self, key, fields=None, base="", scope=ldap.SCOPE_SUBTREE) :
209        """Does an LDAP search query."""
210        try :
211            base = base or self.basedn
212            self.tool.logdebug("QUERY : Filter : %s, BaseDN : %s, Scope : %s, Attributes : %s" % (key, base, scope, fields))
213            result = self.database.search_s(base or self.basedn, scope, key, fields)
214        except ldap.LDAPError, msg :   
215            raise PyKotaStorageError, (_("Search for %s(%s) from %s(scope=%s) returned no answer.") % (key, fields, base, scope)) + " : %s" % str(msg)
216        else :     
217            self.tool.logdebug("QUERY : Result : %s" % result)
218            return result
219           
220    def doAdd(self, dn, fields) :
221        """Adds an entry in the LDAP directory."""
222        try :
223            self.tool.logdebug("QUERY : ADD(%s, %s)" % (dn, str(fields)))
224            self.database.add_s(dn, modlist.addModlist(fields))
225        except ldap.LDAPError, msg :
226            raise PyKotaStorageError, (_("Problem adding LDAP entry (%s, %s)") % (dn, str(fields))) + " : %s" % str(msg)
227        else :
228            return dn
229           
230    def doDelete(self, dn) :
231        """Deletes an entry from the LDAP directory."""
232        try :
233            self.tool.logdebug("QUERY : Delete(%s)" % dn)
234            self.database.delete_s(dn)
235        except ldap.LDAPError, msg :
236            raise PyKotaStorageError, (_("Problem deleting LDAP entry (%s)") % dn) + " : %s" % str(msg)
237           
238    def doModify(self, dn, fields, ignoreold=1) :
239        """Modifies an entry in the LDAP directory."""
240        try :
241            oldentry = self.doSearch("objectClass=*", base=dn, scope=ldap.SCOPE_BASE)
242            self.tool.logdebug("QUERY : Modify(%s, %s ==> %s)" % (dn, oldentry[0][1], fields))
243            self.database.modify_s(dn, modlist.modifyModlist(oldentry[0][1], fields, ignore_oldexistent=ignoreold))
244        except ldap.LDAPError, msg :
245            raise PyKotaStorageError, (_("Problem modifying LDAP entry (%s, %s)") % (dn, fields)) + " : %s" % str(msg)
246        else :
247            return dn
248           
249    def getAllUsersNames(self) :   
250        """Extracts all user names."""
251        usernames = []
252        result = self.doSearch("objectClass=pykotaAccount", ["pykotaUserName"], base=self.info["userbase"])
253        if result :
254            usernames = [record[1]["pykotaUserName"][0] for record in result]
255        return usernames
256       
257    def getAllGroupsNames(self) :   
258        """Extracts all group names."""
259        groupnames = []
260        result = self.doSearch("objectClass=pykotaGroup", ["pykotaGroupName"], base=self.info["groupbase"])
261        if result :
262            groupnames = [record[1]["pykotaGroupName"][0] for record in result]
263        return groupnames
264       
265    def getUserFromBackend(self, username) :   
266        """Extracts user information given its name."""
267        user = StorageUser(self, username)
268        result = self.doSearch("(&(objectClass=pykotaAccount)(|(pykotaUserName=%s)(%s=%s)))" % (username, self.info["userrdn"], username), ["pykotaLimitBy", self.info["usermail"]], base=self.info["userbase"])
269        if result :
270            fields = result[0][1]
271            user.ident = result[0][0]
272            user.Email = fields.get(self.info["usermail"])
273            if user.Email is not None :
274                user.Email = user.Email[0]
275            user.LimitBy = fields.get("pykotaLimitBy")
276            if user.LimitBy is not None :
277                user.LimitBy = user.LimitBy[0]
278            result = self.doSearch("(&(objectClass=pykotaAccountBalance)(|(pykotaUserName=%s)(%s=%s)))" % (username, self.info["balancerdn"], username), ["pykotaBalance", "pykotaLifeTimePaid"], base=self.info["balancebase"])
279            if result :
280                fields = result[0][1]
281                user.idbalance = result[0][0]
282                user.AccountBalance = fields.get("pykotaBalance")
283                if user.AccountBalance is not None :
284                    if user.AccountBalance[0].upper() == "NONE" :
285                        user.AccountBalance = None
286                    else :   
287                        user.AccountBalance = float(user.AccountBalance[0])
288                user.AccountBalance = user.AccountBalance or 0.0       
289                user.LifeTimePaid = fields.get("pykotaLifeTimePaid")
290                if user.LifeTimePaid is not None :
291                    if user.LifeTimePaid[0].upper() == "NONE" :
292                        user.LifeTimePaid = None
293                    else :   
294                        user.LifeTimePaid = float(user.LifeTimePaid[0])
295                user.LifeTimePaid = user.LifeTimePaid or 0.0       
296            user.Exists = 1
297        return user
298       
299    def getGroupFromBackend(self, groupname) :   
300        """Extracts group information given its name."""
301        group = StorageGroup(self, groupname)
302        result = self.doSearch("(&(objectClass=pykotaGroup)(|(pykotaGroupName=%s)(%s=%s)))" % (groupname, self.info["grouprdn"], groupname), ["pykotaLimitBy"], base=self.info["groupbase"])
303        if result :
304            fields = result[0][1]
305            group.ident = result[0][0]
306            group.LimitBy = fields.get("pykotaLimitBy")
307            if group.LimitBy is not None :
308                group.LimitBy = group.LimitBy[0]
309            group.AccountBalance = 0.0
310            group.LifeTimePaid = 0.0
311            for member in self.getGroupMembers(group) :
312                if member.Exists :
313                    group.AccountBalance += member.AccountBalance
314                    group.LifeTimePaid += member.LifeTimePaid
315            group.Exists = 1
316        return group
317       
318    def getPrinterFromBackend(self, printername) :       
319        """Extracts printer information given its name."""
320        printer = StoragePrinter(self, printername)
321        result = self.doSearch("(&(objectClass=pykotaPrinter)(|(pykotaPrinterName=%s)(%s=%s)))" % (printername, self.info["printerrdn"], printername), ["pykotaPricePerPage", "pykotaPricePerJob"], base=self.info["printerbase"])
322        if result :
323            fields = result[0][1]
324            printer.ident = result[0][0]
325            printer.PricePerJob = float(fields.get("pykotaPricePerJob")[0] or 0.0)
326            printer.PricePerPage = float(fields.get("pykotaPricePerPage")[0] or 0.0)
327            printer.LastJob = self.getPrinterLastJob(printer)
328            printer.Exists = 1
329        return printer   
330       
331    def getUserPQuotaFromBackend(self, user, printer) :       
332        """Extracts a user print quota."""
333        userpquota = StorageUserPQuota(self, user, printer)
334        if user.Exists :
335            result = self.doSearch("(&(objectClass=pykotaUserPQuota)(pykotaUserName=%s)(pykotaPrinterName=%s))" % (user.Name, printer.Name), ["pykotaPageCounter", "pykotaLifePageCounter", "pykotaSoftLimit", "pykotaHardLimit", "pykotaDateLimit"], base=self.info["userquotabase"])
336            if result :
337                fields = result[0][1]
338                userpquota.ident = result[0][0]
339                userpquota.PageCounter = int(fields.get("pykotaPageCounter")[0] or 0)
340                userpquota.LifePageCounter = int(fields.get("pykotaLifePageCounter")[0] or 0)
341                userpquota.SoftLimit = fields.get("pykotaSoftLimit")
342                if userpquota.SoftLimit is not None :
343                    if userpquota.SoftLimit[0].upper() == "NONE" :
344                        userpquota.SoftLimit = None
345                    else :   
346                        userpquota.SoftLimit = int(userpquota.SoftLimit[0])
347                userpquota.HardLimit = fields.get("pykotaHardLimit")
348                if userpquota.HardLimit is not None :
349                    if userpquota.HardLimit[0].upper() == "NONE" :
350                        userpquota.HardLimit = None
351                    elif userpquota.HardLimit is not None :   
352                        userpquota.HardLimit = int(userpquota.HardLimit[0])
353                userpquota.DateLimit = fields.get("pykotaDateLimit")
354                if userpquota.DateLimit is not None :
355                    if userpquota.DateLimit[0].upper() == "NONE" : 
356                        userpquota.DateLimit = None
357                    else :   
358                        userpquota.DateLimit = userpquota.DateLimit[0]
359                userpquota.Exists = 1
360        return userpquota
361       
362    def getGroupPQuotaFromBackend(self, group, printer) :       
363        """Extracts a group print quota."""
364        grouppquota = StorageGroupPQuota(self, group, printer)
365        if group.Exists :
366            result = self.doSearch("(&(objectClass=pykotaGroupPQuota)(pykotaGroupName=%s)(pykotaPrinterName=%s))" % (group.Name, printer.Name), ["pykotaSoftLimit", "pykotaHardLimit", "pykotaDateLimit"], base=self.info["groupquotabase"])
367            if result :
368                fields = result[0][1]
369                grouppquota.ident = result[0][0]
370                grouppquota.SoftLimit = fields.get("pykotaSoftLimit")
371                if grouppquota.SoftLimit is not None :
372                    if grouppquota.SoftLimit[0].upper() == "NONE" :
373                        grouppquota.SoftLimit = None
374                    else :   
375                        grouppquota.SoftLimit = int(grouppquota.SoftLimit[0])
376                grouppquota.HardLimit = fields.get("pykotaHardLimit")
377                if grouppquota.HardLimit is not None :
378                    if grouppquota.HardLimit[0].upper() == "NONE" :
379                        grouppquota.HardLimit = None
380                    else :   
381                        grouppquota.HardLimit = int(grouppquota.HardLimit[0])
382                grouppquota.DateLimit = fields.get("pykotaDateLimit")
383                if grouppquota.DateLimit is not None :
384                    if grouppquota.DateLimit[0].upper() == "NONE" : 
385                        grouppquota.DateLimit = None
386                    else :   
387                        grouppquota.DateLimit = grouppquota.DateLimit[0]
388                grouppquota.PageCounter = 0
389                grouppquota.LifePageCounter = 0
390                usernamesfilter = "".join(["(pykotaUserName=%s)" % member.Name for member in self.getGroupMembers(group)])
391                result = self.doSearch("(&(objectClass=pykotaUserPQuota)(pykotaPrinterName=%s)(|%s))" % (printer.Name, usernamesfilter), ["pykotaPageCounter", "pykotaLifePageCounter"], base=self.info["userquotabase"])
392                if result :
393                    for userpquota in result :   
394                        grouppquota.PageCounter += int(userpquota[1].get("pykotaPageCounter")[0] or 0)
395                        grouppquota.LifePageCounter += int(userpquota[1].get("pykotaLifePageCounter")[0] or 0)
396                grouppquota.Exists = 1
397        return grouppquota
398       
399    def getPrinterLastJobFromBackend(self, printer) :       
400        """Extracts a printer's last job information."""
401        lastjob = StorageLastJob(self, printer)
402        result = self.doSearch("(&(objectClass=pykotaLastjob)(|(pykotaPrinterName=%s)(%s=%s)))" % (printer.Name, self.info["printerrdn"], printer.Name), ["pykotaLastJobIdent"], base=self.info["lastjobbase"])
403        if result :
404            lastjob.lastjobident = result[0][0]
405            lastjobident = result[0][1]["pykotaLastJobIdent"][0]
406            result = self.doSearch("objectClass=pykotaJob", ["pykotaUserName", "pykotaJobId", "pykotaPrinterPageCounter", "pykotaJobSize", "pykotaAction", "createTimestamp"], base="cn=%s,%s" % (lastjobident, self.info["jobbase"]), scope=ldap.SCOPE_BASE)
407            if result :
408                fields = result[0][1]
409                lastjob.ident = result[0][0]
410                lastjob.JobId = fields.get("pykotaJobId")[0]
411                lastjob.User = self.getUser(fields.get("pykotaUserName")[0])
412                lastjob.PrinterPageCounter = int(fields.get("pykotaPrinterPageCounter")[0] or 0)
413                lastjob.JobSize = int(fields.get("pykotaJobSize", [0])[0])
414                lastjob.JobAction = fields.get("pykotaAction")[0]
415                date = fields.get("createTimestamp")[0]
416                year = int(date[:4])
417                month = int(date[4:6])
418                day = int(date[6:8])
419                hour = int(date[8:10])
420                minute = int(date[10:12])
421                second = int(date[12:14])
422                lastjob.JobDate = "%04i-%02i-%02i %02i:%02i:%02i" % (year, month, day, hour, minute, second)
423                lastjob.Exists = 1
424        return lastjob
425       
426    def getGroupMembersFromBackend(self, group) :       
427        """Returns the group's members list."""
428        groupmembers = []
429        result = self.doSearch("(&(objectClass=pykotaGroup)(|(pykotaGroupName=%s)(%s=%s)))" % (group.Name, self.info["grouprdn"], group.Name), [self.info["groupmembers"]], base=self.info["groupbase"])
430        if result :
431            for username in result[0][1].get(self.info["groupmembers"], []) :
432                groupmembers.append(self.getUser(username))
433        return groupmembers       
434       
435    def getUserGroupsFromBackend(self, user) :       
436        """Returns the user's groups list."""
437        groups = []
438        result = self.doSearch("(&(objectClass=pykotaGroup)(%s=%s))" % (self.info["groupmembers"], user.Name), [self.info["grouprdn"], "pykotaGroupName", "pykotaLimitBy"], base=self.info["groupbase"])
439        if result :
440            for (groupid, fields) in result :
441                groupname = (fields.get("pykotaGroupName", [None]) or fields.get(self.info["grouprdn"], [None]))[0]
442                group = self.getFromCache("GROUPS", groupname)
443                if group is None :
444                    group = StorageGroup(self, groupname)
445                    group.ident = groupid
446                    group.LimitBy = fields.get("pykotaLimitBy")
447                    if group.LimitBy is not None :
448                        group.LimitBy = group.LimitBy[0]
449                    group.AccountBalance = 0.0
450                    group.LifeTimePaid = 0.0
451                    for member in self.getGroupMembers(group) :
452                        if member.Exists :
453                            group.AccountBalance += member.AccountBalance
454                            group.LifeTimePaid += member.LifeTimePaid
455                    group.Exists = 1
456                    self.cacheEntry("GROUPS", group.Name, group)
457                groups.append(group)
458        return groups       
459       
460    def getMatchingPrinters(self, printerpattern) :
461        """Returns the list of all printers for which name matches a certain pattern."""
462        printers = []
463        # see comment at the same place in pgstorage.py
464        result = self.doSearch("(&(objectClass=pykotaPrinter)(|%s))" % "".join(["(pykotaPrinterName=%s)" % pname for pname in printerpattern.split(",")]), ["pykotaPrinterName", "pykotaPricePerPage", "pykotaPricePerJob"], base=self.info["printerbase"])
465        if result :
466            for (printerid, fields) in result :
467                printername = fields["pykotaPrinterName"][0]
468                printer = StoragePrinter(self, printername)
469                printer.ident = printerid
470                printer.PricePerJob = float(fields.get("pykotaPricePerJob")[0] or 0.0)
471                printer.PricePerPage = float(fields.get("pykotaPricePerPage")[0] or 0.0)
472                printer.LastJob = self.getPrinterLastJob(printer)
473                printer.Exists = 1
474                printers.append(printer)
475                self.cacheEntry("PRINTERS", printer.Name, printer)
476        return printers       
477       
478    def getPrinterUsersAndQuotas(self, printer, names=["*"]) :       
479        """Returns the list of users who uses a given printer, along with their quotas."""
480        usersandquotas = []
481        result = self.doSearch("(&(objectClass=pykotaUserPQuota)(pykotaPrinterName=%s)(|%s))" % (printer.Name, "".join(["(pykotaUserName=%s)" % uname for uname in names])), ["pykotaUserName", "pykotaPageCounter", "pykotaLifePageCounter", "pykotaSoftLimit", "pykotaHardLimit", "pykotaDateLimit"], base=self.info["userquotabase"])
482        if result :
483            for (userquotaid, fields) in result :
484                user = self.getUser(fields.get("pykotaUserName")[0])
485                userpquota = StorageUserPQuota(self, user, printer)
486                userpquota.ident = userquotaid
487                userpquota.PageCounter = int(fields.get("pykotaPageCounter")[0] or 0)
488                userpquota.LifePageCounter = int(fields.get("pykotaLifePageCounter")[0] or 0)
489                userpquota.SoftLimit = fields.get("pykotaSoftLimit")
490                if userpquota.SoftLimit is not None :
491                    if userpquota.SoftLimit[0].upper() == "NONE" :
492                        userpquota.SoftLimit = None
493                    else :   
494                        userpquota.SoftLimit = int(userpquota.SoftLimit[0])
495                userpquota.HardLimit = fields.get("pykotaHardLimit")
496                if userpquota.HardLimit is not None :
497                    if userpquota.HardLimit[0].upper() == "NONE" :
498                        userpquota.HardLimit = None
499                    elif userpquota.HardLimit is not None :   
500                        userpquota.HardLimit = int(userpquota.HardLimit[0])
501                userpquota.DateLimit = fields.get("pykotaDateLimit")
502                if userpquota.DateLimit is not None :
503                    if userpquota.DateLimit[0].upper() == "NONE" : 
504                        userpquota.DateLimit = None
505                    else :   
506                        userpquota.DateLimit = userpquota.DateLimit[0]
507                userpquota.Exists = 1
508                usersandquotas.append((user, userpquota))
509                self.cacheEntry("USERPQUOTAS", "%s@%s" % (user.Name, printer.Name), userpquota)
510        usersandquotas.sort(lambda x, y : cmp(x[0].Name, y[0].Name))           
511        return usersandquotas
512               
513    def getPrinterGroupsAndQuotas(self, printer, names=["*"]) :       
514        """Returns the list of groups which uses a given printer, along with their quotas."""
515        groupsandquotas = []
516        result = self.doSearch("(&(objectClass=pykotaGroupPQuota)(pykotaPrinterName=%s)(|%s))" % (printer.Name, "".join(["(pykotaGroupName=%s)" % gname for gname in names])), ["pykotaGroupName"], base=self.info["groupquotabase"])
517        if result :
518            for (groupquotaid, fields) in result :
519                group = self.getGroup(fields.get("pykotaGroupName")[0])
520                grouppquota = self.getGroupPQuota(group, printer)
521                groupsandquotas.append((group, grouppquota))
522        groupsandquotas.sort(lambda x, y : cmp(x[0].Name, y[0].Name))           
523        return groupsandquotas
524       
525    def addPrinter(self, printername) :       
526        """Adds a printer to the quota storage, returns it."""
527        fields = { self.info["printerrdn"] : printername,
528                   "objectClass" : ["pykotaObject", "pykotaPrinter"],
529                   "cn" : printername,
530                   "pykotaPrinterName" : printername,
531                   "pykotaPricePerPage" : "0.0",
532                   "pykotaPricePerJob" : "0.0",
533                 } 
534        dn = "%s=%s,%s" % (self.info["printerrdn"], printername, self.info["printerbase"])
535        self.doAdd(dn, fields)
536        return self.getPrinter(printername)
537       
538    def addUser(self, user) :       
539        """Adds a user to the quota storage, returns it."""
540        newfields = {
541                       "pykotaUserName" : user.Name,
542                       "pykotaLimitBY" : (user.LimitBy or "quota"),
543                       "pykotaBalance" : str(user.AccountBalance or 0.0),
544                       "pykotaLifeTimePaid" : str(user.LifeTimePaid or 0.0),
545                    }   
546        mustadd = 1
547        if self.info["newuser"].lower() != 'below' :
548            result = self.doSearch("(&(objectClass=%s)(%s=%s))" % (self.info["newuser"], self.info["userrdn"], user.Name), None, base=self.info["userbase"])
549            if result :
550                (dn, fields) = result[0]
551                fields["objectClass"].extend(["pykotaAccount", "pykotaAccountBalance"])
552                fields.update(newfields)
553                self.doModify(dn, fields)
554                mustadd = 0
555               
556        if mustadd :
557            fields = { self.info["userrdn"] : user.Name,
558                       "objectClass" : ["pykotaObject", "pykotaAccount", "pykotaAccountBalance"],
559                       "cn" : user.Name,
560                     } 
561            fields.update(newfields)         
562            dn = "%s=%s,%s" % (self.info["userrdn"], user.Name, self.info["userbase"])
563            self.doAdd(dn, fields)
564        return self.getUser(user.Name)
565       
566    def addGroup(self, group) :       
567        """Adds a group to the quota storage, returns it."""
568        newfields = { 
569                      "pykotaGroupName" : group.Name,
570                      "pykotaLimitBY" : (group.LimitBy or "quota"),
571                    } 
572        mustadd = 1
573        if self.info["newgroup"].lower() != 'below' :
574            result = self.doSearch("(&(objectClass=%s)(%s=%s))" % (self.info["newgroup"], self.info["grouprdn"], group.Name), None, base=self.info["groupbase"])
575            if result :
576                (dn, fields) = result[0]
577                fields["objectClass"].extend(["pykotaGroup"])
578                fields.update(newfields)
579                self.doModify(dn, fields)
580                mustadd = 0
581               
582        if mustadd :
583            fields = { self.info["grouprdn"] : group.Name,
584                       "objectClass" : ["pykotaObject", "pykotaGroup"],
585                       "cn" : group.Name,
586                     } 
587            fields.update(newfields)         
588            dn = "%s=%s,%s" % (self.info["grouprdn"], group.Name, self.info["groupbase"])
589            self.doAdd(dn, fields)
590        return self.getGroup(group.Name)
591       
592    def addUserToGroup(self, user, group) :   
593        """Adds an user to a group."""
594        if user.Name not in [u.Name for u in self.getGroupMembers(group)] :
595            result = self.doSearch("objectClass=pykotaGroup", None, base=group.ident, scope=ldap.SCOPE_BASE)   
596            if result :
597                fields = result[0][1]
598                if not fields.has_key(self.info["groupmembers"]) :
599                    fields[self.info["groupmembers"]] = []
600                fields[self.info["groupmembers"]].append(user.Name)
601                self.doModify(group.ident, fields)
602                group.Members.append(user)
603               
604    def addUserPQuota(self, user, printer) :
605        """Initializes a user print quota on a printer."""
606        uuid = self.genUUID()
607        fields = { "cn" : uuid,
608                   "objectClass" : ["pykotaObject", "pykotaUserPQuota"],
609                   "pykotaUserName" : user.Name,
610                   "pykotaPrinterName" : printer.Name,
611                   "pykotaDateLimit" : "None",
612                   "pykotaPageCounter" : "0",
613                   "pykotaLifePageCounter" : "0",
614                 } 
615        dn = "cn=%s,%s" % (uuid, self.info["userquotabase"])
616        self.doAdd(dn, fields)
617        return self.getUserPQuota(user, printer)
618       
619    def addGroupPQuota(self, group, printer) :
620        """Initializes a group print quota on a printer."""
621        uuid = self.genUUID()
622        fields = { "cn" : uuid,
623                   "objectClass" : ["pykotaObject", "pykotaGroupPQuota"],
624                   "pykotaGroupName" : group.Name,
625                   "pykotaPrinterName" : printer.Name,
626                   "pykotaDateLimit" : "None",
627                 } 
628        dn = "cn=%s,%s" % (uuid, self.info["groupquotabase"])
629        self.doAdd(dn, fields)
630        return self.getGroupPQuota(group, printer)
631       
632    def writePrinterPrices(self, printer) :   
633        """Write the printer's prices back into the storage."""
634        fields = {
635                   "pykotaPricePerPage" : str(printer.PricePerPage),
636                   "pykotaPricePerJob" : str(printer.PricePerJob),
637                 }
638        self.doModify(printer.ident, fields)
639       
640    def writeUserLimitBy(self, user, limitby) :   
641        """Sets the user's limiting factor."""
642        fields = {
643                   "pykotaLimitBy" : limitby,
644                 }
645        self.doModify(user.ident, fields)         
646       
647    def writeGroupLimitBy(self, group, limitby) :   
648        """Sets the group's limiting factor."""
649        fields = {
650                   "pykotaLimitBy" : limitby,
651                 }
652        self.doModify(group.ident, fields)         
653       
654    def writeUserPQuotaDateLimit(self, userpquota, datelimit) :   
655        """Sets the date limit permanently for a user print quota."""
656        fields = {
657                   "pykotaDateLimit" : "%04i-%02i-%02i %02i:%02i:%02i" % (datelimit.year, datelimit.month, datelimit.day, datelimit.hour, datelimit.minute, datelimit.second),
658                 }
659        return self.doModify(userpquota.ident, fields)
660           
661    def writeGroupPQuotaDateLimit(self, grouppquota, datelimit) :   
662        """Sets the date limit permanently for a group print quota."""
663        fields = {
664                   "pykotaDateLimit" : "%04i-%02i-%02i %02i:%02i:%02i" % (datelimit.year, datelimit.month, datelimit.day, datelimit.hour, datelimit.minute, datelimit.second),
665                 }
666        return self.doModify(grouppquota.ident, fields)
667       
668    def writeUserPQuotaPagesCounters(self, userpquota, newpagecounter, newlifepagecounter) :   
669        """Sets the new page counters permanently for a user print quota."""
670        fields = {
671                   "pykotaPageCounter" : str(newpagecounter),
672                   "pykotaLifePageCounter" : str(newlifepagecounter),
673                 } 
674        return self.doModify(userpquota.ident, fields)         
675       
676    def writeUserAccountBalance(self, user, newbalance, newlifetimepaid=None) :   
677        """Sets the new account balance and eventually new lifetime paid."""
678        fields = {
679                   "pykotaBalance" : str(newbalance),
680                 }
681        if newlifetimepaid is not None :
682            fields.update({ "pykotaLifeTimePaid" : str(newlifetimepaid) })
683        return self.doModify(user.idbalance, fields)         
684           
685    def writeLastJobSize(self, lastjob, jobsize) :       
686        """Sets the last job's size permanently."""
687        fields = {
688                   "pykotaJobSize" : str(jobsize),
689                 }
690        self.doModify(lastjob.ident, fields)         
691       
692    def writeJobNew(self, printer, user, jobid, pagecounter, action, jobsize=None) :   
693        """Adds a job in a printer's history."""
694        if (not self.disablehistory) or (not printer.LastJob.Exists) :
695            uuid = self.genUUID()
696            dn = "cn=%s,%s" % (uuid, self.info["jobbase"])
697        else :   
698            uuid = printer.LastJob.ident[3:].split(",")[0]
699            dn = printer.LastJob.ident
700        fields = {
701                   "objectClass" : ["pykotaObject", "pykotaJob"],
702                   "cn" : uuid,
703                   "pykotaUserName" : user.Name,
704                   "pykotaPrinterName" : printer.Name,
705                   "pykotaJobId" : jobid,
706                   "pykotaPrinterPageCounter" : str(pagecounter),
707                   "pykotaAction" : action,
708                 }
709        if (not self.disablehistory) or (not printer.LastJob.Exists) :
710            if jobsize is not None :         
711                fields.update({ "pykotaJobSize" : str(jobsize) })
712            self.doAdd(dn, fields)
713        else :   
714            # here we explicitly want to reset jobsize to 'None' if needed
715            fields.update({ "pykotaJobSize" : str(jobsize) })
716            self.doModify(dn, fields)
717           
718        if printer.LastJob.Exists :
719            fields = {
720                       "pykotaLastJobIdent" : uuid,
721                     }
722            self.doModify(printer.LastJob.lastjobident, fields)         
723        else :   
724            lastjuuid = self.genUUID()
725            lastjdn = "cn=%s,%s" % (lastjuuid, self.info["lastjobbase"])
726            fields = {
727                       "objectClass" : ["pykotaObject", "pykotaLastJob"],
728                       "cn" : lastjuuid,
729                       "pykotaPrinterName" : printer.Name,
730                       "pykotaLastJobIdent" : uuid,
731                     } 
732            self.doAdd(lastjdn, fields)         
733           
734    def writeUserPQuotaLimits(self, userpquota, softlimit, hardlimit) :
735        """Sets soft and hard limits for a user quota."""
736        fields = { 
737                   "pykotaSoftLimit" : str(softlimit),
738                   "pykotaHardLimit" : str(hardlimit),
739                 }
740        self.doModify(userpquota.ident, fields)
741       
742    def writeGroupPQuotaLimits(self, grouppquota, softlimit, hardlimit) :
743        """Sets soft and hard limits for a group quota on a specific printer."""
744        fields = { 
745                   "pykotaSoftLimit" : str(softlimit),
746                   "pykotaHardLimit" : str(hardlimit),
747                 }
748        self.doModify(grouppquota.ident, fields)
749           
750    def deleteUser(self, user) :   
751        """Completely deletes an user from the Quota Storage."""
752        # TODO : What should we do if we delete the last person who used a given printer ?
753        # TODO : we can't reassign the last job to the previous one, because next user would be
754        # TODO : incorrectly charged (overcharged).
755        result = self.doSearch("(&(objectClass=pykotaLastJob)(pykotaUserName=%s))" % user.Name, base=self.info["lastjobbase"])
756        for (ident, fields) in result :
757            self.doDelete(ident)
758        result = self.doSearch("(&(objectClass=pykotaJob)(pykotaUserName=%s))" % user.Name, base=self.info["jobbase"])
759        for (ident, fields) in result :
760            self.doDelete(ident)
761        result = self.doSearch("(&(objectClass=pykotaUserPQuota)(pykotaUserName=%s))" % user.Name, ["pykotaUserName"], base=self.info["userquotabase"])
762        for (ident, fields) in result :
763            self.doDelete(ident)
764        result = self.doSearch("objectClass=pykotaAccount", None, base=user.ident, scope=ldap.SCOPE_BASE)   
765        if result :
766            fields = result[0][1]
767            for k in fields.keys() :
768                if k.startswith("pykota") :
769                    del fields[k]
770                elif k.lower() == "objectclass" :   
771                    todelete = []
772                    for i in range(len(fields[k])) :
773                        if fields[k][i].startswith("pykota") : 
774                            todelete.append(i)
775                    todelete.sort()       
776                    todelete.reverse()
777                    for i in todelete :
778                        del fields[k][i]
779            if fields.get("objectClass") or fields.get("objectclass") :
780                self.doModify(user.ident, fields, ignoreold=0)       
781            else :   
782                self.doDelete(user.ident)
783        result = self.doSearch("(&(objectClass=pykotaAccountBalance)(pykotaUserName=%s))" % user.Name, ["pykotaUserName"], base=self.info["balancebase"])
784        for (ident, fields) in result :
785            self.doDelete(ident)
786       
787    def deleteGroup(self, group) :   
788        """Completely deletes a group from the Quota Storage."""
789        result = self.doSearch("(&(objectClass=pykotaGroupPQuota)(pykotaGroupName=%s))" % group.Name, ["pykotaGroupName"], base=self.info["groupquotabase"])
790        for (ident, fields) in result :
791            self.doDelete(ident)
792        result = self.doSearch("objectClass=pykotaGroup", None, base=group.ident, scope=ldap.SCOPE_BASE)   
793        if result :
794            fields = result[0][1]
795            for k in fields.keys() :
796                if k.startswith("pykota") :
797                    del fields[k]
798                elif k.lower() == "objectclass" :   
799                    todelete = []
800                    for i in range(len(fields[k])) :
801                        if fields[k][i].startswith("pykota") : 
802                            todelete.append(i)
803                    todelete.sort()       
804                    todelete.reverse()
805                    for i in todelete :
806                        del fields[k][i]
807            if fields.get("objectClass") or fields.get("objectclass") :
808                self.doModify(group.ident, fields, ignoreold=0)       
809            else :   
810                self.doDelete(group.ident)
811           
Note: See TracBrowser for help on using the browser.