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

Revision 1203, 39.7 kB (checked in by jalet, 20 years ago)

Job price added to history

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