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

Revision 1228, 40.2 kB (checked in by jalet, 20 years ago)

Don't try to retrieve the user print quota information if current printer
doesn't exist.

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