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

Revision 1149, 37.6 kB (checked in by jalet, 21 years ago)

Job history can be disabled.
Some typos in README.
More messages in setup script.

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