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

Revision 1240, 41.0 kB (checked in by uid67467, 20 years ago)

Should be ok now.

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