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

Revision 1259, 42.1 kB (checked in by jalet, 20 years ago)

Additionnal check to not create a circular printers group.

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